"use client";

import * as React from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Building2Icon, ChevronsUpDownIcon, ClipboardListIcon, LogOutIcon } from "lucide-react";
import { useSessionExpiredRedirect } from "@/lib/useSessionExpired";
import { MedoraScope } from "@/components/design-system/medora-scope";
import { SidebarLogo } from "@/components/medora/sidebar-logo";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Separator } from "@/components/ui/separator";
import { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInset, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarProvider, SidebarRail, SidebarTrigger } from "@/components/ui/sidebar";
import { Toaster } from "@/components/ui/toast";
import { TooltipProvider } from "@/components/ui/tooltip";

/**
 * The SuperAdmin area's shell (plan O): the design's app shell (`AppShell.tsx`, design system → Layout patterns →
 * App shell) with the SuperAdmin's own two pages. It isn't AppShell itself because that one's menus follow a
 * pharmacy role's permissions, which a SuperAdmin doesn't have.
 */
const PAGES = [
    { href: "/admin/pharmacies", title: "Pharmacies", icon: Building2Icon },
    { href: "/admin/login-logs", title: "Login logs", icon: ClipboardListIcon },
];

type StoredUser = { name?: string; username?: string; email?: string; role?: string };
const initials = (n: string) => n.split(/\s+/).filter(Boolean).map((w) => w[0]).join("").slice(0, 2).toUpperCase() || "SA";

export function AdminClientLayout({ children }: { children: React.ReactNode }) {
    useSessionExpiredRedirect();
    const pathname = usePathname();
    const router = useRouter();
    const [user, setUser] = React.useState<StoredUser>({});

    React.useEffect(() => {
        try {
            setUser(JSON.parse(localStorage.getItem("user") || "{}"));
        } catch {
            /* each page sends a non-SuperAdmin to sign-in */
        }
    }, []);

    const active = PAGES.find((p) => pathname === p.href || pathname.startsWith(p.href + "/"));
    const name = user.name || user.username || "Super Admin";
    const signOut = () => {
        localStorage.removeItem("token");
        localStorage.removeItem("user");
        router.push("/login");
    };

    return (
        <div className="medora h-svh">
            <MedoraScope />
            <TooltipProvider>
                <Toaster>
                    <SidebarProvider className="h-svh min-h-0">
                        <Sidebar collapsible="icon">
                            <SidebarHeader className="items-center px-3 pt-4 pb-2">
                                <Link href="/admin/pharmacies" aria-label="Medora, go to Pharmacies">
                                    <SidebarLogo tone="light" className="group-data-[collapsible=icon]:hidden" />
                                    <SidebarLogo tone="light" symbol className="hidden group-data-[collapsible=icon]:block" />
                                </Link>
                            </SidebarHeader>
                            <SidebarContent className="gap-0">
                                <SidebarGroup className="py-1">
                                    <SidebarGroupLabel>Platform</SidebarGroupLabel>
                                    <SidebarGroupContent>
                                        <SidebarMenu>
                                            {PAGES.map((p) => (
                                                <SidebarMenuItem key={p.href}>
                                                    <SidebarMenuButton tooltip={p.title} isActive={active?.href === p.href} render={<Link href={p.href} />}>
                                                        <p.icon />
                                                        <span>{p.title}</span>
                                                    </SidebarMenuButton>
                                                </SidebarMenuItem>
                                            ))}
                                        </SidebarMenu>
                                    </SidebarGroupContent>
                                </SidebarGroup>
                            </SidebarContent>
                            <SidebarFooter className="border-t border-sidebar-border">
                                <SidebarMenu>
                                    <SidebarMenuItem>
                                        <DropdownMenu>
                                            <DropdownMenuTrigger render={<SidebarMenuButton size="lg" className="h-10" />}>
                                                <Avatar className="size-7">
                                                    <AvatarFallback>{initials(name)}</AvatarFallback>
                                                </Avatar>
                                                <div className="grid flex-1 text-left leading-tight">
                                                    <span className="truncate text-sm font-medium">{name}</span>
                                                    <span className="truncate text-xs text-(--sidebar-muted)">SuperAdmin</span>
                                                </div>
                                                <ChevronsUpDownIcon className="ml-auto size-4" />
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent side="right" align="end" className="min-w-48">
                                                {user.email ? (
                                                    <DropdownMenuGroup>
                                                        <DropdownMenuLabel>{user.email}</DropdownMenuLabel>
                                                    </DropdownMenuGroup>
                                                ) : null}
                                                {user.email ? <DropdownMenuSeparator /> : null}
                                                <DropdownMenuItem onClick={signOut}>
                                                    <LogOutIcon /> Sign out
                                                </DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </SidebarMenuItem>
                                </SidebarMenu>
                            </SidebarFooter>
                            <SidebarRail />
                        </Sidebar>
                        <SidebarInset className="min-w-0 overflow-hidden bg-muted/40">
                            <header className="flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-4">
                                <SidebarTrigger className="-ml-1" />
                                <Separator orientation="vertical" className="h-5" />
                                <Breadcrumb>
                                    <BreadcrumbList>
                                        <BreadcrumbItem>
                                            <BreadcrumbLink render={<Link href="/admin/pharmacies" />}>Medora platform</BreadcrumbLink>
                                        </BreadcrumbItem>
                                        {active ? (
                                            <>
                                                <BreadcrumbSeparator />
                                                <BreadcrumbItem>
                                                    <BreadcrumbPage>{active.title}</BreadcrumbPage>
                                                </BreadcrumbItem>
                                            </>
                                        ) : null}
                                    </BreadcrumbList>
                                </Breadcrumb>
                            </header>
                            <main className="min-h-0 flex-1 overflow-y-auto p-4 md:p-6">{children}</main>
                        </SidebarInset>
                    </SidebarProvider>
                </Toaster>
            </TooltipProvider>
        </div>
    );
}
