import { Link, usePage } from '@inertiajs/react';
import { LayoutDashboard, ShoppingBag, CalendarCheck, ClipboardList, LogOut, Menu, X, ArrowLeft, Settings, Image as ImageIcon, FileText, Newspaper, Folder } from 'lucide-react';
import { useState, ReactNode, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Toaster, toast } from 'sonner';
import ScrollToTop from '@/Components/ScrollToTop';

const navigation = [
    { name: 'Overview', href: '/admin', icon: LayoutDashboard },
    { name: 'Media', href: '/admin/media', icon: ImageIcon },
    { name: 'Bookings', href: '/admin/bookings', icon: CalendarCheck },
    { name: 'Case Studies', href: '/admin/case-studies', icon: FileText },
    { 
        name: 'Blog', 
        icon: Newspaper, 
        children: [
            { name: 'Articles', href: '/admin/posts' },
            { name: 'Categories', href: '/admin/categories' },
        ]
    },
    { name: 'Products', href: '/admin/products', icon: ShoppingBag },
    { name: 'Orders', href: '/admin/orders', icon: ClipboardList },
    { name: 'Settings', href: '/admin/settings', icon: Settings },
];

export default function AdminLayout({ children }: { children: ReactNode }) {
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const { url, props } = usePage<any>();
    const { auth, flash, branding } = props;

    const user = auth?.user;
    const userName = user?.name || 'Admin User';
    const userInitials = userName.split(' ').map((n: string) => n[0]).join('').toUpperCase().slice(0, 2);

    // Flash message toasts
    useEffect(() => {
        if (flash?.success) {
            toast.success(flash.success);
        }
        if (flash?.error) {
            toast.error(flash.error);
        }
    }, [flash]);

    // Close sidebar on route change (mobile nav)
    useEffect(() => { setSidebarOpen(false); }, [url]);

    // Derive current page name for mobile header breadcrumb
    const currentPage = navigation.find(
        (n) => url === n.href || (n.href !== '/admin' && url.startsWith(n.href))
    )?.name ?? 'Overview';

    return (
        <div className="min-h-screen bg-cream font-sans text-ink grain">
            <Toaster 
                position="top-right" 
                expand={true} 
                richColors={false}
                toastOptions={{
                    style: {
                        background: '#FFFFFF',
                        border: '1px solid #E8E6DF',
                        color: '#1A1A1A',
                        borderRadius: '14px',
                        padding: '12px 16px',
                        fontSize: '14px',
                        fontWeight: '500',
                        boxShadow: '0 10px 30px -10px rgba(0,0,0,0.1)',
                    },
                }}
            />

            {/* ── Mobile backdrop ─────────────────────────────── */}
            <AnimatePresence>
                {sidebarOpen && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        className="fixed inset-0 z-40 bg-ink/20 backdrop-blur-sm lg:hidden"
                        onClick={() => setSidebarOpen(false)}
                    />
                )}
            </AnimatePresence>

            {/* ── Sidebar ─────────────────────────────────────── */}
            <AnimatePresence>
                {(sidebarOpen) && (
                    <motion.aside
                        initial={{ x: '-100%' }}
                        animate={{ x: 0 }}
                        exit={{ x: '-100%' }}
                        transition={{ type: 'spring', damping: 28, stiffness: 260 }}
                        className="fixed inset-y-0 left-0 z-50 w-[270px] flex flex-col bg-white border-r border-[#E8E6DF] lg:hidden"
                    >
                        <SidebarContent url={url} userInitials={userInitials} onClose={() => setSidebarOpen(false)} branding={branding} />
                    </motion.aside>
                )}
            </AnimatePresence>

            {/* Desktop sidebar — always visible ≥ lg */}
            <aside className="hidden lg:flex lg:flex-col fixed inset-y-0 left-0 w-64 bg-white border-r border-[#E8E6DF] z-30">
                <SidebarContent url={url} userInitials={userInitials} onClose={() => {}} branding={branding} />
            </aside>

            {/* ── Main area ───────────────────────────────────── */}
            <div className="lg:pl-64 flex flex-col min-h-screen">

                {/* Top bar */}
                <header className="sticky top-0 z-30 flex h-14 lg:h-[60px] items-center justify-between border-b border-[#E8E6DF] bg-white/90 px-4 lg:px-8 backdrop-blur-md">
                    <div className="flex items-center gap-3">
                        {/* Hamburger — mobile only */}
                        <button
                            onClick={() => setSidebarOpen(true)}
                            className="lg:hidden p-1.5 -ml-1 rounded-md text-[#8C92AC] hover:text-ink transition-colors"
                        >
                            <Menu className="h-5 w-5" />
                        </button>

                        {/* Breadcrumb label */}
                        <div className="flex items-center gap-2 text-[10px] md:text-[11px] font-bold uppercase tracking-[0.14em] text-[#8C92AC]">
                            <LayoutDashboard className="h-3.5 w-3.5 hidden md:block" />
                            <span className="hidden md:inline">Admin</span>
                            <span className="text-[#C0BDBA] hidden md:inline">·</span>
                            <span className="text-ink bg-[#F5F3EF] px-2 py-0.5 rounded md:bg-transparent md:px-0 md:py-0">{currentPage}</span>
                        </div>
                    </div>

                    <div className="flex items-center gap-2 md:gap-3">
                        <span className="hidden lg:block text-[10px] font-semibold uppercase tracking-[0.18em] text-[#8C92AC]">
                            Demo workspace
                        </span>
                        <div className="h-8 w-8 rounded-full bg-[#F0EDE8] flex items-center justify-center text-[11px] font-bold text-ink select-none border border-[#E8E6DF] md:border-none">
                            {userInitials}
                        </div>
                        <Link
                            href={route('logout')}
                            method="post"
                            as="button"
                            className="p-1.5 text-[#8C92AC] hover:text-red-500 transition-colors"
                            title="Sign out"
                        >
                            <LogOut className="h-4 w-4" />
                        </Link>
                    </div>
                </header>

                {/* Page content */}
                <main className="flex-1 p-4 sm:p-6 lg:p-10 mb-20 lg:mb-0">
                    <div className="mx-auto max-w-7xl">
                        {children}
                    </div>
                </main>
            </div>

            {/* ── Mobile Bottom Nav ─────────────────────────── */}
            <div className="lg:hidden fixed bottom-0 left-0 right-0 z-[60] bg-white/95 backdrop-blur-xl border-t border-[#E8E6DF] px-2 pb-safe-area-inset-bottom h-[72px] flex items-center justify-around shadow-[0_-8px_20px_-10px_rgba(0,0,0,0.1)]">
                {navigation.filter(n => !n.children).slice(0, 4).map((item) => {
                    const Icon = item.icon;
                    const isActive = url === item.href || (item.href !== '/admin' && url.startsWith(item.href));
                    return (
                        <Link
                            key={item.name}
                            href={item.href}
                            className={`flex flex-col items-center justify-center gap-1.5 flex-1 h-full relative transition-all ${
                                isActive ? 'text-primary' : 'text-[#8C92AC]'
                            }`}
                        >
                            {isActive && (
                                <motion.div
                                    layoutId="bottomNavTab"
                                    className="absolute -top-[1px] left-1/2 -translate-x-1/2 w-8 h-[2px] bg-primary rounded-full"
                                />
                            )}
                            <Icon className={`h-[22px] w-[22px] ${isActive ? 'text-primary' : 'text-[#8C92AC]'}`} strokeWidth={isActive ? 2.5 : 2} />
                            <span className={`text-[10px] font-bold tracking-tight ${isActive ? 'text-ink' : 'text-[#8C92AC]'}`}>
                                {item.name}
                            </span>
                        </Link>
                    );
                })}
                
                {/* Menu Trigger */}
                <button
                    onClick={() => setSidebarOpen(true)}
                    className="flex flex-col items-center justify-center gap-1.5 flex-1 h-full text-[#8C92AC]"
                >
                    <div className="h-[22px] w-[22px] flex flex-col justify-center items-center gap-0.5">
                        <span className="w-4 h-[2px] bg-[#8C92AC] rounded-full" />
                        <span className="w-4 h-[2px] bg-[#8C92AC] rounded-full" />
                        <span className="w-4 h-[2px] bg-[#8C92AC] rounded-full" />
                    </div>
                    <span className="text-[10px] font-bold tracking-tight">More</span>
                </button>
            </div>

            <ScrollToTop />
        </div>
    );
}

/* ── Shared sidebar body ──────────────────────────────────────── */
function SidebarContent({
    url,
    userInitials,
    onClose,
    branding,
}: {
    url: string;
    userInitials: string;
    onClose: () => void;
    branding: any;
}) {
    const [openSubmenus, setOpenSubmenus] = useState<string[]>([]);

    useEffect(() => {
        // Auto-expand submenus if a child is active
        navigation.forEach(item => {
            if (item.children?.some(child => url.startsWith(child.href))) {
                setOpenSubmenus(prev => Array.from(new Set([...prev, item.name])));
            }
        });
    }, [url]);

    const toggleSubmenu = (name: string) => {
        setOpenSubmenus(prev => 
            prev.includes(name) ? prev.filter(n => n !== name) : [...prev, name]
        );
    };

    const NavItem = ({ item, isSub = false }: { item: any, isSub?: boolean }) => {
        const Icon = item.icon;
        const hasChildren = item.children && item.children.length > 0;
        const isOpen = openSubmenus.includes(item.name);
        const isActive = item.href ? (url === item.href || (item.href !== '/admin' && url.startsWith(item.href))) 
                                   : item.children?.some((child: any) => url.startsWith(child.href));

        return (
            <div className="w-full">
                {hasChildren ? (
                    <button
                        onClick={() => toggleSubmenu(item.name)}
                        className={`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-[13px] font-medium transition-all ${
                            isActive ? 'bg-[#F0EDE8] text-ink font-semibold' : 'text-[#8C92AC] hover:bg-[#F5F3EF] hover:text-ink'
                        }`}
                    >
                        <div className="flex items-center gap-3">
                            {Icon && <Icon className={`h-4 w-4 flex-shrink-0 ${isActive ? 'text-ink' : 'text-[#C0BDBA]'}`} strokeWidth={isActive ? 2 : 1.5} />}
                            {item.name}
                        </div>
                        <motion.div
                            animate={{ rotate: isOpen ? 180 : 0 }}
                            transition={{ duration: 0.2 }}
                        >
                            <Menu className="h-3 w-3 opacity-50" />
                        </motion.div>
                    </button>
                ) : (
                    <Link
                        href={item.href}
                        onClick={onClose}
                        className={`flex items-center gap-3 rounded-lg px-3 py-2.5 text-[13px] font-medium transition-all ${
                            isActive
                                ? 'bg-[#F0EDE8] text-ink font-semibold'
                                : 'text-[#8C92AC] hover:bg-[#F5F3EF] hover:text-ink'
                        } ${isSub ? 'pl-10' : ''}`}
                    >
                        {Icon && <Icon className={`h-4 w-4 flex-shrink-0 ${isActive ? 'text-ink' : 'text-[#C0BDBA]'}`} strokeWidth={isActive ? 2 : 1.5} />}
                        {item.name}
                    </Link>
                )}

                <AnimatePresence>
                    {hasChildren && isOpen && (
                        <motion.div
                            initial={{ height: 0, opacity: 0 }}
                            animate={{ height: 'auto', opacity: 1 }}
                            exit={{ height: 0, opacity: 0 }}
                            className="overflow-hidden"
                        >
                            <div className="mt-0.5 space-y-0.5">
                                {item.children.map((child: any) => (
                                    <NavItem key={child.name} item={child} isSub={true} />
                                ))}
                            </div>
                        </motion.div>
                    )}
                </AnimatePresence>
            </div>
        );
    };

    return (
        <div className="flex h-full flex-col">
            {/* Logo */}
            <div className="flex h-14 lg:h-[60px] items-center justify-between px-5 border-b border-[#F0EDE8]">
                <Link href="/admin" className="flex items-center gap-2" onClick={onClose}>
                    {branding?.logo ? (
                        <img src={branding.logo} alt={branding.name} className="h-6 w-auto object-contain" />
                    ) : (
                        <div className="h-2 w-2 rounded-full" style={{ backgroundColor: branding?.primary_color || '#ff3b3b' }} />
                    )}
                    {!branding?.logo && (
                        <span className="font-display text-lg font-bold tracking-tight">
                            {branding?.name || 'Altivate'}
                            <span className="text-[#8C92AC] font-normal text-[10px] uppercase tracking-widest ml-1">
                                . ADMIN
                            </span>
                        </span>
                    )}
                </Link>
                {/* Close — mobile only */}
                <button onClick={onClose} className="lg:hidden p-1 text-[#8C92AC] hover:text-ink transition-colors">
                    <X className="h-4 w-4" />
                </button>
            </div>

            {/* Nav */}
            <nav className="flex-1 px-3 py-5 space-y-0.5">
                <p className="text-[9px] font-semibold tracking-[0.18em] uppercase text-[#8C92AC] px-3 mb-3">
                    Workspace
                </p>
                {navigation.map((item) => (
                    <NavItem key={item.name} item={item} />
                ))}
            </nav>

            {/* Footer links */}
            <div className="px-3 pb-5 border-t border-[#F0EDE8] pt-4 space-y-0.5">
                <Link
                    href="/"
                    className="flex items-center gap-3 rounded-lg px-3 py-2.5 text-[13px] text-[#8C92AC] hover:bg-[#F5F3EF] hover:text-ink transition-all"
                >
                    <ArrowLeft className="h-4 w-4 flex-shrink-0 text-[#C0BDBA]" strokeWidth={1.5} />
                    Back to site
                </Link>
                <Link
                    href={route('logout')}
                    method="post"
                    as="button"
                    className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-[13px] text-[#8C92AC] hover:bg-red-50 hover:text-red-600 transition-all"
                >
                    <LogOut className="h-4 w-4 flex-shrink-0 text-[#C0BDBA]" strokeWidth={1.5} />
                    Logout
                </Link>
            </div>
        </div>
    );
}
