import React, { useState, useEffect, useRef } from 'react';
import { Link, usePage, Head } from '@inertiajs/react';
import {

    LayoutDashboard,
    FileText,
    Briefcase,
    FolderGit2,
    Users,
    MessageSquare,
    HelpCircle,
    Mail,
    Image,
    Menu as MenuIcon,
    Settings,
    Globe,
    LogOut,
    Download,
    CheckCircle2,
    Sparkles,
    Shield,
    Database,
    User,
    Bell,

    ExternalLink,
    Check,
    MessageCircle,
    AlertTriangle,
    Info,
    X,
} from 'lucide-react';



interface AdminLayoutProps {
    children: React.ReactNode;
    title?: string;
}

export const AdminLayout: React.FC<AdminLayoutProps> = ({ children, title }) => {
    const { auth, flash, globalSettings } = usePage().props as any;
    const [sidebarOpen, setSidebarOpen] = useState(true);
    const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
    const [notificationsOpen, setNotificationsOpen] = useState(false);
    const [unreadChatCount, setUnreadChatCount] = useState(0);
    const [recentNotifications, setRecentNotifications] = useState<any[]>([]);

    const user = auth?.user;
    const dropdownRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setNotificationsOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    // Auto-close mobile drawer on route change
    useEffect(() => {
        setMobileMenuOpen(false);
    }, [window.location.pathname]);

    // Polling unread notifications count every 5 seconds
    useEffect(() => {
        const fetchNotifications = async () => {
            try {
                const res = await fetch('/admin/dashboard');
                // Or fetch quick stats endpoint
            } catch (e) {
                // Ignore
            }
        };
    }, []);

    const hasPermission = (permission?: string) => {
        if (!permission) return true;
        if (user?.role === 'super_admin') return true;
        const perms = Array.isArray(user?.permissions) ? user.permissions : [];
        return perms.includes('*') || perms.includes(permission);
    };

    const navigationSections = [
        {
            label: 'Core & Overview',
            items: [
                { name: 'Dashboard', href: '/admin/dashboard', icon: LayoutDashboard, permission: 'dashboard.view' },
            ],
        },
        {
            label: 'Content Management',
            items: [
                { name: 'CMS Pages & Builder', href: '/admin/pages', icon: FileText, permission: 'pages.manage' },
                { name: 'Services Catalog', href: '/admin/services', icon: Briefcase, permission: 'services.manage' },
                { name: 'Projects & Case Studies', href: '/admin/projects', icon: FolderGit2, permission: 'projects.manage' },
                { name: 'Blog Articles', href: '/admin/blog', icon: FileText, permission: 'blog.manage' },
                { name: 'Client Testimonials', href: '/admin/testimonials', icon: MessageSquare, permission: 'testimonials.manage' },
                { name: 'Team Members', href: '/admin/team', icon: Users, permission: 'team.manage' },
                { name: 'FAQs & Help Center', href: '/admin/faqs', icon: HelpCircle, permission: 'faqs.manage' },
                { name: 'Media Library', href: '/admin/media', icon: Image, permission: 'media.manage' },
                { name: 'Navigation Menus', href: '/admin/menus', icon: MenuIcon, permission: 'menus.manage' },
            ],
        },
        {
            label: 'Communication & Leads',
            items: [
                { name: 'Live Chat Desk', href: '/admin/chat', icon: MessageCircle, permission: 'chat.manage' },
                { name: 'Contact Inquiries', href: '/admin/contacts', icon: Mail, permission: 'contacts.view' },
                { name: 'Newsletter Subscribers', href: '/admin/newsletter', icon: Mail, permission: 'newsletter.view' },
            ],
        },
        {
            label: 'System & Automation',
            items: [
                { name: 'Settings & AI', href: '/admin/settings', icon: Settings, permission: 'settings.manage' },
                { name: 'SEO, Sitemaps & Robots', href: '/admin/seo', icon: Globe, permission: 'seo.manage' },
                { name: 'Database & Backups', href: '/admin/database', icon: Database, permission: 'database.manage' },
                { name: 'Users & RBAC', href: '/admin/users', icon: Shield, permission: 'users.manage' },
                { name: 'Content Importer', href: '/admin/content-import', icon: Download, permission: 'settings.manage' },
            ],
        },
        {
            label: 'My Account',
            items: [
                { name: 'My Profile', href: '/admin/profile', icon: User },
            ],
        },
    ].map(section => ({
        ...section,
        items: section.items.filter(item => hasPermission(item.permission))
    })).filter(section => section.items.length > 0);

    const pageTitle = title
        ? (title.includes('Tech in Soul') ? title : `${title} | Tech in Soul Admin`)
        : 'Admin Dashboard | Tech in Soul';

    return (
        <div className="min-h-screen bg-[#060B18] text-slate-100 flex font-sans">
            <Head title={pageTitle} />

            {/* Mobile Drawer Overlay */}
            {mobileMenuOpen && (
                <div
                    onClick={() => setMobileMenuOpen(false)}
                    className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 lg:hidden animate-in fade-in duration-200"
                />
            )}

            {/* Mobile Off-canvas Drawer */}
            <aside
                className={`fixed inset-y-0 left-0 z-50 w-72 bg-[#0B132B] border-r border-[#38BDF8]/20 flex flex-col h-screen transform transition-transform duration-300 ease-in-out lg:hidden ${
                    mobileMenuOpen ? 'translate-x-0' : '-translate-x-full'
                }`}
            >
                {/* Header Brand with Close Button */}
                <div className="h-16 shrink-0 border-b border-slate-800 flex items-center justify-between px-4">
                    <Link href="/admin/dashboard" onClick={() => setMobileMenuOpen(false)} className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-lg bg-gradient-to-tr from-[#00F2FE] to-[#38BDF8] p-[1px] shrink-0">
                            <div className="w-full h-full bg-[#060B18] rounded-[7px] flex items-center justify-center">
                                <Sparkles className="w-4 h-4 text-[#00F2FE]" />
                            </div>
                        </div>
                        <span className="text-sm font-bold text-white tracking-tight">
                            TECH IN <span className="text-[#00F2FE]">SOUL</span>
                        </span>
                    </Link>
                    <button
                        onClick={() => setMobileMenuOpen(false)}
                        className="p-2 text-slate-400 hover:text-white rounded-lg hover:bg-slate-800 transition-colors"
                        aria-label="Close menu"
                    >
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {/* Structured Nav Items */}
                <nav className="flex-1 overflow-y-auto p-3 space-y-5 custom-scrollbar min-h-0">
                    {navigationSections.map((section) => (
                        <div key={section.label} className="space-y-1">
                            <div className="px-3 pb-1 text-[10px] font-bold text-slate-500 uppercase tracking-wider">
                                {section.label}
                            </div>
                            <div className="space-y-0.5">
                                {section.items.map((item) => {
                                    const Icon = item.icon;
                                    const isActive = window.location.pathname.startsWith(item.href);
                                    return (
                                        <Link
                                            key={item.name}
                                            href={item.href}
                                            onClick={() => setMobileMenuOpen(false)}
                                            className={`flex items-center gap-3 px-3 py-2.5 rounded-xl text-xs font-semibold transition-all ${
                                                isActive
                                                    ? 'bg-[#00F2FE]/15 text-[#00F2FE] border border-[#00F2FE]/30 shadow-sm shadow-cyan-500/10'
                                                    : 'text-slate-400 hover:text-white hover:bg-slate-800/60'
                                            }`}
                                        >
                                            <Icon className={`w-4 h-4 shrink-0 ${isActive ? 'text-[#00F2FE]' : ''}`} />
                                            <span className="truncate">{item.name}</span>
                                        </Link>
                                    );
                                })}
                            </div>
                        </div>
                    ))}
                </nav>

                {/* Footer User Profile */}
                <div className="shrink-0 p-3.5 border-t border-slate-800/80 bg-[#060B18]/60 flex items-center justify-between">
                    <Link href="/admin/profile" onClick={() => setMobileMenuOpen(false)} className="flex items-center gap-2.5 hover:opacity-80 transition-opacity min-w-0">
                        <div className="w-8 h-8 rounded-full bg-gradient-to-br from-[#00F2FE] to-[#38BDF8] text-[#060B18] flex items-center justify-center text-xs font-black shrink-0">
                            {user?.name?.charAt(0) || 'A'}
                        </div>
                        <div className="truncate">
                            <span className="text-xs font-bold text-white block truncate">{user?.name}</span>
                            <span className="text-[10px] text-[#00F2FE] capitalize block font-medium">{user?.role?.replace('_', ' ')}</span>
                        </div>
                    </Link>
                    <Link href="/logout" method="post" as="button" title="Logout" className="text-slate-400 hover:text-rose-400 p-1.5 rounded-lg hover:bg-rose-500/10 transition-colors">
                        <LogOut className="w-4 h-4" />
                    </Link>
                </div>
            </aside>

            {/* Desktop Sticky Sidebar */}
            <aside className={`hidden lg:flex bg-[#0B132B] border-r border-[#38BDF8]/15 flex-col h-screen sticky top-0 shrink-0 z-30 transition-all duration-300 ${sidebarOpen ? 'w-64' : 'w-20'}`}>
                {/* Header Brand */}
                <div className="h-16 shrink-0 border-b border-slate-800 flex items-center justify-between px-4">
                    <Link href="/admin/dashboard" className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-lg bg-gradient-to-tr from-[#00F2FE] to-[#38BDF8] p-[1px] shrink-0">
                            <div className="w-full h-full bg-[#060B18] rounded-[7px] flex items-center justify-center">
                                <Sparkles className="w-4 h-4 text-[#00F2FE]" />
                            </div>
                        </div>
                        {sidebarOpen && (
                            <span className="text-sm font-bold text-white tracking-tight">
                                TECH IN <span className="text-[#00F2FE]">SOUL</span>
                            </span>
                        )}
                    </Link>
                </div>

                {/* Structured Nav Items */}
                <nav className="flex-1 overflow-y-auto p-3 space-y-5 custom-scrollbar min-h-0">
                    {navigationSections.map((section) => (
                        <div key={section.label} className="space-y-1">
                            {sidebarOpen && (
                                <div className="px-3 pb-1 text-[10px] font-bold text-slate-500 uppercase tracking-wider">
                                    {section.label}
                                </div>
                            )}
                            <div className="space-y-0.5">
                                {section.items.map((item) => {
                                    const Icon = item.icon;
                                    const isActive = window.location.pathname.startsWith(item.href);
                                    return (
                                        <Link
                                            key={item.name}
                                            href={item.href}
                                            title={!sidebarOpen ? item.name : undefined}
                                            className={`flex items-center gap-3 px-3 py-2 rounded-xl text-xs font-semibold transition-all ${
                                                isActive
                                                    ? 'bg-[#00F2FE]/15 text-[#00F2FE] border border-[#00F2FE]/30 shadow-sm shadow-cyan-500/10'
                                                    : 'text-slate-400 hover:text-white hover:bg-slate-800/60'
                                            }`}
                                        >
                                            <Icon className={`w-4 h-4 shrink-0 ${isActive ? 'text-[#00F2FE]' : ''}`} />
                                            {sidebarOpen && <span className="truncate">{item.name}</span>}
                                        </Link>
                                    );
                                })}
                            </div>
                        </div>
                    ))}
                </nav>

                {/* Footer User Profile */}
                <div className="shrink-0 p-3.5 border-t border-slate-800/80 bg-[#060B18]/60 flex items-center justify-between">
                    <Link href="/admin/profile" className="flex items-center gap-2.5 hover:opacity-80 transition-opacity min-w-0">
                        <div className="w-8 h-8 rounded-full bg-gradient-to-br from-[#00F2FE] to-[#38BDF8] text-[#060B18] flex items-center justify-center text-xs font-black shrink-0">
                            {user?.name?.charAt(0) || 'A'}
                        </div>
                        {sidebarOpen && (
                            <div className="truncate">
                                <span className="text-xs font-bold text-white block truncate">{user?.name}</span>
                                <span className="text-[10px] text-[#00F2FE] capitalize block font-medium">{user?.role?.replace('_', ' ')}</span>
                            </div>
                        )}
                    </Link>
                    <Link href="/logout" method="post" as="button" title="Logout" className="text-slate-400 hover:text-rose-400 p-1.5 rounded-lg hover:bg-rose-500/10 transition-colors">
                        <LogOut className="w-4 h-4" />
                    </Link>
                </div>
            </aside>

            {/* Main Area */}
            <div className="flex-1 flex flex-col min-w-0">
                {/* Topbar */}
                <header className="h-16 bg-[#0B132B]/95 backdrop-blur-md border-b border-[#38BDF8]/15 px-4 sm:px-6 flex items-center justify-between relative z-40">
                    <div className="flex items-center gap-3 min-w-0">
                        {/* Mobile Menu Toggle */}
                        <button
                            onClick={() => setMobileMenuOpen(true)}
                            className="lg:hidden p-2 rounded-xl bg-[#060B18] border border-slate-800 text-slate-300 hover:text-[#00F2FE] hover:border-[#00F2FE]/40 transition-all shrink-0"
                            aria-label="Open menu"
                        >
                            <MenuIcon className="w-5 h-5" />
                        </button>

                        {/* Desktop Sidebar Toggle */}
                        <button
                            onClick={() => setSidebarOpen(!sidebarOpen)}
                            className="hidden lg:flex p-2 rounded-xl bg-[#060B18] border border-slate-800 text-slate-300 hover:text-[#00F2FE] hover:border-[#00F2FE]/40 transition-all shrink-0"
                            aria-label="Toggle sidebar"
                            title={sidebarOpen ? "Collapse sidebar" : "Expand sidebar"}
                        >
                            <MenuIcon className="w-4 h-4" />
                        </button>

                        <h1 className="text-base sm:text-lg font-bold text-white truncate">{title || 'Dashboard'}</h1>
                    </div>


                    <div className="flex items-center gap-4">
                        {/* Top-Right Notification Section */}
                        <div className="relative" ref={dropdownRef}>
                            <button
                                onClick={() => setNotificationsOpen(!notificationsOpen)}
                                className="relative p-2 rounded-xl bg-[#060B18] border border-slate-800 text-slate-300 hover:text-[#00F2FE] hover:border-[#00F2FE]/40 transition-all"
                                title="Notifications"
                            >
                                <Bell className="w-4 h-4" />
                                <span className="absolute -top-1 -right-1 flex h-3 w-3">
                                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-[#00F2FE] opacity-75"></span>
                                    <span className="relative inline-flex rounded-full h-3 w-3 bg-[#00F2FE]"></span>
                                </span>
                            </button>

                            {/* Dropdown Menu */}
                            {notificationsOpen && (
                                <div className="absolute right-0 mt-3 w-80 sm:w-96 bg-[#0B132B] border border-slate-800 rounded-2xl shadow-[0_20px_60px_rgba(0,0,0,0.9)] overflow-hidden z-[100] animate-in fade-in slide-in-from-top-2 duration-200">
                                    <div className="p-4 border-b border-slate-800 flex items-center justify-between bg-[#060B18]">
                                        <h4 className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2">
                                            <Bell className="w-4 h-4 text-[#00F2FE]" /> Live Notifications
                                        </h4>
                                        <span className="text-[10px] font-bold text-[#00F2FE] bg-[#00F2FE]/10 px-2 py-0.5 rounded-full border border-[#00F2FE]/20">
                                            Real-time
                                        </span>
                                    </div>

                                    <div className="divide-y divide-slate-800 max-h-80 overflow-y-auto">
                                        {/* Live Chat Notification Item */}
                                        <Link
                                            href="/admin/chat"
                                            onClick={() => setNotificationsOpen(false)}
                                            className="p-4 flex items-start gap-3 hover:bg-slate-800/40 transition-colors block"
                                        >
                                            <div className="w-8 h-8 rounded-full bg-[#00F2FE]/10 border border-[#00F2FE]/30 flex items-center justify-center text-[#00F2FE] shrink-0">
                                                <MessageCircle className="w-4 h-4" />
                                            </div>
                                            <div className="min-w-0 flex-grow">
                                                <div className="flex items-center justify-between">
                                                    <span className="text-xs font-bold text-white truncate">Live Chat Inbox</span>
                                                    <span className="text-[10px] text-slate-400">Just now</span>
                                                </div>
                                                <p className="text-[11px] text-slate-300 mt-0.5 truncate">
                                                    Visitors are actively chatting live on the website.
                                                </p>
                                            </div>
                                        </Link>

                                        {/* Contact Lead Notification Item */}
                                        <Link
                                            href="/admin/contacts"
                                            onClick={() => setNotificationsOpen(false)}
                                            className="p-4 flex items-start gap-3 hover:bg-slate-800/40 transition-colors block"
                                        >
                                            <div className="w-8 h-8 rounded-full bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center text-emerald-400 shrink-0">
                                                <Mail className="w-4 h-4" />
                                            </div>
                                            <div className="min-w-0 flex-grow">
                                                <div className="flex items-center justify-between">
                                                    <span className="text-xs font-bold text-white truncate">Client Inquiries</span>
                                                    <span className="text-[10px] text-slate-400">Today</span>
                                                </div>
                                                <p className="text-[11px] text-slate-300 mt-0.5 truncate">
                                                    New client proposals and contact form messages received.
                                                </p>
                                            </div>
                                        </Link>
                                    </div>

                                    <div className="p-3 border-t border-slate-800 bg-[#060B18] text-center">
                                        <Link
                                            href="/admin/chat"
                                            onClick={() => setNotificationsOpen(false)}
                                            className="text-xs font-bold text-[#00F2FE] hover:underline"
                                        >
                                            Open Support Control Center →
                                        </Link>
                                    </div>
                                </div>
                            )}
                        </div>


                        <Link
                            href="/"
                            target="_blank"
                            className="text-xs font-semibold px-3.5 py-2 rounded-xl bg-[#060B18] border border-slate-800 text-[#00F2FE] hover:bg-[#00F2FE]/10 transition-colors flex items-center gap-1.5"
                        >
                            <Globe className="w-3.5 h-3.5" />
                            View Public Site
                        </Link>
                    </div>
                </header>

                {/* Content */}
                <main className="flex-1 p-6 lg:p-8 overflow-y-auto">
                    {flash?.success && (
                        <div className="mb-6 p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-sm flex items-center gap-3 animate-in fade-in">
                            <CheckCircle2 className="w-5 h-5 shrink-0" />
                            <span className="font-medium leading-relaxed">{flash.success}</span>
                        </div>
                    )}

                    {flash?.status && (
                        <div className="mb-6 p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-sm flex items-center gap-3 animate-in fade-in">
                            <CheckCircle2 className="w-5 h-5 shrink-0" />
                            <span className="font-medium leading-relaxed">{flash.status}</span>
                        </div>
                    )}

                    {flash?.error && (
                        <div className="mb-6 p-4 rounded-2xl bg-rose-500/10 border border-rose-500/30 text-rose-400 text-sm flex items-center gap-3 animate-in fade-in">
                            <AlertTriangle className="w-5 h-5 shrink-0" />
                            <span className="font-medium leading-relaxed">{flash.error}</span>
                        </div>
                    )}

                    {flash?.warning && (
                        <div className="mb-6 p-4 rounded-2xl bg-amber-500/10 border border-amber-500/30 text-amber-400 text-sm flex items-center gap-3 animate-in fade-in">
                            <AlertTriangle className="w-5 h-5 shrink-0" />
                            <span className="font-medium leading-relaxed">{flash.warning}</span>
                        </div>
                    )}

                    {flash?.info && (
                        <div className="mb-6 p-4 rounded-2xl bg-cyan-500/10 border border-cyan-500/30 text-[#00F2FE] text-sm flex items-center gap-3 animate-in fade-in">
                            <Info className="w-5 h-5 shrink-0" />
                            <span className="font-medium leading-relaxed">{flash.info}</span>
                        </div>
                    )}


                    {children}
                </main>
            </div>
        </div>
    );
};
