"use client";

import { useQuery } from "@tanstack/react-query";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState, type ReactNode } from "react";

import { FormAlert } from "@/components/forms/form-field";
import { GlobalBanners } from "@/components/layout/global-banners";
import { PageHeaderProvider } from "@/components/layout/page-header";
import { Sidebar } from "@/components/layout/sidebar";
import { Topbar } from "@/components/layout/topbar";
import { LoadingScreen, SessionUnavailableScreen } from "@/components/loading-screen";
import { PageTransition } from "@/components/motion/page-transition";
import { Drawer } from "@/components/ui/overlay";
import { api } from "@/lib/api-client";
import { useAuth } from "@/lib/auth";
import { useSidebarCollapsed } from "@/lib/ui-prefs";
import { cn } from "@/lib/utils";
import { dashboardSummarySchema, type AttentionItem } from "@/lib/dashboard";
import { queryKeys } from "@/lib/query-keys";
import { usePermission } from "@/hooks/use-permission";
import type { MeResponse } from "@/shared/types";

interface WalletView {
  balanceMinor: number;
  currency: string;
  lowBalance: boolean;
  provider: "manual" | "stripe";
}

export function AppShell({ children }: { children: ReactNode }) {
  const { status, tenant, permissions, retryAfterSeconds, retrySession } = useAuth();
  const pathname = usePathname();
  const router = useRouter();
  const canReadWallet = usePermission("wallet:read");
  const [menuOpen, setMenuOpen] = useState(false);
  const [collapsed, setCollapsed] = useSidebarCollapsed();
  const [offline, setOffline] = useState(false);
  const me = useQuery({
    queryKey: queryKeys.me,
    enabled: status === "authenticated",
    queryFn: () => api<MeResponse>("/auth/me"),
  });
  const wallet = useQuery({
    queryKey: queryKeys.wallet,
    enabled: status === "authenticated" && canReadWallet,
    queryFn: () => api<WalletView>("/wallet"),
  });
  const summary = useQuery({
    queryKey: queryKeys.dashboard(30),
    enabled: status === "authenticated",
    queryFn: async () =>
      dashboardSummarySchema.parse(await api("/dashboard/summary?range=30")),
  });

  useEffect(() => {
    if (status === "anonymous") {
      const next = `${window.location.pathname}${window.location.search}`;
      router.replace(`/login?next=${encodeURIComponent(next)}`);
    }
  }, [status, router]);

  useEffect(() => {
    const update = () => setOffline(!window.navigator.onLine);
    update();
    window.addEventListener("online", update);
    window.addEventListener("offline", update);
    return () => {
      window.removeEventListener("online", update);
      window.removeEventListener("offline", update);
    };
  }, []);

  if (status === "unavailable") return <SessionUnavailableScreen retryAfterSeconds={retryAfterSeconds} onRetry={retrySession} />;
  if (status !== "authenticated" || tenant === null) return <LoadingScreen />;
  const balanceMinor = wallet.data?.balanceMinor ?? me.data?.wallet?.balanceMinor ?? 0;
  const currency = wallet.data?.currency ?? me.data?.wallet?.currency ?? tenant.currency;
  const lowBalance = wallet.data?.lowBalance === true;
  const notifications: AttentionItem[] = summary.data?.attention ?? [];
  const suspended = tenant.status === "SUSPENDED";
  const tenantName = tenant.brandName ?? tenant.name;
  const exceptionCount = notifications.filter(
    (item) => item.type === "exception",
  ).length;
  const badges: Record<string, number> =
    exceptionCount > 0 ? { "/shipments": exceptionCount } : {};
  return (
    <PageHeaderProvider>
      <div className="min-h-screen bg-background text-foreground">
        <aside
          className={cn(
            "fixed inset-y-0 left-0 z-40 hidden border-r border-border bg-surface transition-[width] duration-200 ease-brand lg:block",
            collapsed ? "w-[72px]" : "w-[264px]",
          )}
        >
          <Sidebar
            permissions={permissions}
            tenantName={tenantName}
            pathname={pathname}
            collapsed={collapsed}
            onToggleCollapsed={() => setCollapsed(!collapsed)}
            badges={badges}
          />
        </aside>
        <div
          className={cn(
            "transition-[padding] duration-200 ease-brand",
            collapsed ? "lg:pl-[72px]" : "lg:pl-[264px]",
          )}
        >
          <Topbar
            balanceMinor={balanceMinor}
            currency={currency}
            lowBalance={lowBalance}
            notifications={notifications}
            onOpenMenu={() => setMenuOpen(true)}
          />
          <Drawer
            open={menuOpen}
            title="Navigation"
            onClose={() => setMenuOpen(false)}
            className="p-0"
          >
            <Sidebar
              permissions={permissions}
              tenantName={tenantName}
              pathname={pathname}
              onNavigate={() => setMenuOpen(false)}
              badges={badges}
            />
          </Drawer>
          <main
            id="main"
            className="mx-auto w-full max-w-content px-4 pb-12 pt-4 md:px-8 md:pt-6"
          >
            {offline ? (
              <FormAlert
                tone="warning"
                className="mb-6"
                title="You are offline."
              >
                Actions will fail until the connection returns.
              </FormAlert>
            ) : null}
            <GlobalBanners lowBalance={lowBalance} suspended={suspended} />
            {suspended ? null : <PageTransition>{children}</PageTransition>}
          </main>
        </div>
      </div>
    </PageHeaderProvider>
  );
}
