"use client";

import { useQuery } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { RouteProgress } from "@/components/RouteProgress";
import { useMe } from "@/hooks/useMe";
import { LoadingState, ErrorState } from "@/src/shared/ui";
import { AccountingShell } from "@/src/modules/accounting/components/AccountingShell";
import { accountingApi } from "@/src/modules/accounting/services/accounting-api";

/** Prefetch shared accounting lookups so sidebar hops skip cold API waits. */
function useWarmAccountingCache(tenantId: string | null) {
  useQuery({
    queryKey: ["accounting", tenantId, "accounts"],
    queryFn: () => accountingApi.accounts.list(tenantId!),
    enabled: !!tenantId,
    staleTime: 60_000,
  });
  useQuery({
    queryKey: ["accounting", tenantId, "fiscal-periods"],
    queryFn: () => accountingApi.fiscal.listPeriods(tenantId!),
    enabled: !!tenantId,
    staleTime: 60_000,
  });
  useQuery({
    queryKey: ["accounting", tenantId, "posting-policy"],
    queryFn: () => accountingApi.setup.getPostingPolicy(tenantId!),
    enabled: !!tenantId,
    staleTime: 60_000,
  });
}

export function AccountingLayoutGate({ children }: { children: React.ReactNode }) {
  const { me, loading, error, reload } = useMe();
  const router = useRouter();
  const tenantId = me?.current_tenant_id ?? null;
  useWarmAccountingCache(tenantId);

  useEffect(() => {
    if (loading) return;
    if (me?.onboarding_required) router.replace("/onboarding");
  }, [me, loading, router]);

  if (loading && !me) return <LoadingState label="در حال آماده‌سازی ماژول حسابداری…" />;
  if (error && !me) return <ErrorState message={error} onRetry={reload} />;
  if (!loading && !me?.current_tenant_id) {
    return (
      <ErrorState message="برای استفاده از حسابداری باید یک workspace فعال داشته باشید." />
    );
  }
  if (!me?.current_tenant_id) {
    return <LoadingState label="در حال آماده‌سازی ماژول حسابداری…" />;
  }

  return (
    <>
      <RouteProgress />
      <AccountingShell>{children}</AccountingShell>
    </>
  );
}
