'use client';

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import {
    LayoutDashboard, Users, FileText, Briefcase, Image as ImageIcon,
    LogOut, Shield, Home, Target, BookOpen, Newspaper, Trophy,
    Mic2, MessageCircle, Award, Zap, Menu, Calendar, Search, Bell,
    ChevronRight
} from "lucide-react";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import { SessionProvider, useSession, signOut } from "next-auth/react";
import { useEffect } from "react";
import ChangePasswordDialog from "@/components/admin/change-password-dialog";

type NavItem = { href: string; label: string; icon: React.ElementType; adminOnly: boolean; };

const MENU_LINKS: NavItem[] = [
    { href: '/admin', label: 'Dashboard', icon: LayoutDashboard, adminOnly: false },
    { href: '/admin/pengurus', label: 'Pengurus', icon: Users, adminOnly: true },
    { href: '/admin/kabinet', label: 'Kabinet', icon: Shield, adminOnly: true },
    { href: '/admin/parlemen', label: 'Parlemen', icon: Newspaper, adminOnly: true },
    { href: '/admin/bidang', label: 'Bidang & Lembaga', icon: Briefcase, adminOnly: false },
    { href: '/admin/ukk', label: 'UKK', icon: Zap, adminOnly: true },
    { href: '/admin/profil', label: 'Profil Himpunan', icon: FileText, adminOnly: true },
];

const KONTEN_LINKS: NavItem[] = [
    { href: '/admin/acara', label: 'Acara', icon: Calendar, adminOnly: false },
    { href: '/admin/shortlink', label: 'LASER', icon: Target, adminOnly: false },
    { href: '/admin/bearr', label: 'BEARR', icon: BookOpen, adminOnly: false },
    { href: '/admin/kurikulum', label: 'Kurikulum Matkul', icon: Target, adminOnly: true },
];

const MEDIA_LINKS: NavItem[] = [
    { href: '/admin/laporan-keuangan', label: 'Lap. Keuangan', icon: FileText, adminOnly: true },
    { href: '/admin/rangers-talk', label: 'Rangers Talk', icon: Mic2, adminOnly: true },
    { href: '/admin/awardee', label: 'Awardee PH', icon: Award, adminOnly: true },
    { href: '/admin/berita', label: 'Berita HMF', icon: Newspaper, adminOnly: true },
    { href: '/admin/prestasi', label: 'Prestasi', icon: Trophy, adminOnly: true },
    { href: '/admin/komentar', label: 'Komentar Tamu', icon: MessageCircle, adminOnly: true }, // Put this here to preserve feature
];

function NavLink({ item, pathname }: { item: NavItem; pathname: string }) {
    const isActive = pathname === item.href || (item.href !== '/admin' && pathname.startsWith(item.href));
    return (
        <Link
            href={item.href}
            className={`group flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-all duration-200 ${
                isActive
                    ? 'bg-[#1e3a5f] text-white shadow-sm'
                    : 'text-white/55 hover:text-white hover:bg-white/8'
            }`}
        >
            <item.icon className={`h-4 w-4 shrink-0 ${isActive ? 'text-blue-300' : 'text-white/40 group-hover:text-white/70'}`} />
            <span className="truncate">{item.label}</span>
            {isActive && <ChevronRight className="ml-auto h-3 w-3 text-blue-300/70" />}
        </Link>
    );
}

function NavSection({ title, items, isAdmin, pathname }: { title: string; items: NavItem[]; isAdmin: boolean; pathname: string }) {
    const filtered = isAdmin ? items : items.filter(l => !l.adminOnly);
    if (!filtered.length) return null;
    return (
        <div className="mb-5">
            <p className="px-3 mb-1.5 text-[10px] font-bold tracking-widest uppercase text-white/25">{title}</p>
            <div className="space-y-0.5">
                {filtered.map(item => <NavLink key={item.href} item={item} pathname={pathname} />)}
            </div>
        </div>
    );
}

function SidebarContent({ session, isAdmin, pathname, onLogout }: {
    session: any; isAdmin: boolean; pathname: string; onLogout: () => void;
}) {
    return (
        <div className="flex flex-col h-full bg-[#050E1F]">
            {/* Brand - Removed per user request */}
            <div className="flex h-[20px] shrink-0"></div>

            {/* Nav */}
            <div className="flex-1 overflow-y-auto py-5 px-3 scrollbar-hide">
                <NavSection title="Menu" items={MENU_LINKS} isAdmin={isAdmin} pathname={pathname} />
                <NavSection title="Konten" items={KONTEN_LINKS} isAdmin={isAdmin} pathname={pathname} />
                <NavSection title="Media" items={MEDIA_LINKS} isAdmin={isAdmin} pathname={pathname} />
            </div>

            {/* Bottom */}
            <div className="shrink-0 px-3 py-4 border-t border-white/8 space-y-1">
                {/* User Profile - Removed per user request */}
                <ChangePasswordDialog />
                <Link
                    href="/"
                    className="w-full flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium text-white/50 hover:text-white hover:bg-white/8 transition-all duration-200"
                >
                    <Home className="h-4 w-4 shrink-0" />
                    Kembali ke Website
                </Link>
                <button
                    onClick={onLogout}
                    className="w-full flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium text-[#E63946]/70 hover:text-[#E63946] hover:bg-[#E63946]/10 transition-all duration-200"
                >
                    <LogOut className="h-4 w-4 shrink-0" />
                    Logout
                </button>
            </div>
        </div>
    );
}

function AdminLayoutContent({ children }: { children: React.ReactNode }) {
    const { data: session, status } = useSession();
    const router = useRouter();
    const pathname = usePathname();

    useEffect(() => {
        if (status === 'unauthenticated') router.replace('/login');
    }, [status, router]);

    if (status === 'loading') {
        return (
            <div className="min-h-screen flex items-center justify-center bg-slate-100 text-slate-500 text-sm">
                Memuat sesi admin...
            </div>
        );
    }

    if (status === 'unauthenticated') return null;

    const isAdmin = (session?.user as any)?.username === 'admin';

    const handleLogout = async () => {
        await signOut({ callbackUrl: '/' });
    };

    return (
        <div className="flex w-full min-h-screen">

            {/* ── SIDEBAR KIRI: GELAP ───────────────────────────── */}
            <aside className="hidden lg:flex flex-col w-[240px] xl:w-[260px] shrink-0 fixed left-0 top-0 h-full z-30 shadow-xl shadow-black/30">
                <SidebarContent session={session} isAdmin={isAdmin} pathname={pathname} onLogout={handleLogout} />
            </aside>

            {/* ── MAIN KANAN: TERANG / PUTIH ───────────────────────── */}
            <div className="flex flex-col flex-1 min-w-0 lg:pl-[240px] xl:pl-[260px] bg-slate-50 text-slate-800">

                {/* Topbar */}
                <header className="sticky top-0 z-30 flex h-14 items-center gap-4 px-4 md:px-6 border-b border-slate-200 bg-white shadow-sm">
                    {/* Mobile hamburger */}
                    <div className="lg:hidden">
                        <Sheet>
                            <SheetTrigger asChild>
                                <Button variant="ghost" size="icon" className="text-slate-500 hover:text-slate-800 hover:bg-slate-100">
                                    <Menu className="h-5 w-5" />
                                </Button>
                            </SheetTrigger>
                            <SheetContent side="left" className="w-[240px] p-0 border-0">
                                <SidebarContent session={session} isAdmin={isAdmin} pathname={pathname} onLogout={handleLogout} />
                            </SheetContent>
                        </Sheet>
                    </div>

                    {/* Search */}
                    <div className="flex-1 max-w-sm">
                        <div className="relative">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                            <input
                                type="text"
                                placeholder="Cari menu..."
                                className="w-full pl-9 pr-4 py-1.5 text-sm bg-slate-100 border border-slate-200 rounded-lg text-slate-700 placeholder:text-slate-400 focus:outline-none focus:border-blue-400 focus:bg-white transition-all"
                            />
                        </div>
                    </div>

                    {/* Right side */}
                    <div className="ml-auto flex items-center gap-2">
                        <button className="p-2 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-all">
                            <Bell className="h-4 w-4" />
                        </button>
                        {session?.user && (
                            <div className="flex items-center gap-2.5 pl-2 border-l border-slate-200 ml-1">
                                <div className="w-8 h-8 rounded-full bg-gradient-to-tr from-[#E63946] to-[#c9a24d] flex items-center justify-center text-white text-xs font-bold shadow-sm">
                                    {session.user.name?.charAt(0).toUpperCase() ?? 'A'}
                                </div>
                                <div className="hidden md:block">
                                    <p className="text-xs font-semibold text-slate-700 leading-tight">{session.user.name}</p>
                                    <p className="text-[10px] text-slate-400">{isAdmin ? 'Administrator' : 'Pengurus'}</p>
                                </div>
                            </div>
                        )}
                    </div>
                </header>

                {/* Page Content */}
                <main className="flex-1 p-4 md:p-6 lg:p-8">
                    {children}
                </main>
            </div>
        </div>
    );
}

export default function AdminLayout({ children }: { children: React.ReactNode }) {
    return (
        <SessionProvider>
            <AdminLayoutContent>{children}</AdminLayoutContent>
        </SessionProvider>
    );
}
