"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import {
  ArrowUpCircleIcon,
  Building2,
  CreditCard,
  LayoutDashboard,
  LogOut,
  Mail,
  Package,
  Plug,
  ScrollText,
  Settings,
  Shield,
} from "lucide-react";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarProvider,
  SidebarTrigger,
} from "@/components/ui/sidebar";
import { Separator } from "@/components/ui/separator";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  apiFetch,
  clearAccessToken,
  getAccessToken,
  hasAccessToken,
  isSessionExpiredError,
  logout,
  onSessionExpired,
} from "@/lib/api";
import { formatRole } from "@/lib/roles";
import { SessionExpiredDialog } from "@/components/layout/SessionExpiredDialog";

const navMain = [
  { href: "/admin/dashboard", label: "Dashboard", icon: LayoutDashboard },
  { href: "/admin/customers", label: "Customers", icon: Building2 },
  { href: "/admin/plans", label: "Plans", icon: Package },
  { href: "/admin/subscriptions", label: "Subscriptions", icon: CreditCard },
];

const navOps = [
  { href: "/admin/integrations", label: "MyGeotab", icon: Plug },
  { href: "/admin/addin-status", label: "Add-in status", icon: Shield },
  { href: "/admin/email-templates", label: "Email templates", icon: Mail },
  { href: "/admin/audit", label: "Audit logs", icon: ScrollText },
  { href: "/admin/settings", label: "Settings", icon: Settings },
];

function titleFromPath(pathname: string) {
  const all = [...navMain, ...navOps];
  const match = all.find((item) => pathname === item.href || pathname.startsWith(`${item.href}/`));
  return match?.label ?? "Dashboard";
}

export function AdminAppShell({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const [ready, setReady] = useState(false);
  const [sessionExpired, setSessionExpired] = useState(false);
  const [userEmail, setUserEmail] = useState("admin@cleral.local");
  const [userRole, setUserRole] = useState("SUPER_ADMIN");

  useEffect(() => onSessionExpired(() => setSessionExpired(true)), []);

  useEffect(() => {
    const token = getAccessToken();
    if (!token) {
      if (hasAccessToken("customer")) {
        router.replace("/dashboard");
        return;
      }
      clearAccessToken();
      router.replace("/admin/login");
      return;
    }
    apiFetch<{ user: { role: string; email?: string } }>("/auth/me")
      .then((me) => {
        if (me.user.role === "CUSTOMER_ADMIN") {
          router.replace("/dashboard");
          return;
        }
        if (me.user.role !== "SUPER_ADMIN") {
          clearAccessToken();
          router.replace("/admin/login");
          return;
        }
        setUserRole(me.user.role);
        if (me.user.email) setUserEmail(me.user.email);
        setReady(true);
      })
      .catch((err) => {
        if (isSessionExpiredError(err)) return;
        clearAccessToken();
        router.replace("/admin/login");
      });
  }, [router]);

  if (!ready) {
    return (
      <>
        <div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
          Verifying admin session…
        </div>
        <SessionExpiredDialog open={sessionExpired} />
      </>
    );
  }

  return (
    <>
      <SidebarProvider>
        <Sidebar collapsible="offcanvas" variant="inset">
          <SidebarHeader>
            <SidebarMenu>
              <SidebarMenuItem>
                <SidebarMenuButton asChild className="data-[slot=sidebar-menu-button]:!p-1.5">
                  <Link href="/admin/dashboard">
                    <ArrowUpCircleIcon className="h-5 w-5" />
                    <span className="text-base font-semibold">CLERAL Admin</span>
                  </Link>
                </SidebarMenuButton>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarHeader>
          <SidebarContent>
            <SidebarGroup>
              <SidebarGroupLabel>Home</SidebarGroupLabel>
              <SidebarGroupContent>
                <SidebarMenu>
                  {navMain.map(({ href, label, icon: Icon }) => {
                    const active = pathname === href || pathname.startsWith(`${href}/`);
                    return (
                      <SidebarMenuItem key={href}>
                        <SidebarMenuButton asChild isActive={active} tooltip={label}>
                          <Link href={href}>
                            <Icon />
                            <span>{label}</span>
                          </Link>
                        </SidebarMenuButton>
                      </SidebarMenuItem>
                    );
                  })}
                </SidebarMenu>
              </SidebarGroupContent>
            </SidebarGroup>
            <SidebarGroup>
              <SidebarGroupLabel>Operations</SidebarGroupLabel>
              <SidebarGroupContent>
                <SidebarMenu>
                  {navOps.map(({ href, label, icon: Icon }) => {
                    const active = pathname === href || pathname.startsWith(`${href}/`);
                    return (
                      <SidebarMenuItem key={href}>
                        <SidebarMenuButton asChild isActive={active} tooltip={label}>
                          <Link href={href}>
                            <Icon />
                            <span>{label}</span>
                          </Link>
                        </SidebarMenuButton>
                      </SidebarMenuItem>
                    );
                  })}
                </SidebarMenu>
              </SidebarGroupContent>
            </SidebarGroup>
          </SidebarContent>
          <SidebarFooter>
            <SidebarMenu>
              <SidebarMenuItem>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <SidebarMenuButton
                      size="lg"
                      className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
                    >
                      <Avatar className="h-8 w-8 rounded-lg">
                        <AvatarFallback className="rounded-lg">SA</AvatarFallback>
                      </Avatar>
                      <div className="grid flex-1 text-left text-sm leading-tight">
                        <span className="truncate font-medium">{formatRole(userRole)}</span>
                        <span className="truncate text-xs text-muted-foreground">{userEmail}</span>
                      </div>
                    </SidebarMenuButton>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent
                    className="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg"
                    side="right"
                    align="end"
                    sideOffset={4}
                  >
                    <DropdownMenuLabel>{formatRole(userRole)}</DropdownMenuLabel>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem asChild>
                      <Link href="/admin/settings">
                        <Settings className="mr-2 h-4 w-4" />
                        Settings
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      onClick={async () => {
                        await logout();
                        router.replace("/admin/login");
                      }}
                    >
                      <LogOut className="mr-2 h-4 w-4" />
                      Sign out
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarFooter>
        </Sidebar>
        <SidebarInset>
          <header className="flex h-12 shrink-0 items-center gap-2 border-b px-4 lg:px-6">
            <SidebarTrigger className="-ml-1" />
            <Separator orientation="vertical" className="mr-2 h-4" />
            <h1 className="text-base font-medium">{titleFromPath(pathname)}</h1>
          </header>
          <div className="flex flex-1 flex-col p-4 md:p-6">{children}</div>
        </SidebarInset>
      </SidebarProvider>
      <SessionExpiredDialog open={sessionExpired} />
    </>
  );
}
