import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAuthStore } from '../features/auth/store/useAuthStore';
import axios from '../bootstrap';
import { timeAgo, timeUntil, compactTimeUntil } from '../utils/timeAgo';
import { useTimeTicker } from '../utils/useTimeTicker';
import { pathFromTab, tabFromPath, type PanelTabId } from '../navigation/panelRoutes';
import {
    LayoutDashboard,
    Globe,
    Key,
    Shield,
    Send,
    FileText,
    LogOut,
    Menu,
    X,
    User,
    Activity,
    AlertTriangle,
    ChevronRight,
    ShieldCheck,
    Package,
    Fingerprint,
    Settings,
} from 'lucide-react';

interface LayoutProps {
    children: React.ReactNode;
}

const navSections = [
    {
        label: 'Management',
        items: [
            { id: 'dashboard', name: 'SOC Overview',       icon: LayoutDashboard },
            { id: 'agents',    name: 'Websites',           icon: Globe },
            { id: 'keys',      name: 'Activation Keys',   icon: Key },
        ],
    },
    {
        label: 'Security',
        items: [
            { id: 'logs',        name: 'Security Events',     icon: FileText },
            { id: 'malware',     name: 'Malware Reports',     icon: AlertTriangle },
            { id: 'verified-safe', name: 'Verified Safe Files', icon: Fingerprint },
            { id: 'policies',    name: 'Policy Engine',       icon: Shield },
        ],
    },
    {
        label: 'Monitoring',
        items: [
            { id: 'performance', name: 'Performance Metrics', icon: Activity },
        ],
    },
    {
        label: 'System',
        items: [
            { id: 'telegram', name: 'Telegram Profiles', icon: Send },
            { id: 'plugin-releases', name: 'Plugin Releases', icon: Package },
            { id: 'security', name: 'Security Settings', icon: ShieldCheck },
            { id: 'settings', name: 'Settings', icon: Settings },
        ],
    },
];

export function DashboardLayout({ children }: LayoutProps) {
    const { user, logout } = useAuthStore();
    const location = useLocation();
    const navigate = useNavigate();
    const currentTab = tabFromPath(location.pathname);
    const setCurrentTab = (tab: string) => {
        navigate(pathFromTab(tab as PanelTabId));
    };
    const [sidebarOpen, setSidebarOpen] = useState(true);
    const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
    const [latestCheckInAt, setLatestCheckInAt] = useState<string | null>(null);
    const [nextExpectedHeartbeatAt, setNextExpectedHeartbeatAt] = useState<string | null>(null);
    const nowTick = useTimeTicker(15000);

    useEffect(() => {
        const fetchCheckIn = async () => {
            try {
                const response = await axios.get('/check-in-summary');
                setLatestCheckInAt(response.data.latest_check_in_at ?? null);
                setNextExpectedHeartbeatAt(response.data.next_expected_heartbeat_at ?? null);
            } catch {
                setLatestCheckInAt(null);
                setNextExpectedHeartbeatAt(null);
            }
        };

        fetchCheckIn();
        const timer = window.setInterval(fetchCheckIn, 15000);
        return () => window.clearInterval(timer);
    }, []);

    // Find the label for the current tab
    const currentItem = navSections.flatMap(s => s.items).find(i => i.id === currentTab);

    const SidebarContent = ({ isMobile = false }: { isMobile?: boolean }) => {
        const expanded = isMobile || sidebarOpen;
        return (
            <>
                {/* Logo */}
                <div className="h-14 flex items-center px-4 border-b border-slate-800/50 justify-between shrink-0">
                    <div className="flex items-center gap-2.5">
                        <div className="w-7 h-7 bg-rose-500/10 border border-rose-500/30 rounded-lg flex items-center justify-center shadow-inner shrink-0">
                            <span className="text-rose-500 text-xs font-black">M</span>
                        </div>
                        {expanded && (
                            <div>
                                <p className="font-extrabold text-xs tracking-widest text-white uppercase leading-none">Monster Guard</p>
                                <p className="text-[9px] text-slate-500 font-semibold tracking-wider uppercase mt-0.5">SOC Control Center</p>
                            </div>
                        )}
                    </div>
                    {isMobile && (
                        <button onClick={() => setMobileSidebarOpen(false)} className="p-1 rounded-lg border border-slate-800 text-slate-400 hover:text-slate-200">
                            <X className="w-4 h-4" />
                        </button>
                    )}
                </div>

                {/* Nav Sections */}
                <nav className="flex-1 px-3 py-4 space-y-5 overflow-y-auto">
                    {navSections.map((section) => (
                        <div key={section.label}>
                            {expanded && (
                                <p className="text-[9px] font-bold text-slate-600 uppercase tracking-widest px-2 mb-1.5">
                                    {section.label}
                                </p>
                            )}
                            <div className="space-y-0.5">
                                {section.items.map((item) => {
                                    const Icon = item.icon;
                                    const isActive = currentTab === item.id;
                                    return (
                                        <button
                                            key={item.id}
                                            onClick={() => {
                                                setCurrentTab(item.id);
                                                if (isMobile) setMobileSidebarOpen(false);
                                            }}
                                            title={!expanded ? item.name : undefined}
                                            className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${
                                                isActive
                                                    ? 'bg-rose-500/10 border border-rose-500/20 text-rose-400'
                                                    : 'border border-transparent text-slate-400 hover:text-slate-200 hover:bg-slate-800/40'
                                            }`}
                                        >
                                            <Icon className="w-4 h-4 shrink-0" />
                                            {expanded && <span className="truncate">{item.name}</span>}
                                            {expanded && isActive && <ChevronRight className="w-3 h-3 ml-auto shrink-0 text-rose-500/60" />}
                                        </button>
                                    );
                                })}
                            </div>
                        </div>
                    ))}
                </nav>

                {/* User */}
                <div className="p-3 border-t border-slate-800/50 shrink-0">
                    <div className={`flex items-center ${expanded ? 'justify-between' : 'justify-center'} gap-2`}>
                        {expanded && (
                            <div className="flex items-center gap-2 overflow-hidden">
                                <div className="w-8 h-8 rounded-lg bg-slate-800 border border-slate-700/60 flex items-center justify-center shrink-0">
                                    <User className="w-3.5 h-3.5 text-slate-300" />
                                </div>
                                <div className="overflow-hidden">
                                    <p className="text-xs font-semibold text-white truncate leading-none">{user?.name}</p>
                                    <p className="text-[10px] text-slate-500 mt-0.5">Administrator</p>
                                </div>
                            </div>
                        )}
                        <button
                            onClick={() => logout()}
                            className="p-2 rounded-xl border border-slate-800 text-slate-400 hover:text-rose-400 hover:bg-rose-500/10 hover:border-rose-500/20 transition-all shrink-0"
                            title="Sign Out"
                        >
                            <LogOut className="w-3.5 h-3.5" />
                        </button>
                    </div>
                </div>
            </>
        );
    };

    return (
        <div className="flex h-dvh overflow-hidden bg-slate-950 text-slate-100">

            {/* Mobile Backdrop */}
            {mobileSidebarOpen && (
                <div
                    className="fixed inset-0 bg-slate-950/80 backdrop-blur-sm z-30 md:hidden"
                    onClick={() => setMobileSidebarOpen(false)}
                />
            )}

            {/* Mobile Drawer */}
            <aside className={`fixed top-0 bottom-0 left-0 w-60 bg-slate-900 border-r border-slate-800 flex flex-col z-40 transition-transform duration-300 transform md:hidden ${
                mobileSidebarOpen ? 'translate-x-0' : '-translate-x-full'
            }`}>
                <SidebarContent isMobile={true} />
            </aside>

            {/* Desktop Sidebar */}
            <aside className={`hidden md:flex bg-slate-900/60 border-r border-slate-800/80 transition-all duration-300 flex-col z-20 ${
                sidebarOpen ? 'w-60' : 'w-[60px]'
            } shrink-0 backdrop-blur-xl`}>
                <SidebarContent isMobile={false} />
            </aside>

            {/* Main */}
            <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">

                {/* Header stays pinned while main scrolls (no fixed positioning on mobile) */}
                <header className="z-30 shrink-0 border-b border-slate-800/80 bg-slate-950/95 pt-[env(safe-area-inset-top,0px)] backdrop-blur-md">
                    <div className="flex h-12 items-center justify-between px-4">
                        <div className="flex items-center gap-3">
                            <button
                                onClick={() => setSidebarOpen(!sidebarOpen)}
                                className="hidden md:flex p-1.5 rounded-lg border border-slate-800 text-slate-500 hover:text-slate-200 hover:bg-slate-800/50 transition-all"
                            >
                                <Menu className="w-3.5 h-3.5" />
                            </button>
                            <button
                                onClick={() => setMobileSidebarOpen(!mobileSidebarOpen)}
                                className="flex md:hidden p-1.5 rounded-lg border border-slate-800 text-slate-500 hover:text-slate-200"
                            >
                                <Menu className="w-3.5 h-3.5" />
                            </button>
                            <div className="flex items-center gap-2">
                                <span className="text-[10px] text-slate-600 font-semibold uppercase tracking-widest hidden sm:block">SOC /</span>
                                <h2 className="text-sm font-bold text-white tracking-tight">
                                    {currentItem?.name || 'Dashboard'}
                                </h2>
                            </div>
                        </div>

                        <div className="flex items-center gap-2 sm:gap-3 min-w-0">
                            <span className="hidden sm:flex items-center gap-1.5 text-[10px] font-semibold text-emerald-400 bg-emerald-500/5 border border-emerald-500/10 px-2 py-1 rounded-full shrink-0">
                                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-ping" />
                                System OK
                            </span>

                            <span
                                className="flex items-center gap-1.5 text-[9px] sm:text-[10px] font-semibold text-emerald-400 bg-emerald-500/5 border border-emerald-500/10 px-2 py-1 rounded-full min-w-0 max-w-[58vw] sm:max-w-none"
                                title={
                                    latestCheckInAt
                                        ? `Last check-in ${timeAgo(latestCheckInAt, nowTick)}${
                                              nextExpectedHeartbeatAt
                                                  ? ` · Next expected ${timeUntil(nextExpectedHeartbeatAt, nowTick)}`
                                                  : ''
                                          }`
                                        : 'Waiting for the first agent check-in'
                                }
                            >
                                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-ping shrink-0 sm:hidden" />
                                <span className="truncate sm:whitespace-normal">
                                    <span className="sm:hidden">Check-in </span>
                                    <span className="hidden sm:inline">Last Check-in </span>
                                    {latestCheckInAt ? timeAgo(latestCheckInAt, nowTick) : 'Never'}
                                    {nextExpectedHeartbeatAt && (
                                        <span className="text-slate-500">
                                            {' '}
                                            · Next{' '}
                                            <span className="sm:hidden">{compactTimeUntil(nextExpectedHeartbeatAt, nowTick)}</span>
                                            <span className="hidden sm:inline">{timeUntil(nextExpectedHeartbeatAt, nowTick)}</span>
                                        </span>
                                    )}
                                </span>
                                <Activity className="hidden sm:block w-3 h-3 shrink-0" />
                            </span>
                        </div>
                    </div>
                </header>

                {/* Content */}
                <main className="scroll-touch min-h-0 flex-1 bg-slate-950 p-4 pb-[max(1rem,env(safe-area-inset-bottom,0px))] sm:p-5">
                    {children}
                </main>
            </div>
        </div>
    );
}
