import { createFileRoute, Link, Outlet, redirect, useNavigate, useRouterState } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { supabaseExt } from "@/integrations/external-supabase/client";
import { checkIsAdmin } from "@/lib/admin.functions";
import { Logo } from "@/components/site/Logo";
import { Button } from "@/components/ui/button";
import { LayoutDashboard, Package, ShoppingBag, Users, Settings, LogOut, Menu } from "lucide-react";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/admin")({
  head: () => ({ meta: [{ title: "Admin — দেশি কোর্স" }] }),
  component: AdminLayout,
});

const nav: Array<{ to: string; label: string; icon: typeof LayoutDashboard; exact?: boolean }> = [
  { to: "/admin", label: "Dashboard", icon: LayoutDashboard, exact: true },
  { to: "/admin/orders", label: "Orders", icon: ShoppingBag },
  { to: "/admin/packages", label: "Packages", icon: Package },
  { to: "/admin/customers", label: "Customers", icon: Users },
  { to: "/admin/settings", label: "Settings", icon: Settings },
];

function AdminLayout() {
  const navigate = useNavigate();
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const [authState, setAuthState] = useState<"loading" | "ok" | "no-session" | "no-admin">("loading");
  const [open, setOpen] = useState(false);
  const check = useServerFn(checkIsAdmin);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const { data } = await supabaseExt.auth.getSession();
      if (!data.session) { if (!cancelled) setAuthState("no-session"); return; }
      try {
        const r = await check();
        if (cancelled) return;
        setAuthState(r.isAdmin ? "ok" : "no-admin");
      } catch {
        if (!cancelled) setAuthState("no-admin");
      }
    })();
    return () => { cancelled = true; };
  }, [check]);

  useEffect(() => {
    if (authState === "no-session") navigate({ to: "/login" });
  }, [authState, navigate]);

  const signOut = async () => {
    await supabaseExt.auth.signOut();
    navigate({ to: "/login" });
  };

  if (authState === "loading") {
    return <div className="min-h-screen flex items-center justify-center text-muted-foreground">Loading admin...</div>;
  }
  if (authState === "no-admin") {
    return (
      <div className="min-h-screen flex items-center justify-center px-4">
        <div className="text-center max-w-sm">
          <h1 className="text-2xl font-bold">Access denied</h1>
          <p className="mt-2 text-muted-foreground text-sm">You don't have admin privileges.</p>
          <div className="mt-6 flex gap-2 justify-center">
            <Button onClick={signOut} variant="outline">Sign out</Button>
            <Button asChild><Link to="/">Go home</Link></Button>
          </div>
        </div>
      </div>
    );
  }
  if (authState !== "ok") return null;

  return (
    <div className="min-h-screen flex bg-muted/20">
      <aside className={cn(
        "fixed inset-y-0 left-0 z-40 w-64 bg-card border-r flex flex-col transition-transform md:translate-x-0",
        open ? "translate-x-0" : "-translate-x-full",
      )}>
        <div className="h-16 border-b flex items-center px-6"><Logo /></div>
        <nav className="flex-1 p-3 space-y-1">
          {nav.map((n) => {
            const active = n.exact ? pathname === n.to : pathname.startsWith(n.to);
            const Icon = n.icon;
            return (
              <Link
                key={n.to}
                to={n.to as any}
                onClick={() => setOpen(false)}
                className={cn(
                  "flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition-colors",
                  active ? "bg-primary text-primary-foreground" : "text-foreground hover:bg-muted",
                )}
              >
                <Icon className="w-4 h-4" />
                {n.label}
              </Link>
            );
          })}
        </nav>
        <div className="p-3 border-t">
          <Button onClick={signOut} variant="ghost" className="w-full justify-start">
            <LogOut className="w-4 h-4" /> Sign out
          </Button>
        </div>
      </aside>
      <div className="flex-1 md:ml-64">
        <header className="h-16 border-b bg-card flex items-center px-4 md:px-8 sticky top-0 z-30">
          <button className="md:hidden mr-3" onClick={() => setOpen((o) => !o)}>
            <Menu className="w-5 h-5" />
          </button>
          <h1 className="font-semibold">Admin Dashboard</h1>
        </header>
        <main className="p-4 md:p-8">
          <Outlet />
        </main>
      </div>
    </div>
  );
}