import { Link } from '@inertiajs/react';
import { 
    Bell, 
    Check, 
    Trash2, 
    ShieldCheck, 
    AlertCircle, 
    Info, 
    Search,
    Sun,
    Moon,
    Grid,
    Laptop,
    Layers,
    FolderGit2,
    Users,
    History,
    Shield
} from 'lucide-react';
import { useState, useEffect, useRef } from 'react';
import { prefixUrl } from '@/lib/utils';
import { Breadcrumbs } from '@/components/breadcrumbs';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Input } from '@/components/ui/input';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { useAppearance } from '@/hooks/use-appearance';
import type { BreadcrumbItem as BreadcrumbItemType } from '@/types';

interface NotificationItem {
    id: string;
    title: string;
    description: string;
    time: string;
    read: boolean;
    type: 'success' | 'warning' | 'info';
}

export function AppSidebarHeader({
    breadcrumbs = [],
}: {
    breadcrumbs?: BreadcrumbItemType[];
}) {
    const [isOpen, setIsOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    const { appearance, updateAppearance } = useAppearance();
    
    // Seed notifications
    const [notifications, setNotifications] = useState<NotificationItem[]>([
        {
            id: 'seed-1',
            title: 'Compliance Milestone Met',
            description: 'Licence Master SOC 2 Certificate validation audit completed successfully.',
            time: '10m ago',
            read: false,
            type: 'success',
        },
        {
            id: 'seed-2',
            title: 'Audit Log Warning',
            description: 'High latency detected on endpoint GET /settings/audit-logs (520ms).',
            time: '1h ago',
            read: false,
            type: 'warning',
        },
        {
            id: 'seed-3',
            title: 'New Workspace Provisioned',
            description: 'Project Master setup compiled standard deliverables for "Acme Web App".',
            time: '4h ago',
            read: true,
            type: 'info',
        }
    ]);

    const [unreadCount, setUnreadCount] = useState(2);

    useEffect(() => {
        // Listen to live simulated updates from Dashboard
        const handleNewNotification = (e: Event) => {
            const detail = (e as CustomEvent).detail as NotificationItem;
            setNotifications(prev => [detail, ...prev]);
            setUnreadCount(prev => prev + 1);
        };

        window.addEventListener('platform-notification', handleNewNotification);

        // Handle click outside to close dropdown
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);

        return () => {
            window.removeEventListener('platform-notification', handleNewNotification);
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, []);

    const markAllRead = () => {
        setNotifications(prev => prev.map(n => ({ ...n, read: true })));
        setUnreadCount(0);
    };

    const clearAll = () => {
        setNotifications([]);
        setUnreadCount(0);
    };

    const toggleRead = (id: string) => {
        setNotifications(prev => prev.map(n => {
            if (n.id === id) {
                if (!n.read) {
                    setUnreadCount(c => Math.max(0, c - 1));
                }

                return { ...n, read: true };
            }

            return n;
        }));
    };

    const getIcon = (type: string) => {
        switch (type) {
            case 'success':
                return <ShieldCheck className="size-4 text-emerald-500" />;
            case 'warning':
                return <AlertCircle className="size-4 text-rose-500" />;
            default:
                return <Info className="size-4 text-indigo-500" />;
        }
    };

    return (
        <header className="flex h-16 shrink-0 items-center justify-between border-b border-sidebar-border/50 px-6 transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12 md:px-6 relative z-40 bg-white/40 dark:bg-zinc-950/40 backdrop-blur-md">
            {/* Left Section: Sidebar Trigger & Breadcrumbs */}
            <div className="flex items-center gap-3">
                <SidebarTrigger className="-ml-1" />
                <Breadcrumbs breadcrumbs={breadcrumbs} />
            </div>

            {/* Middle Section: Quick Search bar (inspired by Paces) */}
            <div className="relative w-full max-w-xs d-none d-md-block mx-4">
                <Search className="absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-zinc-400" />
                <Input
                    type="search"
                    placeholder="Quick Search..."
                    className="h-9 w-full rounded-full border-zinc-200/80 bg-zinc-50/50 pl-9 pr-4 text-xs dark:border-zinc-800 dark:bg-zinc-900/50 focus-visible:ring-indigo-500/50"
                />
            </div>

            {/* Right Section: Apps Grid, Theme Switcher & Real-time Notification Tray */}
            <div className="flex items-center gap-2">
                
                {/* Apps Dropdown Grid (inspired by Paces) */}
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button
                            variant="ghost"
                            size="icon"
                            className="size-9 rounded-xl hover:bg-zinc-100 dark:hover:bg-zinc-900 transition-colors"
                            title="Apps Dashboard"
                        >
                            <Grid className="size-4.5 text-zinc-600 dark:text-zinc-400" />
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="w-80 rounded-2xl p-3 shadow-2xl backdrop-blur-xl border border-zinc-200/80 dark:border-zinc-800/80 bg-white/95 dark:bg-zinc-950/95">
                        <DropdownMenuLabel className="px-2 pb-2 text-xs font-bold text-zinc-500">Quick App Links</DropdownMenuLabel>
                        <DropdownMenuSeparator className="mb-2" />
                        <div className="grid grid-cols-3 gap-2">
                            <DropdownMenuItem asChild className="rounded-xl">
                                <Link href={prefixUrl("/kanban")} className="flex flex-col items-center justify-center p-3 text-center border border-dashed border-zinc-200/60 dark:border-zinc-800/80 hover:bg-zinc-50 dark:hover:bg-zinc-900 cursor-pointer">
                                    <Layers className="size-5 text-indigo-500 mb-1" />
                                    <span className="text-[10px] font-extrabold text-zinc-700 dark:text-zinc-300">Kanban</span>
                                </Link>
                            </DropdownMenuItem>

                            <DropdownMenuItem asChild className="rounded-xl">
                                <Link href={prefixUrl("/settings/projects")} className="flex flex-col items-center justify-center p-3 text-center border border-dashed border-zinc-200/60 dark:border-zinc-800/80 hover:bg-zinc-50 dark:hover:bg-zinc-900 cursor-pointer">
                                    <FolderGit2 className="size-5 text-blue-500 mb-1" />
                                    <span className="text-[10px] font-extrabold text-zinc-700 dark:text-zinc-300">Projects</span>
                                </Link>
                            </DropdownMenuItem>

                            <DropdownMenuItem asChild className="rounded-xl">
                                <Link href={prefixUrl("/settings/users")} className="flex flex-col items-center justify-center p-3 text-center border border-dashed border-zinc-200/60 dark:border-zinc-800/80 hover:bg-zinc-50 dark:hover:bg-zinc-900 cursor-pointer">
                                    <Users className="size-5 text-purple-500 mb-1" />
                                    <span className="text-[10px] font-extrabold text-zinc-700 dark:text-zinc-300">Users</span>
                                </Link>
                            </DropdownMenuItem>

                            <DropdownMenuItem asChild className="rounded-xl">
                                <Link href={prefixUrl("/settings/audit-logs")} className="flex flex-col items-center justify-center p-3 text-center border border-dashed border-zinc-200/60 dark:border-zinc-800/80 hover:bg-zinc-50 dark:hover:bg-zinc-900 cursor-pointer">
                                    <History className="size-5 text-pink-500 mb-1" />
                                    <span className="text-[10px] font-extrabold text-zinc-700 dark:text-zinc-300">Audits</span>
                                </Link>
                            </DropdownMenuItem>

                            <DropdownMenuItem asChild className="rounded-xl">
                                <Link href={prefixUrl("/settings/rbac")} className="flex flex-col items-center justify-center p-3 text-center border border-dashed border-zinc-200/60 dark:border-zinc-800/80 hover:bg-zinc-50 dark:hover:bg-zinc-900 cursor-pointer">
                                    <Shield className="size-5 text-emerald-500 mb-1" />
                                    <span className="text-[10px] font-extrabold text-zinc-700 dark:text-zinc-300">Roles</span>
                                </Link>
                            </DropdownMenuItem>
                        </div>
                    </DropdownMenuContent>
                </DropdownMenu>

                {/* Light/Dark/System Theme Toggler (inspired by Paces) */}
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button
                            variant="ghost"
                            size="icon"
                            className="size-9 rounded-xl hover:bg-zinc-100 dark:hover:bg-zinc-900 transition-colors"
                            title="Appearance mode"
                        >
                            {appearance === 'light' && <Sun className="size-4.5 text-amber-500" />}
                            {appearance === 'dark' && <Moon className="size-4.5 text-indigo-400" />}
                            {appearance === 'system' && <Laptop className="size-4.5 text-zinc-500" />}
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="w-36 rounded-xl p-1 shadow-xl border border-zinc-200/80 dark:border-zinc-800/80 bg-white/95 dark:bg-zinc-950/95">
                        <DropdownMenuItem onClick={() => updateAppearance('light')} className="flex items-center gap-2 text-xs font-bold py-1.5 cursor-pointer">
                            <Sun className="size-3.5 text-amber-500" /> Light
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => updateAppearance('dark')} className="flex items-center gap-2 text-xs font-bold py-1.5 cursor-pointer">
                            <Moon className="size-3.5 text-indigo-400" /> Dark
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => updateAppearance('system')} className="flex items-center gap-2 text-xs font-bold py-1.5 cursor-pointer">
                            <Laptop className="size-3.5 text-zinc-500" /> System
                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenu>

                {/* Notifications Tray */}
                <div className="relative" ref={dropdownRef}>
                    <Button
                        variant="ghost"
                        size="icon"
                        className="relative size-9 rounded-xl hover:bg-zinc-100 dark:hover:bg-zinc-900 transition-colors"
                        onClick={() => setIsOpen(!isOpen)}
                    >
                        <Bell className="size-4.5 text-zinc-600 dark:text-zinc-400" />
                        {unreadCount > 0 && (
                            <span className="absolute top-1.5 right-1.5 flex h-2 w-2">
                                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-rose-400 opacity-75"></span>
                                <span className="relative inline-flex rounded-full h-2 w-2 bg-rose-500"></span>
                            </span>
                        )}
                    </Button>

                    {isOpen && (
                        <div className="absolute right-0 mt-2 w-80 md:w-96 rounded-2xl border border-zinc-200/80 dark:border-zinc-800/80 bg-white/95 dark:bg-zinc-950/95 backdrop-blur-xl shadow-2xl overflow-hidden z-50 animate-in fade-in slide-in-from-top-3 duration-250">
                            <div className="p-4 border-b border-zinc-100 dark:border-zinc-850 flex items-center justify-between bg-zinc-50/50 dark:bg-zinc-900/50">
                                <div>
                                    <h4 className="font-extrabold text-sm text-zinc-900 dark:text-zinc-100 flex items-center gap-1.5">
                                        Alert & Activity Hub
                                        {unreadCount > 0 && (
                                            <span className="px-2 py-0.5 rounded-full bg-indigo-50 dark:bg-indigo-950/50 text-[10px] font-extrabold text-indigo-600 dark:text-indigo-400 border border-indigo-150/50 dark:border-indigo-900/50">
                                                {unreadCount} new
                                            </span>
                                        )}
                                    </h4>
                                </div>
                                {notifications.length > 0 && (
                                    <div className="flex items-center gap-1">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="h-7 text-[10px] font-bold text-zinc-500 hover:text-zinc-900 hover:bg-zinc-100 dark:hover:bg-zinc-850 px-2 rounded-lg flex items-center gap-1"
                                            onClick={markAllRead}
                                        >
                                            <Check className="size-3" /> Read All
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="h-7 text-[10px] font-bold text-red-500 hover:text-red-650 hover:bg-red-50 dark:hover:bg-red-950/20 px-2 rounded-lg flex items-center gap-1"
                                            onClick={clearAll}
                                        >
                                            <Trash2 className="size-3" /> Clear
                                        </Button>
                                    </div>
                                )}
                            </div>

                            <div className="max-h-[360px] overflow-y-auto divide-y divide-zinc-100 dark:divide-zinc-850 scrollbar-thin">
                                {notifications.length === 0 ? (
                                    <div className="p-8 text-center text-zinc-400 flex flex-col items-center justify-center gap-2">
                                        <Bell className="size-8 stroke-1 text-zinc-300 dark:text-zinc-700 animate-pulse" />
                                        <p className="text-xs font-bold">No active alerts</p>
                                        <p className="text-[10px] text-zinc-400 max-w-[200px]">Simulated workspace activities will stream notifications here live.</p>
                                    </div>
                                ) : (
                                    notifications.map(item => (
                                        <div
                                            key={item.id}
                                            className={`p-4 flex items-start gap-3 hover:bg-zinc-50/50 dark:hover:bg-zinc-900/30 transition-colors cursor-pointer relative group ${
                                                !item.read ? 'bg-indigo-50/10 dark:bg-indigo-950/5' : ''
                                            }`}
                                            onClick={() => toggleRead(item.id)}
                                        >
                                            <div className="mt-0.5 size-7 rounded-lg bg-zinc-50 dark:bg-zinc-900 border border-zinc-200/50 dark:border-zinc-800/50 flex items-center justify-center shrink-0 shadow-sm">
                                                {getIcon(item.type)}
                                            </div>

                                            <div className="flex-1 min-w-0 space-y-0.5">
                                                <div className="flex items-center justify-between gap-1.5">
                                                    <h5 className={`text-xs font-extrabold truncate ${
                                                        !item.read ? 'text-zinc-900 dark:text-zinc-50' : 'text-zinc-650 dark:text-zinc-400'
                                                    }`}>
                                                        {item.title}
                                                    </h5>
                                                    <span className="text-[9px] font-medium text-zinc-400 shrink-0">{item.time}</span>
                                                </div>
                                                <p className="text-[11px] text-zinc-450 dark:text-zinc-500 leading-relaxed font-semibold">
                                                    {item.description}
                                                </p>
                                            </div>

                                            {!item.read && (
                                                <span className="absolute right-3 top-1/2 -translate-y-1/2 size-1.5 rounded-full bg-indigo-500 group-hover:scale-125 transition-transform" />
                                            )}
                                        </div>
                                    ))
                                )}
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </header>
    );
}
