"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { useDashboard } from "@/hooks/useDashboard";
import { useLogout } from "@/hooks/useLogout";
import { ApiError } from "@/hooks/api-error";
import { clearStoredUser, getStoredUser, initialsFrom } from "@/lib/auth-user";
import { Sidebar } from "@/app/components/dashboard/Sidebar";
import { TopHeader } from "@/app/components/dashboard/TopHeader";
import { Toast } from "@/app/components/dashboard/parts";
import { AddVehicleModal } from "@/app/components/dashboard/AddVehicleModal";
import { AddEmergencyContactModal } from "@/app/components/dashboard/AddEmergencyContactModal";
import { ScanVehicleModal } from "@/app/components/dashboard/ScanVehicleModal";
import { VoiceCallModal } from "@/app/components/dashboard/VoiceCallModal";
import { DashboardProvider } from "@/app/components/dashboard/context";
import type { VoiceCallTarget } from "@/hooks/useVoiceCall";

/** `fleet-50` -> `Fleet 50`, for a plan with no name snapshotted yet. */
function titleCasePlan(slug: string): string {
  return slug
    .split(/[-_]/)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");
}

// Read a /dashboard?qr=<id> deep-link value (client-only; null on the server).
// Used to pre-open the scanner as if the QR had already been scanned.
function readDeepLinkQr(): string | null {
  if (typeof window === "undefined") return null;
  const qr = new URLSearchParams(window.location.search).get("qr")?.trim();
  return qr ? qr : null;
}

// Shared shell for every authenticated section. The 10 sidebar entries are now
// real routes (app/(app)/<segment>/page.tsx); this layout persists across them,
// holding the single dashboard query, the sidebar/header chrome, the add-vehicle
// modal and the toast. Section pages read data + actions via DashboardProvider.
export default function AppLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const queryClient = useQueryClient();
  const { data, isLoading, isError, error, refetch } = useDashboard();
  const logout = useLogout();

  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [addVehicleOpen, setAddVehicleOpen] = useState(false);
  const [addContactOpen, setAddContactOpen] = useState(false);
  // Seeded once from a /dashboard?qr=<id> deep link (lazy init, not an effect, so
  // there's no setState-in-effect cascade and no hydration flip mid-render).
  const [scanOpen, setScanOpen] = useState<boolean>(() => readDeepLinkQr() !== null);
  const [scanInitialQr, setScanInitialQr] = useState<string | null>(() =>
    readDeepLinkQr(),
  );
  const [callTarget, setCallTarget] = useState<VoiceCallTarget | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const noticeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  // The /dashboard payload has no email; surface the one cached at login (if any).
  const [email] = useState<string | undefined>(() => getStoredUser()?.email);

  useEffect(() => {
    if (isError && error instanceof ApiError && error.code === 401) {
      router.replace("/login");
    }
  }, [isError, error, router]);

  useEffect(
    () => () => {
      if (noticeTimer.current) clearTimeout(noticeTimer.current);
    },
    [],
  );

  // The ?qr= value was consumed by the lazy state above; strip it from the URL
  // post-mount so a refresh/back doesn't re-trigger the scan and the link stays
  // clean. Side-effect only (no setState) — safe inside an effect.
  useEffect(() => {
    const url = new URL(window.location.href);
    if (!url.searchParams.has("qr")) return;
    url.searchParams.delete("qr");
    window.history.replaceState(null, "", url.pathname + url.search + url.hash);
  }, []);

  function showNotice(message: string) {
    setNotice(message);
    if (noticeTimer.current) clearTimeout(noticeTimer.current);
    noticeTimer.current = setTimeout(() => setNotice(null), 3600);
  }

  function handleLogout() {
    logout.mutate(undefined, {
      onSettled: () => {
        clearStoredUser();
        queryClient.removeQueries({ queryKey: ["dashboard"] });
        router.replace("/login");
      },
    });
  }

  function handleAction(action: string) {
    switch (action) {
      case "generate-qr":
        router.push("/qr-codes");
        break;
      case "view-requests":
        router.push("/requests");
        break;
      case "manage-vehicle":
        router.push("/vehicles");
        break;
      case "manage-subscription":
      case "upgrade":
        router.push("/billing");
        break;
      case "manage-contacts":
        router.push("/emergency");
        break;
      case "view-notifications":
        router.push("/notifications");
        break;
      case "profile":
        router.push("/settings");
        break;
      case "scan":
        setScanInitialQr(null);
        setScanOpen(true);
        break;
      case "contact_owner":
        showNotice("Contacting the owner is available in the VehCall mobile app.");
        break;
      case "add":
        setAddVehicleOpen(true);
        break;
      case "add-contact":
        setAddContactOpen(true);
        break;
      case "share":
        showNotice("QR link ready to share — your phone number stays private.");
        break;
      case "download":
        showNotice("QR image saved to your device.");
        break;
      case "messages":
        showNotice("No new messages.");
        break;
      default:
        showNotice("This action opens in the VehCall app.");
        break;
    }
  }

  if (isLoading) return <DashboardSkeleton />;
  if (isError && error instanceof ApiError && error.code === 401) {
    return <DashboardSkeleton />;
  }
  if (isError || !data) {
    return (
      <main className="flex min-h-svh items-center justify-center px-5">
        <div className="glass w-full max-w-sm rounded-3xl p-8 text-center">
          <h2 className="text-lg font-semibold text-white">
            Couldn&apos;t load your dashboard
          </h2>
          <p className="mt-2 text-sm text-white/55">
            {error?.message ?? "Check your connection and try again."}
          </p>
          <button
            type="button"
            onClick={() => refetch()}
            className="btn-primary mt-6 w-full text-sm"
          >
            Retry
          </button>
        </div>
      </main>
    );
  }

  const name = data.user.name;
  const initials = initialsFrom(name);
  // The plan badge in the sidebar/topbar. Plans are admin-defined, so use the
  // name the API reports — the old `isPro ? "Premium" : "Free"` could only ever
  // print those two words, whatever plan the user was actually on.
  const planLabel =
    data.subscription.planName ?? titleCasePlan(data.subscription.plan);

  return (
    <DashboardProvider
      value={{
        data,
        onAction: handleAction,
        name,
        email,
        initials,
        loggingOut: logout.isPending,
        onLogout: handleLogout,
      }}
    >
      <div className="min-h-svh">
        <Sidebar
          open={sidebarOpen}
          onClose={() => setSidebarOpen(false)}
          onNavigate={() => setSidebarOpen(false)}
          plan={planLabel}
          vehiclesUsed={data.subscription.vehiclesUsed}
          vehiclesTotal={data.subscription.vehiclesTotal}
        />

        <div className="lg:pl-64">
          <TopHeader
            name={name}
            initials={initials}
            unread={data.unreadCount}
            plan={planLabel}
            onMenu={() => setSidebarOpen(true)}
            onAction={handleAction}
          />

          <main className="mx-auto max-w-[1400px] px-4 py-6 sm:px-6 lg:px-8">
            {children}
          </main>
        </div>

        {addVehicleOpen && (
          <AddVehicleModal
            onClose={() => setAddVehicleOpen(false)}
            onSuccess={(vehicleNumber) => {
              setAddVehicleOpen(false);
              queryClient.invalidateQueries({ queryKey: ["vehicles"] });
              queryClient.invalidateQueries({ queryKey: ["dashboard"] });
              showNotice(`${vehicleNumber} added — generating its QR code.`);
            }}
          />
        )}

        {addContactOpen && (
          <AddEmergencyContactModal
            defaultPriority={data.emergencyContacts.length}
            onClose={() => setAddContactOpen(false)}
            onSuccess={(contactName) => {
              setAddContactOpen(false);
              queryClient.invalidateQueries({ queryKey: ["emergency-contacts"] });
              queryClient.invalidateQueries({ queryKey: ["dashboard"] });
              showNotice(`${contactName} added to your emergency contacts.`);
            }}
          />
        )}

        {scanOpen && (
          <ScanVehicleModal
            initialQrCodeId={scanInitialQr}
            onClose={() => {
              setScanOpen(false);
              setScanInitialQr(null);
            }}
            onContact={({ vehicleNumber, vehicleId, qrCodeId, method }) => {
              setScanOpen(false);
              setScanInitialQr(null);
              if (method === "call") {
                setCallTarget({
                  vehicleId,
                  vehicleNumber,
                  qrCodeId: qrCodeId ?? undefined,
                });
              } else {
                showNotice(
                  `Opening a private WhatsApp request to the owner of ${vehicleNumber}.`,
                );
              }
            }}
          />
        )}

        {callTarget && (
          <VoiceCallModal
            key={callTarget.vehicleId}
            target={callTarget}
            onClose={() => setCallTarget(null)}
          />
        )}

        <Toast message={notice} />
      </div>
    </DashboardProvider>
  );
}

function DashboardSkeleton() {
  return (
    <div className="min-h-svh lg:pl-64">
      <div className="fixed inset-y-0 left-0 hidden w-64 border-r border-white/8 bg-surface/95 lg:block" />
      <div className="h-[72px] border-b border-white/8" />
      <div className="mx-auto max-w-[1400px] animate-pulse space-y-6 px-4 py-6 sm:px-6 lg:px-8">
        <div className="h-28 rounded-2xl bg-white/5" />
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="h-28 rounded-2xl bg-white/5" />
          ))}
        </div>
        <div className="grid gap-6 lg:grid-cols-3">
          <div className="h-72 rounded-2xl bg-white/5 lg:col-span-2" />
          <div className="h-72 rounded-2xl bg-white/5" />
        </div>
      </div>
    </div>
  );
}
