import { LogOut, ShieldCheck } from "lucide-react";
import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router";
import { logoutAdmin } from "../firebase/auth";
import { sidebarNavigation } from "../theme/navigation";
import { Badge } from "@/src/components/ui/badge";
import { Button } from "@/src/components/ui/button";
import { Separator } from "@/src/components/ui/separator";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarProvider,
  SidebarRail,
  SidebarSeparator,
  SidebarTrigger,
} from "@/src/components/ui/sidebar"

const navigationSections = [
    {
        label: "Workspace",
        items: sidebarNavigation.filter((item) =>
            ["Overview", "Users", "Bathrooms"].includes(item.label)
        ),
    },
    {
        label: "Moderation",
        items: sidebarNavigation.filter((item) =>
            ["Reviews", "Feedback", "FAQs"].includes(item.label)
        ),
    },
    {
        label: "Engagement",
        items: sidebarNavigation.filter((item) =>
            ["Badges", "User Badges", "Notifications", "Subscriptions"].includes(item.label)
        ),
    },
    {
        label: "System",
        items: sidebarNavigation.filter((item) =>
            ["System Logs", "Admin Config"].includes(item.label)
        ),
    },
];

function getCurrentNavItem(pathname) {
    return [...sidebarNavigation]
        .sort((a, b) => b.path.length - a.path.length)
        .find((item) =>
            item.path === "/dashboard"
                ? pathname === "/dashboard"
                : pathname.startsWith(item.path)
        );
}

function SidebarNav() {
    const location = useRouterState({ select: (state) => state.location });
    
    return (
        <>
            {navigationSections.map((section) => (
                <SidebarGroup key={section.label} className="px-0 py-1">
                    <SidebarGroupLabel className="px-2 text-[11px] font-semibold uppercase tracking-widest text-poot-light">
                        {section.label}
                    </SidebarGroupLabel>
                    <SidebarGroupContent>
                        <SidebarMenu className="gap-1">
                            {section.items.map((item) => {
                                const Icon = item.icon;
                                const isActive = item.path === "/dashboard"
                                    ? location.pathname === "/dashboard"
                                    : location.pathname.startsWith(item.path);

                                return (
                                    <SidebarMenuItem key={item.path}>
                                        <SidebarMenuButton
                                            asChild
                                            isActive={isActive}
                                            tooltip={item.label}
                                            className="h-9 rounded-lg px-2.5 text-poot-muted data-[active=true]:bg-poot-primary data-[active=true]:text-white data-[active=true]:shadow-sm hover:bg-poot-primary/10 hover:text-poot-primary"
                                        >
                                            <Link
                                                to={item.path}
                                                activeOptions={{ exact: item.path === "/dashboard" }}
                                                activeProps={{
                                                    className: "font-medium",
                                                }}
                                            >
                                                <Icon size={17} />
                                                <span>{item.label}</span>
                                            </Link>
                                        </SidebarMenuButton>
                                    </SidebarMenuItem>
                                );
                            })}
                        </SidebarMenu>
                    </SidebarGroupContent>
                </SidebarGroup>
            ))}
        </>
    );
}

export default function AdminLayout() {
    const navigate = useNavigate();
    const location = useRouterState({ select: (state) => state.location });
    const currentItem = getCurrentNavItem(location.pathname);
    const CurrentIcon = currentItem?.icon ?? ShieldCheck;

    const handleLogout = async () => {
        await logoutAdmin();
        navigate({ to: "/login", replace: true });
    };

    return (
        <SidebarProvider>
            <div className="flex min-h-screen w-full bg-poot-bg text-poot-text">
                <Sidebar collapsible="icon" className="border-r border-poot-border bg-poot-surface/95">
                    <SidebarHeader className="border-b border-poot-border p-3">
                        <div className="flex min-h-12 items-center gap-3 rounded-xl bg-poot-primary/8 px-2.5 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0">
                            <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-poot-primary text-sm font-bold text-white shadow-sm">
                                P
                            </div>
                            <div className="min-w-0 group-data-[collapsible=icon]:hidden">
                                <p className="truncate font-heading text-sm font-bold text-poot-primary">
                                    Poot Admin
                                </p>

                            </div>
                        </div>
                    </SidebarHeader>
                    <SidebarContent className="px-2 py-3">
                        <SidebarNav />
                    </SidebarContent>
                    <SidebarSeparator />
                    <SidebarFooter className="p-3">
                        <div className="rounded-lg border border-poot-border bg-poot-bg/70 p-3 group-data-[collapsible=icon]:hidden">
                            <div className="mb-2 flex items-center justify-between gap-2">
                                <span className="text-xs font-semibold text-poot-muted">Environment</span>
                                <Badge variant="outline" className="border-poot-border text-poot-primary">
                                    v1.0.0
                                </Badge>
                            </div>
                            <p className="text-xs leading-relaxed text-poot-light">
                                Authorized staff workspace
                            </p>
                        </div>
                        <Badge variant="outline" className="hidden justify-center group-data-[collapsible=icon]:inline-flex">
                            v1
                        </Badge>
                    </SidebarFooter>
                    <SidebarRail />
                </Sidebar>

                <SidebarInset className="flex flex-col">
                    <header className="sticky top-0 z-30 border-b border-poot-border bg-poot-surface/90 backdrop-blur-xl">
                        <div className="flex min-h-16 w-full items-center justify-between gap-3 px-3 py-2 md:px-5">
                            <div className="flex min-w-0 items-center gap-3">
                                <SidebarTrigger className="text-poot-primary hover:bg-poot-primary/10" />
                                <Separator orientation="vertical" className="hidden h-6 sm:block" />
                                <div className="flex min-w-0 items-center gap-3">
                                    <div className="hidden size-9 shrink-0 items-center justify-center rounded-lg bg-poot-primary/10 text-poot-primary sm:flex">
                                        <CurrentIcon size={18} />
                                    </div>
                                    <div className="min-w-0">
                                        <p className="truncate text-sm font-semibold text-poot-text">
                                            {currentItem?.label ?? "Dashboard"}
                                        </p>
                                        <p className="hidden truncate text-xs text-poot-light sm:block">
                                            Internal dashboard for authorized staff
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={handleLogout}
                                className="gap-2 border-poot-border bg-poot-surface text-poot-muted hover:bg-poot-primary/10 hover:text-poot-primary"
                            >
                                <LogOut size={16} />
                                <span className="hidden sm:inline">Logout</span>
                            </Button>
                        </div>
                    </header>

                    <main className="flex-1 overflow-y-auto">
                        <div className="mx-auto w-full max-w-[1600px] p-3 md:p-5 lg:p-6">
                            <Outlet />
                        </div>
                    </main>
                </SidebarInset>
            </div>
        </SidebarProvider>
    );
}
