import { useState, useEffect, useRef } from "react";
import { Link, useLocation, Outlet } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { LayoutDashboard, Search, Activity, Settings, Sun, Moon, Laptop, Wrench, HelpCircle, Users, Bot, PanelLeft, PanelLeftClose, RefreshCw, Shield, ScrollText, Info, Plug } from "lucide-react";
import { cn } from "@/lib/utils";
import { humanizeSlug } from "@oak/ui/lib/utils";
import { useTheme } from "@oak/ui/components/theme-provider";
import { FontSelector } from "@oak/ui/components/ui/font-selector";
import { DensitySelector } from "@oak/ui/components/ui/density-selector";
import { usePowerState } from "@oak/ui/hooks/use-power-state";
import type { PowerState } from "@oak/ui/hooks/use-power-state";
import { useStatus } from "@/hooks/use-status";
import { useRestart } from "@/hooks/use-restart";
import { useChannel } from "@/hooks/use-channel";
import { AboutDialog } from "@/components/about/AboutDialog";
import { UpdateBanner } from "@/components/ui/update-banner";

import type { LucideIcon } from "lucide-react";

const SIDEBAR_COLLAPSED_KEY = "oak-ci-sidebar-collapsed";

const NavItem = ({ to, icon: Icon, label, active, collapsed }: { to: string; icon: LucideIcon; label: string; active: boolean; collapsed: boolean }) => (
    <Link
        to={to}
        title={collapsed ? label : undefined}
        className={cn(
            "flex items-center gap-3 px-3 py-2 rounded-md transition-colors text-sm font-medium",
            collapsed && "justify-center px-2",
            active
                ? "bg-primary text-primary-foreground"
                : "text-muted-foreground hover:bg-muted hover:text-foreground"
        )}
    >
        <Icon className="w-4 h-4 flex-shrink-0" />
        {!collapsed && <span>{label}</span>}
    </Link>
);

export function Layout() {
    const location = useLocation();
    const { setTheme, theme } = useTheme();
    const { data: status } = useStatus();
    const { restart, isRestarting } = useRestart();
    const { data: channelData } = useChannel();
    const [aboutOpen, setAboutOpen] = useState(false);
    const queryClient = useQueryClient();
    const { state: powerState, reportActivity } = usePowerState();
    const prevPowerStateRef = useRef<PowerState>(powerState);

    // Wake invalidation: refresh all queries when returning from hidden/deep_sleep
    useEffect(() => {
        const prev = prevPowerStateRef.current;
        prevPowerStateRef.current = powerState;

        if (powerState === "active" && (prev === "hidden" || prev === "deep_sleep")) {
            queryClient.invalidateQueries();
        }
    }, [powerState, queryClient]);

    // Daemon wake: if status shows daemon activity while user is idle/deep_sleep, wake up.
    // Skips "hidden" — no point waking polls the user can't see; wake invalidation
    // handles the refresh when the tab becomes visible again.
    useEffect(() => {
        if (powerState !== "active" && powerState !== "hidden") {
            const daemonBusy = status?.indexing || (status?.file_watcher?.pending_changes ?? 0) > 0;
            if (daemonBusy) {
                reportActivity();
            }
        }
    }, [powerState, status?.indexing, status?.file_watcher?.pending_changes, reportActivity]);

    const [collapsed, setCollapsed] = useState(() => {
        const saved = localStorage.getItem(SIDEBAR_COLLAPSED_KEY);
        return saved === "true";
    });

    useEffect(() => {
        localStorage.setItem(SIDEBAR_COLLAPSED_KEY, String(collapsed));
    }, [collapsed]);

    // Derive system health: green = running, yellow = indexing, red = team configured but disconnected
    const healthColor = !status
        ? "bg-gray-400"
        : status.team?.configured && !status.team?.connected
            ? "bg-red-500"
            : status.indexing
                ? "bg-yellow-500"
                : "bg-green-500";

    const projectSlug = status?.project_root
        ? status.project_root.split('/').pop()
        : null;

    const projectName = projectSlug ? humanizeSlug(projectSlug) : null;

    useEffect(() => {
        document.title = projectName ? `${projectName} — OAK Team` : "OAK Team";
    }, [projectName]);

    const navItems = [
        { to: "/", icon: LayoutDashboard, label: "Dashboard" },
        { to: "/search", icon: Search, label: "Search" },
        { to: "/activity", icon: Activity, label: "Activity" },
        { to: "/team", icon: Users, label: "Team" },
        { to: "/connect", icon: Plug, label: "Connect" },
        { to: "/agents", icon: Bot, label: "Agents" },
        { to: "/governance", icon: Shield, label: "Governance" },
        { to: "/config", icon: Settings, label: "Configuration" },
        { to: "/logs", icon: ScrollText, label: "Logs" },
        { to: "/devtools", icon: Wrench, label: "DevTools" },
        { to: "/help", icon: HelpCircle, label: "Help" },
    ];

    const toggleCollapse = () => setCollapsed(!collapsed);

    return (
        <div className="flex h-screen bg-background text-foreground overflow-hidden font-sans">
            <AboutDialog open={aboutOpen} onOpenChange={setAboutOpen} />
            {/* Sidebar */}
            <aside className={cn(
                "border-r flex flex-col transition-all duration-200",
                "bg-gradient-to-b from-card to-muted/40 dark:bg-card dark:from-card dark:to-card",
                collapsed ? "w-16" : "w-64"
            )}>
                <div className={cn("border-b", collapsed ? "p-3" : "p-6")}>
                    <div className={cn("flex items-center mb-3", collapsed ? "justify-center" : "gap-2")}>
                        <div className="w-8 h-8 flex items-center justify-center flex-shrink-0 relative">
                            <img src="/logo.png" alt="OAK" className="w-8 h-8 object-contain rounded-lg" />
                            <span
                                className={cn(
                                    "absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-card",
                                    healthColor
                                )}
                                title={!status ? "Loading" : healthColor === "bg-green-500" ? "Healthy" : healthColor === "bg-yellow-500" ? "Busy" : "Disconnected"}
                            />
                        </div>
                        {!collapsed && (
                            <div className="min-w-0">
                                <div className="flex items-center gap-2">
                                    <span className="font-bold text-lg tracking-tight truncate">{projectName ?? "OAK Team"}</span>
                                    {channelData?.current_channel === "beta" && (
                                        <span className="px-1.5 py-0.5 rounded-full text-xs font-semibold bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30 flex-shrink-0">
                                            Beta
                                        </span>
                                    )}
                                </div>
                                {projectSlug && (
                                    <span className="text-xs text-muted-foreground truncate block">{projectSlug}</span>
                                )}
                            </div>
                        )}
                    </div>
                </div>

                <nav className={cn("flex-1 space-y-1 overflow-y-auto", collapsed ? "p-2" : "p-4")}>
                    {navItems.map((item) => (
                        <NavItem
                            key={item.to}
                            {...item}
                            collapsed={collapsed}
                            active={location.pathname === item.to || (item.to !== "/" && location.pathname.startsWith(item.to))}
                        />
                    ))}
                </nav>

                <div className={cn("border-t", collapsed ? "p-2" : "p-4")}>
                    {/* About / Info button */}
                    <button
                        onClick={() => setAboutOpen(true)}
                        title="About OAK Team"
                        aria-label="About OAK Team"
                        className={cn(
                            "flex items-center gap-2 w-full px-3 py-2 rounded-md transition-colors text-sm font-medium text-muted-foreground hover:bg-muted hover:text-foreground mb-2",
                            collapsed && "justify-center px-2",
                        )}
                    >
                        <Info className="w-4 h-4 flex-shrink-0" />
                        {!collapsed && <span>About</span>}
                    </button>

                    {/* Restart daemon button */}
                    <button
                        onClick={restart}
                        disabled={isRestarting}
                        title="Restart Daemon"
                        aria-label="Restart Daemon"
                        className={cn(
                            "flex items-center gap-2 w-full px-3 py-2 rounded-md transition-colors text-sm font-medium text-muted-foreground hover:bg-muted hover:text-foreground mb-2",
                            collapsed && "justify-center px-2",
                            "disabled:opacity-50 disabled:cursor-not-allowed"
                        )}
                    >
                        <RefreshCw className={cn("w-4 h-4 flex-shrink-0", isRestarting && "animate-spin")} />
                        {!collapsed && <span>{isRestarting ? "Restarting..." : "Restart"}</span>}
                    </button>

                    {/* Theme switcher */}
                    <div className={cn(
                        "flex items-center rounded-md bg-muted/50 mb-2",
                        collapsed ? "flex-col gap-1 px-1 py-2" : "justify-between px-2 py-1"
                    )}>
                        <button
                            onClick={() => setTheme("light")}
                            title="Light theme"
                            aria-label="Light theme"
                            className={cn("p-1.5 rounded-sm transition-all", theme === "light" && "bg-background shadow-sm")}
                        >
                            <Sun className="w-4 h-4" />
                        </button>
                        <button
                            onClick={() => setTheme("system")}
                            title="System theme"
                            aria-label="System theme"
                            className={cn("p-1.5 rounded-sm transition-all", theme === "system" && "bg-background shadow-sm")}
                        >
                            <Laptop className="w-4 h-4" />
                        </button>
                        <button
                            onClick={() => setTheme("dark")}
                            title="Dark theme"
                            aria-label="Dark theme"
                            className={cn("p-1.5 rounded-sm transition-all", theme === "dark" && "bg-background shadow-sm")}
                        >
                            <Moon className="w-4 h-4" />
                        </button>
                    </div>

                    {/* Density selector */}
                    <DensitySelector collapsed={collapsed} />

                    {/* Font selector */}
                    <FontSelector collapsed={collapsed} />

                    {/* Collapse toggle */}
                    <button
                        onClick={toggleCollapse}
                        title={collapsed ? "Expand sidebar" : "Collapse sidebar"}
                        aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"}
                        className={cn(
                            "flex items-center gap-2 w-full px-3 py-2 rounded-md transition-colors text-sm font-medium text-muted-foreground hover:bg-muted hover:text-foreground",
                            collapsed && "justify-center px-2"
                        )}
                    >
                        {collapsed ? (
                            <PanelLeft className="w-4 h-4" />
                        ) : (
                            <>
                                <PanelLeftClose className="w-4 h-4" />
                                <span>Collapse</span>
                            </>
                        )}
                    </button>
                </div>
            </aside>

            {/* Main Content */}
            <main className="flex-1 flex flex-col overflow-hidden relative">
                <div className="flex-1 overflow-y-auto p-8 relative z-10">
                    <div className="max-w-6xl mx-auto">
                        {(status?.version?.update_available || status?.upgrade?.needed) && (
                            <UpdateBanner
                                version={status.version}
                                upgrade={status.upgrade}
                                cliCommand={status.cli_command}
                            />
                        )}
                        <Outlet />
                    </div>
                </div>

                {/* Background decorative elements (Glassmorphism effect backing) */}
                <div className="absolute top-0 left-0 w-full h-full pointer-events-none z-0 overflow-hidden">
                    <div className="absolute top-[-20%] right-[-10%] w-[500px] h-[500px] bg-primary/5 rounded-full blur-[100px]" />
                    <div className="absolute bottom-[-20%] left-[-10%] w-[600px] h-[600px] bg-blue-500/5 rounded-full blur-[120px]" />
                </div>
            </main>
        </div>
    );
}
