import { Head, Link, usePage } from '@inertiajs/react';
import { type ReactNode, useState, useEffect, useMemo } from 'react';
import { Toaster, toast } from 'sonner';
import {
    Home,
    Settings,
    BookOpen,
    FileSignature,
    Gamepad2,
    Sun,
    Moon,
    LogOut,
    Vote,
    UserRound,
    Award,
    Wallet,
    MoreHorizontal,
    CalendarCheck,
} from 'lucide-react';
import { cn, getInitials } from '@/lib/utils';
import { claimVisualEffectsNotice, useVisualEffects } from '@/hooks/useVisualEffects';
import BrandLogo from '@/components/BrandLogo';
import VisualEffectsToggle from '@/components/VisualEffectsToggle';
import type { PageProps } from '@/types';

interface Props {
    children: ReactNode;
    title?: string;
    hideMobileDock?: boolean;
}

interface NavItem {
    href: string;
    label: string;
    icon: any;
}

const navItems: NavItem[] = [
    { href: '/dashboard', label: 'Beranda', icon: Home },
    { href: '/materials', label: 'Materi', icon: BookOpen },
    { href: '/assignments', label: 'Tugas', icon: FileSignature },
    { href: '/games', label: 'Arena', icon: Gamepad2 },
    { href: '/student/voting', label: 'Voting', icon: Vote },
    { href: '/student/recognitions', label: 'Penghargaan', icon: Award },
    { href: '/settings', label: 'Profil', icon: Settings },
];

export default function StudentLayout({ children, title, hideMobileDock = false }: Props) {
    const { auth, flash } = usePage<PageProps>().props;
    const visibleNavItems = [
        ...navItems.slice(0, -1),
        ...(auth.user?.is_class_treasurer ? [{ href: '/student/finances', label: 'Kas Kelas', icon: Wallet }] : []),
        ...(auth.user?.is_class_secretary ? [{ href: '/student/attendance', label: 'Absensi Kelas', icon: CalendarCheck }] : []),
        navItems[navItems.length - 1],
    ];
    const dockItems = [
        ...navItems.slice(0, 3),
        auth.user?.is_class_secretary
            ? { href: '/student/attendance', label: 'Absensi', icon: CalendarCheck }
            : auth.user?.is_class_treasurer
            ? { href: '/student/finances', label: 'Kas Kelas', icon: Wallet }
            : navItems[3],
    ];
    const moreItems = visibleNavItems.filter(item => !dockItems.some(dockItem => dockItem.href === item.href));
    useVisualEffects();

    const [theme, setTheme] = useState<'light' | 'dark'>(() => {
        if (typeof window !== 'undefined') {
            const saved = localStorage.getItem('theme');
            if (saved === 'light' || saved === 'dark') {
                return saved;
            }
            return 'dark'; // Default to dark mode
        }
        return 'dark';
    });

    const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
    const [isMoreMenuOpen, setIsMoreMenuOpen] = useState(false);
    const [isScrolled, setIsScrolled] = useState(false);
    const [isScrollingDown, setIsScrollingDown] = useState(false);

    useEffect(() => {
        let lastScrollY = window.scrollY;
        const handleScroll = () => {
            const currentScrollY = window.scrollY;
            setIsScrolled(currentScrollY > 10);
            
            if (Math.abs(currentScrollY - lastScrollY) < 15) return;
            
            if (currentScrollY > lastScrollY && currentScrollY > 60) {
                setIsScrollingDown(true);
            } else {
                setIsScrollingDown(false);
            }
            lastScrollY = currentScrollY;
        };
        window.addEventListener('scroll', handleScroll, { passive: true });
        return () => window.removeEventListener('scroll', handleScroll);
    }, []);

    useEffect(() => {
        const root = window.document.documentElement;
        if (theme === 'dark') {
            root.classList.add('dark');
        } else {
            root.classList.remove('dark');
        }
        localStorage.setItem('theme', theme);
    }, [theme]);

    const toggleTheme = () => {
        setTheme(prev => (prev === 'dark' ? 'light' : 'dark'));
    };

    const currentPath = typeof window !== 'undefined' ? window.location.pathname : '';
    const isNavActive = (href: string) => currentPath === href || (href !== '/dashboard' && currentPath.startsWith(href));
    const isMoreActive = moreItems.some(item => isNavActive(item.href));

    useEffect(() => {
        setIsMoreMenuOpen(false);
    }, [currentPath]);

    useEffect(() => {
        if (!isMoreMenuOpen) return;
        const closeOnEscape = (event: KeyboardEvent) => {
            if (event.key === 'Escape') setIsMoreMenuOpen(false);
        };
        document.addEventListener('keydown', closeOnEscape);
        return () => document.removeEventListener('keydown', closeOnEscape);
    }, [isMoreMenuOpen]);

    useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('revealed');
                    }
                });
            },
            { threshold: 0.1, rootMargin: '0px 0px -30px 0px' }
        );

        const els = document.querySelectorAll('.reveal');
        els.forEach((el) => observer.observe(el));

        return () => observer.disconnect();
    }, [currentPath]); // Re-run when path changes

    useEffect(() => {
        if (flash?.success) {
            toast.success(flash.success, { id: 'success-' + Date.now() });
        }
        if (flash?.error) {
            toast.error(flash.error, { id: 'error-' + Date.now() });
        }
    }, [flash]);

    useEffect(() => {
        if (currentPath === '/settings') return;

        if (claimVisualEffectsNotice()) {
            toast.info('Mode performa otomatis aktif.', {
                id: 'visual-effects-notice',
                duration: 2500,
                closeButton: true,
            });
        }
    }, [currentPath]);

    const particles = useMemo(() =>
        Array.from({ length: 12 }, (_, i) => ({
            left: `${(i * 8.3) % 100}%`,
            bottom: `-${(i * 2.1) % 10}%`,
            animationDuration: `${8 + (i * 1.7) % 12}s`,
            animationDelay: `${(i * 0.8) % 10}s`,
            width: `${2 + (i * 0.4) % 3}px`,
            height: `${2 + (i * 0.4) % 3}px`,
        })), []
    );

    return (
        <div className="relative min-h-dvh bg-background text-text transition-colors duration-300">
            {/* CSS Aurora Mesh Background */}
            <div className="aurora-mesh fixed inset-0 z-0 opacity-40 dark:opacity-20 pointer-events-none overflow-hidden">
                <div className="aurora-orb-accent" />
                {particles.map((p, i) => (
                    <div
                        key={i}
                        className="aurora-particle"
                        style={{
                            left: p.left,
                            bottom: p.bottom,
                            animationDuration: p.animationDuration,
                            animationDelay: p.animationDelay,
                            width: p.width,
                            height: p.height,
                        }}
                    />
                ))}
            </div>

            {/* Subtle dot grid overlay */}
            <div
                className="fixed inset-0 z-0 opacity-10 dark:opacity-[0.07] pointer-events-none"
                style={{
                    backgroundImage: 'radial-gradient(currentColor 1px, transparent 1px)',
                    backgroundSize: '24px 24px',
                }}
            />

            <div className="relative z-10 flex flex-col min-h-dvh">
                <style dangerouslySetInnerHTML={{__html: `
                    .reveal {
                        opacity: 0;
                        transform: translateY(30px) scale(0.95);
                        transition: all 0.8s cubic-bezier(0.16, 1, 0.3, 1);
                    }
                    .reveal.revealed {
                        opacity: 1;
                        transform: translateY(0) scale(1);
                    }
                    .reveal-delay-1 { transition-delay: 100ms; }
                    .reveal-delay-2 { transition-delay: 200ms; }
                    .reveal-delay-3 { transition-delay: 300ms; }
                    .reveal-delay-4 { transition-delay: 400ms; }
                    .reveal-delay-5 { transition-delay: 500ms; }
                    .reveal-delay-6 { transition-delay: 600ms; }
                    .reveal-delay-7 { transition-delay: 700ms; }
                    .reveal-delay-8 { transition-delay: 800ms; }
                    .reveal-delay-9 { transition-delay: 900ms; }
                    .reveal-delay-10 { transition-delay: 1000ms; }
                `}} />
                <Toaster position="top-center" richColors theme={theme} />
                {title && <Head title={title} />}

                {/* Top App Bar */}
                <header className={cn(
                    "app-shell-surface app-shell-header sticky top-0 z-40 w-full backdrop-blur-xl transition-all duration-300",
                    isScrolled 
                        ? "bg-surface/95 border-b border-border/80 shadow-sm" 
                        : "bg-surface/80 border-b border-border/40"
                )}>
                    <div className={cn(
                        "flex items-center justify-between px-4 sm:px-6 lg:px-8 transition-all duration-300",
                        isScrolled ? "h-12 md:h-14" : "h-14 md:h-16"
                    )}>
                        {/* Logo */}
                        <div className="flex items-center gap-3">
                            <BrandLogo
                                alt="Ikon UtiClass"
                                className={cn("object-contain drop-shadow-md transition-all duration-300", isScrolled ? "h-6 w-6" : "h-7 w-7 md:h-8 md:w-8")}
                            />
                            <span className={cn("font-extrabold tracking-tight text-text transition-all duration-300", isScrolled ? "text-base" : "text-base md:text-lg")}>
                                UtiClass
                            </span>
                        </div>

                    {/* Desktop Navigation (Visible only on md and up) */}
                    <div className="hidden md:flex flex-1 items-center justify-center gap-1">
                        {visibleNavItems.map((item) => {
                            const Icon = item.icon;
                            const isActive = currentPath === item.href || (item.href !== '/dashboard' && currentPath.startsWith(item.href));

                            return (
                                <Link
                                    key={item.href}
                                    href={item.href}
                                    className={cn(
                                        "flex items-center gap-2 px-4 py-2 rounded-full transition-colors text-sm font-medium",
                                        isActive 
                                            ? "bg-primary-500/10 text-primary-400" 
                                            : "text-text-muted hover:text-text hover:bg-surface-hover/50"
                                    )}
                                >
                                    <Icon className="h-4 w-4" />
                                    {item.label}
                                </Link>
                            );
                        })}
                    </div>

                    <div className="flex items-center gap-3">
                        <VisualEffectsToggle />

                        <button
                            onClick={toggleTheme}
                            className="flex h-9 w-9 items-center justify-center rounded-full hover:bg-surface-hover/50 text-text-muted hover:text-text transition-colors"
                            aria-label="Toggle Theme"
                        >
                            {theme === 'dark' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
                        </button>
                        <div className="relative">
                            <button
                                onClick={() => {
                                    setIsMoreMenuOpen(false);
                                    setIsUserMenuOpen(!isUserMenuOpen);
                                }}
                                className="flex h-9 w-9 items-center justify-center rounded-full bg-primary-500/10 text-sm font-semibold text-primary-400 hover:bg-primary-500/20 transition-colors"
                                aria-label="User menu"
                            >
                                {getInitials(auth.user.name)}
                            </button>
                            
                            {isUserMenuOpen && (
                                <>
                                    <div className="fixed inset-0 z-40" onClick={() => setIsUserMenuOpen(false)} />
                                    <div className="absolute right-0 mt-2 w-48 rounded-xl bg-surface border border-border shadow-lg py-1 z-50 overflow-hidden">
                                        <div className="px-4 py-2.5 border-b border-border/50 bg-surface-hover/30">
                                            <p className="text-xs font-semibold text-text line-clamp-2 leading-snug wrap-break-word">{auth.user.name}</p>
                                        </div>
                                        <div className="p-1">
                                            <Link
                                                href="/student/profile"
                                                className="flex items-center gap-2 w-full text-left px-3 py-2 text-xs md:text-sm text-text hover:bg-surface-hover rounded-lg transition-colors"
                                                onClick={() => setIsUserMenuOpen(false)}
                                            >
                                                <UserRound className="w-4 h-4 text-text-muted" />
                                                Biodata Saya
                                            </Link>
                                            <Link
                                                href="/student/recognitions"
                                                className="flex items-center gap-2 w-full text-left px-3 py-2 text-xs md:text-sm text-text hover:bg-surface-hover rounded-lg transition-colors"
                                                onClick={() => setIsUserMenuOpen(false)}
                                            >
                                                <Award className="w-4 h-4 text-text-muted" />
                                                Penghargaan Saya
                                            </Link>
                                            <Link
                                                href="/settings"
                                                className="flex items-center gap-2 w-full text-left px-3 py-2 text-xs md:text-sm text-text hover:bg-surface-hover rounded-lg transition-colors"
                                                onClick={() => setIsUserMenuOpen(false)}
                                            >
                                                <Settings className="w-4 h-4 text-text-muted" />
                                                Atur Profil
                                            </Link>
                                            <Link
                                                href={route('logout')}
                                                method="post"
                                                as="button"
                                                className="flex items-center gap-2 w-full text-left px-3 py-2 text-xs md:text-sm text-rose-500 hover:bg-rose-500/10 rounded-lg transition-colors"
                                            >
                                                <LogOut className="w-4 h-4" />
                                                Keluar
                                            </Link>
                                        </div>
                                    </div>
                                </>
                            )}
                        </div>
                    </div>
                </div>
            </header>

                {/* Main Content Area */}
                <main className={cn(
                    "flex-1 mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8 transition-all duration-300",
                    hideMobileDock ? "pb-6" : "mobile-dock-content pb-24 md:pb-6"
                )}>
                    {children}
                </main>

            {/* Floating Bottom Navigation Dock (Visible only on mobile/tablet) */}
            {!hideMobileDock && isMoreMenuOpen && (
                <button type="button" aria-label="Tutup menu lainnya" onClick={() => setIsMoreMenuOpen(false)}
                    className="fixed inset-0 z-[45] md:hidden" />
            )}
            {!hideMobileDock && <div className="app-mobile-dock-shell mobile-safe-dock fixed bottom-5 left-0 right-0 z-50 md:hidden flex justify-center px-4 transition-all duration-300 pointer-events-none">
                <div className={cn(
                    "app-mobile-dock relative grid grid-cols-5 items-center rounded-full border border-white/20 dark:border-white/10 bg-surface/50 dark:bg-surface/40 backdrop-blur-xl shadow-lg dark:shadow-[0_8px_30px_rgba(0,0,0,0.6)] transition-all duration-300 ease-in-out pointer-events-auto",
                    isScrollingDown && !isMoreMenuOpen
                        ? "h-13 w-64 max-w-full px-2"
                        : "h-17 w-full max-w-md px-2"
                )}>
                    {isMoreMenuOpen && (
                        <nav id="student-more-menu" aria-label="Menu lainnya"
                            className="absolute bottom-full right-0 mb-2 max-h-[60dvh] w-44 overflow-y-auto rounded-xl border border-border bg-surface p-1.5 shadow-xl dark:bg-slate-950">
                            {moreItems.map(item => {
                                const Icon = item.icon;
                                return (
                                    <Link key={item.href} href={item.href} onClick={() => setIsMoreMenuOpen(false)}
                                        aria-current={isNavActive(item.href) ? 'page' : undefined}
                                        className={cn('flex min-h-11 items-center gap-2.5 rounded-lg px-3 py-2 text-sm font-medium',
                                            isNavActive(item.href) ? 'bg-primary-500/10 text-primary-400' : 'text-text-muted hover:bg-surface-hover hover:text-text')}>
                                        <Icon className="h-4 w-4 shrink-0" />{item.label}
                                    </Link>
                                );
                            })}
                        </nav>
                    )}
                    {dockItems.map((item) => {
                        const Icon = item.icon;
                        const isActive = currentPath === item.href || (item.href !== '/dashboard' && currentPath.startsWith(item.href));

                        return (
                            <Link
                                key={item.href}
                                href={item.href}
                                aria-label={item.label}
                                aria-current={isActive ? 'page' : undefined}
                                className="group relative flex min-w-0 flex-col items-center justify-center h-full transition-all duration-300"
                            >
                                {/* Active Indicator Pill */}
                                <div className={cn(
                                    "absolute inset-0 m-auto rounded-full transition-all duration-300",
                                    isScrollingDown && !isMoreMenuOpen ? "h-9 w-9" : "h-13 w-full max-w-18",
                                    isActive ? "bg-primary-500/20 scale-100 opacity-100" : "scale-50 opacity-0"
                                )} />
                                
                                <Icon className={cn(
                                    "relative z-10 transition-all duration-300",
                                    isActive ? "h-6 w-6 text-primary-400" : "h-5 w-5 text-text-muted group-hover:text-text-light",
                                    isScrollingDown && !isMoreMenuOpen && !isActive ? "h-5.5 w-5.5" : ""
                                )} />
                                
                                <span className={cn(
                                    "relative z-10 text-[10px] font-medium transition-all duration-300 origin-bottom",
                                    isActive ? "text-primary-400 font-bold" : "text-text-muted group-hover:text-text-light",
                                    isScrollingDown && !isMoreMenuOpen
                                        ? "max-h-0 opacity-0 scale-0 pointer-events-none mt-0 overflow-hidden" 
                                        : "max-h-4 opacity-100 mt-0.5 scale-100"
                                )}>
                                    {item.label}
                                </span>
                            </Link>
                        );
                    })}
                    <button type="button" aria-label="Menu lainnya" aria-expanded={isMoreMenuOpen}
                        aria-controls="student-more-menu" onClick={() => {
                            setIsUserMenuOpen(false);
                            setIsMoreMenuOpen(open => !open);
                        }}
                        className="group relative flex h-full min-w-0 flex-col items-center justify-center">
                        <div className={cn('absolute inset-0 m-auto rounded-full transition-all duration-300',
                            isScrollingDown && !isMoreMenuOpen ? 'h-9 w-9' : 'h-13 w-full max-w-18',
                            isMoreActive || isMoreMenuOpen ? 'bg-primary-500/20 opacity-100' : 'opacity-0')} />
                        <MoreHorizontal className={cn('relative z-10 h-6 w-6',
                            isMoreActive || isMoreMenuOpen ? 'text-primary-400' : 'text-text-muted group-hover:text-text')} />
                        <span className={cn('relative z-10 text-[10px] font-medium transition-all duration-300',
                            isMoreActive || isMoreMenuOpen ? 'text-primary-400 font-bold' : 'text-text-muted',
                            isScrollingDown && !isMoreMenuOpen ? 'max-h-0 overflow-hidden opacity-0' : 'mt-0.5 max-h-4 opacity-100')}>
                            Lainnya
                        </span>
                    </button>
                </div>
            </div>}
            </div>
        </div>
    );
}
