import React, { useState } from 'react';
import { Link, usePage, router } from '@inertiajs/react';
import { useEditMode } from '../Contexts/EditModeContext';
import { APP_NAME, APP_TAGLINE } from '../constants/brand';

export const navLinks = [
    { name: 'Home', href: '/beranda', icon: 'fa-house', match: (url) => url === '/beranda' },
    { name: 'Materi', href: '/materi', icon: 'fa-book-open', match: (url) => url.startsWith('/materi') },
    { name: 'Latihan', href: '/evaluasi', icon: 'fa-pen-to-square', match: (url) => url.startsWith('/evaluasi') },
    { name: 'Audio', href: '/praktik-percakapan', icon: 'fa-headphones', match: (url) => url.startsWith('/praktik-percakapan') },
    { name: 'Budaya', href: '/budaya', icon: 'fa-mosque', match: (url) => url.startsWith('/budaya') },
    { name: 'Profil', href: '/beranda', icon: 'fa-user', match: () => false },
];

export function LogoIcon({ className = 'w-10 h-10' }) {
    return (
        <img
            src="/images/sidikpro-logo.png"
            alt={APP_NAME}
            className={`${className} object-contain`}
        />
    );
}

export default function AppLayout({ children }) {
    const { props, url } = usePage();
    const { auth } = props;
    const [showUserMenu, setShowUserMenu] = useState(false);
    const { isEditMode, setIsEditMode } = useEditMode();
    const userName = auth?.user?.name?.split(' ')[0] || 'Ahmad';
    const isAdmin = auth?.user?.email === 'admin@shiddiqpro.com';

    const handleLogout = () => router.post('/logout');

    return (
        <div className="app-layout app-shell min-h-screen bg-[#f0f4f8] font-['Nunito'] text-slate-800">
            <header className="sticky top-0 z-50 bg-white border-b border-slate-100 shadow-sm">
                <div className="flex items-center gap-2 sm:gap-4 px-3 sm:px-5 h-[68px] min-w-0">
                    <Link href="/beranda" className="flex items-center gap-2 sm:gap-3 shrink-0 min-w-0 max-w-[55%] sm:max-w-none">
                        <LogoIcon className="w-9 h-9 sm:w-10 sm:h-10 shrink-0" />
                        <div className="min-w-0 hidden sm:block">
                            <h1 className="font-extrabold text-[10px] sm:text-[12px] md:text-[14px] text-teal-700 leading-tight break-words line-clamp-2">{APP_NAME}</h1>
                            <p className="text-[10px] sm:text-[11px] text-slate-400 font-medium truncate hidden md:block">{APP_TAGLINE}</p>
                        </div>
                    </Link>

                    <div className="flex-1 max-w-xl mx-auto hidden md:block">
                        <div className="relative">
                            <i className="fas fa-search absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 text-sm"></i>
                            <input
                                type="text"
                                placeholder="Cari materi, topik, atau latihan..."
                                className="w-full pl-11 pr-24 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm text-slate-600 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-teal-500/30 focus:border-teal-400"
                            />
                            <span className="absolute right-3 top-1/2 -translate-y-1/2 text-[11px] text-slate-400 bg-white border border-slate-200 rounded-md px-1.5 py-0.5 font-medium">
                                Ctrl + K
                            </span>
                        </div>
                    </div>

                    <div className="flex items-center gap-2 sm:gap-3 ml-auto shrink-0">
                        <button type="button" className="hidden sm:flex w-10 h-10 rounded-xl bg-slate-50 border border-slate-200 items-center justify-center text-slate-500 hover:bg-slate-100 transition-colors">
                            <i className="fas fa-bell text-sm"></i>
                        </button>

                        {auth?.user ? (
                            <div className="relative">
                                <button
                                    type="button"
                                    onClick={() => setShowUserMenu(!showUserMenu)}
                                    className="flex items-center gap-2.5 pl-1 pr-3 py-1 rounded-full hover:bg-slate-50 transition-colors"
                                >
                                    <div className="w-9 h-9 rounded-full bg-gradient-to-br from-teal-400 to-teal-600 flex items-center justify-center text-white font-bold text-sm">
                                        {auth.user.name.charAt(0).toUpperCase()}
                                    </div>
                                    <div className="hidden sm:block text-left">
                                        <p className="text-[11px] text-slate-400 leading-none">Selamat datang,</p>
                                        <p className="text-sm font-bold text-slate-700 leading-tight">{userName}</p>
                                    </div>
                                    <i className={`fas fa-chevron-down text-[10px] text-slate-400 transition-transform ${showUserMenu ? 'rotate-180' : ''}`}></i>
                                </button>
                                {showUserMenu && (
                                    <>
                                        <div className="fixed inset-0 z-40" onClick={() => setShowUserMenu(false)}></div>
                                        <div className="absolute right-0 mt-1 w-52 bg-white rounded-xl shadow-xl border border-slate-100 py-1 z-50">
                                            <div className="px-4 py-2.5 border-b border-slate-100">
                                                <p className="text-sm font-bold text-slate-700">{auth.user.name}</p>
                                                <p className="text-xs text-slate-400">{auth.user.email}</p>
                                            </div>
                                            {isAdmin && (
                                                <>
                                                    <Link
                                                        href="/dashboard"
                                                        onClick={() => setShowUserMenu(false)}
                                                        className="w-full px-4 py-2.5 text-left text-sm font-semibold text-slate-600 hover:bg-slate-50 flex items-center gap-2"
                                                    >
                                                        <i className="fas fa-tachometer-alt text-teal-600"></i> Dashboard Admin
                                                    </Link>
                                                    {url.startsWith('/materi') && (
                                                        <button
                                                            type="button"
                                                            onClick={() => { setIsEditMode(!isEditMode); setShowUserMenu(false); }}
                                                            className="w-full px-4 py-2.5 text-left text-sm font-semibold text-slate-600 hover:bg-slate-50 flex items-center gap-2"
                                                        >
                                                            <i className={`fas ${isEditMode ? 'fa-edit' : 'fa-cog'} text-amber-500`}></i>
                                                            {isEditMode ? 'Edit Mode: Aktif' : 'Edit Mode'}
                                                        </button>
                                                    )}
                                                </>
                                            )}
                                            <button
                                                type="button"
                                                onClick={handleLogout}
                                                className="w-full px-4 py-2.5 text-left text-sm text-red-500 hover:bg-red-50 flex items-center gap-2"
                                            >
                                                <i className="fas fa-sign-out-alt"></i> Keluar
                                            </button>
                                        </div>
                                    </>
                                )}
                            </div>
                        ) : (
                            <Link href="/login" className="flex items-center gap-2.5 pl-1 pr-3 py-1 rounded-full hover:bg-slate-50 transition-colors">
                                <div className="w-9 h-9 rounded-full bg-gradient-to-br from-amber-300 to-amber-500 flex items-center justify-center">
                                    <i className="fas fa-user text-white text-sm"></i>
                                </div>
                                <div className="hidden sm:block text-left">
                                    <p className="text-[11px] text-slate-400 leading-none">Selamat datang,</p>
                                    <p className="text-sm font-bold text-slate-700 leading-tight">{userName}</p>
                                </div>
                                <i className="fas fa-chevron-down text-[10px] text-slate-400"></i>
                            </Link>
                        )}
                    </div>
                </div>
            </header>

            <div className="flex min-w-0">
                <aside className="hidden lg:flex flex-col w-[220px] shrink-0 bg-white border-r border-slate-100 min-h-[calc(100vh-68px)] sticky top-[68px] h-[calc(100vh-68px)]">
                    <nav className="p-4 space-y-1">
                        {navLinks.map((link) => {
                            const active = link.match(url);
                            return (
                                <Link
                                    key={link.name}
                                    href={link.href}
                                    className={`flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-semibold transition-all ${
                                        active
                                            ? 'bg-teal-600 text-white shadow-md shadow-teal-600/20'
                                            : 'text-slate-500 hover:bg-slate-50 hover:text-slate-700'
                                    }`}
                                >
                                    <i className={`fas ${link.icon} w-4 text-center text-[13px]`}></i>
                                    {link.name}
                                </Link>
                            );
                        })}
                    </nav>

                    <div className="px-4 mt-2">
                        <div className="bg-slate-50 rounded-2xl p-4 border border-slate-100">
                            <div className="flex items-center gap-2 mb-2">
                                <i className="fas fa-trophy text-amber-500 text-sm"></i>
                                <span className="text-xs font-bold text-slate-600">Target Harian</span>
                            </div>
                            <p className="text-[13px] font-bold text-slate-700 mb-2">15 menit belajar</p>
                            <div className="h-2 bg-slate-200 rounded-full overflow-hidden">
                                <div className="h-full bg-teal-500 rounded-full" style={{ width: '53%' }}></div>
                            </div>
                            <div className="flex justify-between mt-1.5">
                                <span className="text-[10px] text-slate-400">8 menit selesai</span>
                                <span className="text-[10px] text-slate-400">15 menit</span>
                            </div>
                        </div>
                    </div>

                    <div className="mt-auto p-4">
                        <div className="bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-4 border border-amber-100 relative overflow-hidden">
                            <p className="text-[12px] font-bold text-slate-600 leading-relaxed pr-8 relative z-10">
                                Terus belajar setiap hari untuk masa depan yang lebih baik.
                            </p>
                            <div className="absolute -bottom-2 -right-2 text-4xl opacity-20">🏮</div>
                        </div>
                    </div>
                </aside>

                <main className="flex-1 min-w-0 max-w-full p-4 md:p-5 lg:p-6 pb-24 lg:pb-6 overflow-x-clip">
                    {children}
                </main>
            </div>

            <nav className="lg:hidden fixed bottom-0 w-full bg-white border-t border-slate-100 z-50 flex justify-around py-2 shadow-[0_-4px_20px_rgba(0,0,0,0.06)]">
                {navLinks.slice(0, 5).map((link) => {
                    const active = link.match(url);
                    return (
                        <Link
                            key={link.name}
                            href={link.href}
                            className={`flex flex-col items-center px-2 py-1.5 rounded-xl transition-all ${active ? 'text-teal-600' : 'text-slate-400'}`}
                        >
                            <i className={`fas ${link.icon} text-base mb-0.5`}></i>
                            <span className="text-[9px] font-bold">{link.name}</span>
                        </Link>
                    );
                })}
            </nav>
        </div>
    );
}
