import { Link, usePage } from '@inertiajs/react';
import {
    Award,
    Bell,
    Bookmark,
    BookOpen,
    CalendarDays,
    Compass,
    LayoutGrid,
    Map,
    Megaphone,
    Menu,
    MoreHorizontal,
    Radio,
    Receipt,
    ShoppingCart,
    Trophy,
} from 'lucide-react';

import AppLogo from '@/components/app-logo';
import AppLogoIcon from '@/components/app-logo-icon';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import { UserMenuContent } from '@/components/user-menu-content';
import { useCurrentUrl } from '@/hooks/use-current-url';
import { useInitials } from '@/hooks/use-initials';
import { cn } from '@/lib/utils';
import { dashboard } from '@/routes';
import type { Auth, NavItem } from '@/types';

const primaryNavItems: NavItem[] = [
    { title: 'Dashboard', href: dashboard(), icon: LayoutGrid },
    { title: 'Jelajahi Kelas', href: '/courses', icon: Compass },
    { title: 'Kelas Saya', href: '/my-courses', icon: BookOpen },
    { title: 'Planner', href: '/planner', icon: CalendarDays },
    { title: 'Paket Belajar', href: '/learning-paths', icon: Map },
    { title: 'Live Class', href: '/live-classes', icon: Radio },
    { title: 'Leaderboard', href: '/leaderboard', icon: Trophy },
];


const moreNavItems: NavItem[] = [
    { title: 'Bookmark', href: '/bookmarks', icon: Bookmark },
    { title: 'Pengumuman', href: '/announcements', icon: Megaphone },
    { title: 'Sertifikat', href: '/certificates', icon: Award },
    { title: 'Riwayat Beli', href: '/orders', icon: Receipt },
];

const allNavItems = [...primaryNavItems, ...moreNavItems];

export function StudentTopBar() {
    const { auth, unreadNotificationsCount = 0, cartCount = 0 } = usePage<{ auth: Auth; unreadNotificationsCount: number; cartCount: number }>().props;
    const user = auth.user;
    const getInitials = useInitials();
    const { isCurrentOrParentUrl, currentUrl } = useCurrentUrl();

    const isPensiunan = user?.ui_theme === 'pensiunan';

    const currentPrimaryItems = isPensiunan
        ? [
              { title: 'Dashboard', href: dashboard(), icon: LayoutGrid },
              { title: 'Jelajahi Kelas', href: '/courses', icon: Compass },
              { title: 'Kelas Saya', href: '/my-courses', icon: BookOpen },
              { title: 'Sertifikat', href: '/certificates', icon: Award },
          ]
        : primaryNavItems;


    const currentMoreItems = isPensiunan ? [] : moreNavItems;

    return (
        <header className="sticky top-0 z-50 border-b border-gray-100 bg-white">
            <div className="mx-auto grid h-16 max-w-screen-xl grid-cols-[auto_1fr_auto] items-center gap-4 px-5">
                {/* Left: logo + mobile hamburger */}
                <div className="flex items-center gap-2">
                    <Link href={dashboard()} prefetch className="shrink-0">
                        <AppLogo />
                    </Link>
                </div>

                {/* Center: desktop nav — pill container */}
                <nav className="hidden items-center justify-center lg:flex">
                    <div className="flex items-center gap-0.5 rounded-full bg-gray-100 p-1">
                        {currentPrimaryItems.map((item) => {
                            let active = isCurrentOrParentUrl(item.href);

                            // Highlight "Kelas Saya" instead of "Jelajahi Kelas" if in the learning area
                            const isLearningArea = currentUrl.includes('/learn') || currentUrl.includes('/quiz') || currentUrl.includes('/assignment') || currentUrl.startsWith('/my-courses/');
                            if (isLearningArea) {
                                if (item.href === '/my-courses') {
                                    active = true;
                                } else if (item.href === '/courses') {
                                    active = false;
                                }
                            }

                            return (
                                <Link
                                    key={item.title}
                                    href={item.href}
                                    prefetch
                                    className={cn(
                                        'flex items-center gap-1.5 rounded-full px-3.5 py-1.5 text-sm font-medium transition-all duration-150',
                                        active
                                            ? 'bg-gray-900 text-white shadow-sm'
                                            : 'text-gray-500 hover:bg-white hover:text-gray-900 hover:shadow-sm',
                                    )}
                                >
                                    {item.icon && (
                                        <item.icon
                                            className={cn(
                                                'h-3.5 w-3.5 shrink-0',
                                                active ? 'text-white' : 'text-gray-400',
                                            )}
                                        />
                                    )}
                                    {item.title}
                                </Link>
                            );
                        })}

                        {/* More dropdown inside the pill container */}
                        {currentMoreItems.length > 0 && (
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <button className="flex items-center gap-1.5 rounded-full px-3.5 py-1.5 text-sm font-medium text-gray-500 transition-all duration-150 hover:bg-white hover:text-gray-900 hover:shadow-sm">
                                        <MoreHorizontal className="h-3.5 w-3.5" />
                                        Lainnya
                                    </button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="center" className="w-48 rounded-xl p-1.5">
                                    {currentMoreItems.map((item) => {
                                        const active = isCurrentOrParentUrl(item.href);
                                        return (
                                            <DropdownMenuItem key={item.title} asChild>
                                                <Link
                                                    href={item.href}
                                                    className={cn(
                                                        'flex cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-sm',
                                                        active ? 'bg-gray-900 text-white' : 'text-gray-600',
                                                    )}
                                                >
                                                    {item.icon && (
                                                        <item.icon
                                                            className={cn(
                                                                'h-4 w-4',
                                                                active ? 'text-white' : 'text-gray-400',
                                                            )}
                                                        />
                                                    )}
                                                    {item.title}
                                                </Link>
                                            </DropdownMenuItem>
                                        );
                                    })}
                                </DropdownMenuContent>
                            </DropdownMenu>
                        )}
                    </div>
                </nav>

                {/* Right: cart + bell + avatar */}
                <div className="flex items-center justify-end gap-1">
                    <Link
                        href="/cart"
                        className="relative flex h-9 w-9 items-center justify-center rounded-full text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900"
                    >
                        <ShoppingCart className="h-4.5 w-4.5" />
                        {cartCount > 0 && (
                            <span className="absolute top-0 right-0 flex h-4 w-4 items-center justify-center rounded-full bg-blue-500 text-[10px] font-bold text-white">
                                {cartCount > 9 ? '9+' : cartCount}
                            </span>
                        )}
                    </Link>
                    <Link
                        href="/notifications"
                        className="relative flex h-9 w-9 items-center justify-center rounded-full text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900"
                    >
                        <Bell className="h-4.5 w-4.5" />
                        {unreadNotificationsCount > 0 && (
                            <span className="absolute top-0 right-0 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white">
                                {unreadNotificationsCount > 9 ? '9+' : unreadNotificationsCount}
                            </span>
                        )}
                    </Link>

                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="ghost" className="h-9 w-9 rounded-full p-0.5">
                                <Avatar className="h-8 w-8">
                                    <AvatarImage src={user?.avatar} alt={user?.name} />
                                    <AvatarFallback className="bg-gray-900 text-white text-xs font-semibold">
                                        {getInitials(user?.name ?? '')}
                                    </AvatarFallback>
                                </Avatar>
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent className="w-56" align="end">
                            {user && <UserMenuContent user={user} />}
                        </DropdownMenuContent>
                    </DropdownMenu>
                </div>
            </div>
        </header>
    );
}
