import { Link, usePage } from '@inertiajs/react';
import type { LucideIcon } from 'lucide-react';
import {
    Award,
    BarChart3,
    ChevronsUpDown,
    ExternalLink,
    ImageIcon,
    Inbox,
    Info,
    LayoutDashboard,
    Layers,
    MessageSquareQuote,
    Newspaper,
    Package,
    PanelsTopLeft,
    Settings,
    Shield,
    Ship,
    Users,
    Wrench,
} from 'lucide-react';
import type { ComponentProps } from 'react';
import { NavUser } from '@/components/nav-user';
import SiteLogo from '@/components/site-logo';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    Sidebar,
    SidebarContent,
    SidebarFooter,
    SidebarGroup,
    SidebarGroupLabel,
    SidebarHeader,
    SidebarMenu,
    SidebarMenuBadge,
    SidebarMenuButton,
    SidebarMenuItem,
    SidebarRail,
    useSidebar,
} from '@/components/ui/sidebar';
import { useSettings } from '@/hooks/useSettings';
import { dashboard } from '@/routes/admin';
import { index as aboutIndex } from '@/routes/admin/about';
import { index as blogIndex } from '@/routes/admin/blog';
import { index as heroesIndex } from '@/routes/admin/heroes';
import { index as mediaIndex } from '@/routes/admin/media';
import { index as messagesIndex } from '@/routes/admin/messages';
import { index as rolesIndex } from '@/routes/admin/roles';
import { index as servicesIndex } from '@/routes/admin/services';
import { index as settingsIndex } from '@/routes/admin/settings';
import { index as testimonialsIndex } from '@/routes/admin/testimonials';
import { index as usersIndex } from '@/routes/admin/users';
import { index as visitorsIndex } from '@/routes/admin/visitors';

type SidebarNavItem = {
    title: string;
    // Route helper mengembalikan `RouteDefinition` (bukan string polos) —
    // tipe href mengikuti pola yang dipakai DataTableRowActions.
    href: ComponentProps<typeof Link>['href'];
    icon: LucideIcon;
    active?: boolean;
    /** Badge jumlah (mis. pesan belum dibaca) — ditampilkan di ujung kanan item. */
    badge?: number | null;
};

export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
    const { url, props: pageProps } = usePage();
    const { auth } = pageProps as { auth?: { user?: { roles?: string[]; permissions?: string[] } } };
    const userPermissions = auth?.user?.permissions ?? [];
    const has = (perm: string) => userPermissions.includes(perm);
    // Jumlah pesan belum dibaca (di-share global via HandleInertiaRequests).
    const unreadCount =
        (pageProps as { notifications?: { unread_count?: number } }).notifications?.unread_count ?? 0;
    const { isMobile } = useSidebar();
    const settings = useSettings();

    // Buka homepage situs di tab baru (root '/' → redirect ke locale default).
    const siteUrl = '/';

    // Grouping profesional — 5 grup ringkas, tiap item punya permission sendiri.
    // Katalog Cocoa (domain utama) dipisah dari Halaman Web (legacy company-profile).
    const groups: { label: string; items: SidebarNavItem[] }[] = [
        {
            label: 'Utama',
            items: [
                ...(has('view dashboard') ? [{ title: 'Dashboard', href: dashboard(), icon: LayoutDashboard, active: url === '/admin/dashboard' }] : []),
            ],
        },
        {
            label: 'Katalog Cocoa',
            items: [
                ...(has('view products') ? [{ title: 'Produk Cocoa', href: '/admin/products' as any, icon: Package, active: url.startsWith('/admin/products') }] : []),
                ...(has('view product categories') ? [{ title: 'Kategori Produk', href: '/admin/product-categories' as any, icon: Layers, active: url.startsWith('/admin/product-categories') }] : []),
                ...(has('view certifications') ? [{ title: 'Sertifikasi', href: '/admin/certifications' as any, icon: Award, active: url.startsWith('/admin/certifications') }] : []),
                ...(has('view export markets') ? [{ title: 'Pasar Ekspor', href: '/admin/export-markets' as any, icon: Ship, active: url.startsWith('/admin/export-markets') }] : []),
            ],
        },
        {
            label: 'Halaman Web',
            items: [
                ...(has('view heroes') ? [{ title: 'Hero', href: heroesIndex(), icon: PanelsTopLeft, active: url.startsWith('/admin/heroes') }] : []),
                ...(has('view about') ? [{ title: 'Tentang', href: aboutIndex(), icon: Info, active: url.startsWith('/admin/about') }] : []),
                ...(has('view services') ? [{ title: 'Layanan', href: servicesIndex(), icon: Wrench, active: url.startsWith('/admin/services') }] : []),
                ...(has('view process steps') ? [{ title: 'Proses', href: '/admin/process-steps' as any, icon: Package, active: url.startsWith('/admin/process-steps') }] : []),
                ...(has('view faqs') ? [{ title: 'FAQ', href: '/admin/faqs' as any, icon: MessageSquareQuote, active: url.startsWith('/admin/faqs') }] : []),
                ...(has('view testimonials') ? [{ title: 'Testimoni', href: testimonialsIndex(), icon: MessageSquareQuote, active: url.startsWith('/admin/testimonials') }] : []),
                ...(has('view posts') || has('view blog categories') ? [{ title: 'Blog', href: blogIndex(), icon: Newspaper, active: url.startsWith('/admin/posts') || url.startsWith('/admin/blog-categories') }] : []),
            ],
        },
        {
            label: 'Media & Pesan',
            items: [
                ...(has('view media') ? [{ title: 'Media', href: mediaIndex(), icon: ImageIcon, active: url.startsWith('/admin/media') }] : []),
                ...(has('view messages') ? [{
                    title: 'Pesan',
                    href: messagesIndex(),
                    icon: Inbox,
                    active: url.startsWith('/admin/messages'),
                    badge: unreadCount,
                }] : []),
                ...(has('view analytics') || has('view visitors') ? [{ title: 'Pengunjung', href: visitorsIndex(), icon: BarChart3, active: url.startsWith('/admin/visitors') }] : []),
            ],
        },
        {
            label: 'Sistem',
            items: [
                ...(has('view users') ? [{ title: 'Pengguna', href: usersIndex(), icon: Users, active: url.startsWith('/admin/users') }] : []),
                ...(has('view roles') ? [{ title: 'Role & Akses', href: rolesIndex(), icon: Shield, active: url.startsWith('/admin/roles') }] : []),
                ...(has('view settings') ? [{ title: 'Pengaturan', href: settingsIndex(), icon: Settings, active: url.startsWith('/admin/settings') }] : []),
            ],
        },
    ];

    const renderItems = (items: SidebarNavItem[]) =>
        items.map((item) => (
            <SidebarMenuItem key={item.title}>
                <SidebarMenuButton asChild isActive={item.active}>
                    <Link href={item.href}>
                        <item.icon />
                        <span>{item.title}</span>
                    </Link>
                </SidebarMenuButton>
                {item.badge != null && item.badge > 0 && (
                    // `!` (Tailwind v4) memastikan warna teks memakai destructive-foreground,
                    // bukan text-sidebar-foreground bawaan SidebarMenuBadge.
                    <SidebarMenuBadge className="rounded-full bg-destructive font-semibold text-destructive-foreground!">
                        {item.badge > 99 ? '99+' : item.badge}
                    </SidebarMenuBadge>
                )}
            </SidebarMenuItem>
        ));

    return (
        <Sidebar collapsible="icon" {...props}>
            <SidebarHeader>
                <SidebarMenu>
                    <SidebarMenuItem>
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <SidebarMenuButton
                                    size="lg"
                                    className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
                                >
                                    <div className="flex aspect-square size-8 items-center justify-center rounded-lg border border-sidebar-border bg-transparent text-sidebar-foreground">
                                        <SiteLogo
                                            lightSrc={settings.site_logo_color}
                                            darkSrc={settings.site_logo_white}
                                            alt=""
                                            className="h-5 w-auto max-w-6 object-contain"
                                        />
                                    </div>
                                    <div className="grid flex-1 text-left text-sm leading-tight">
                                        <span className="truncate font-semibold">{settings.site_name || import.meta.env.VITE_APP_NAME || 'Admin'}</span>
                                        {settings.site_tagline && (
                                            <span className="truncate text-xs text-muted-foreground">{settings.site_tagline}</span>
                                        )}
                                    </div>
                                    <ChevronsUpDown className="ml-auto" />
                                </SidebarMenuButton>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent
                                className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
                                align="start"
                                side={isMobile ? 'bottom' : 'right'}
                                sideOffset={4}
                            >
                                <DropdownMenuLabel className="text-xs text-muted-foreground">
                                    {settings.site_name || 'Admin Panel'}
                                </DropdownMenuLabel>
                                <DropdownMenuItem asChild>
                                    <a href={siteUrl} target="_blank" rel="noopener noreferrer">
                                        <ExternalLink />
                                        Kunjungi Situs
                                    </a>
                                </DropdownMenuItem>
                                <DropdownMenuSeparator />
                                <DropdownMenuItem asChild>
                                    <Link href="/settings/profile">
                                        <Settings />
                                        Pengaturan Akun
                                    </Link>
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    </SidebarMenuItem>
                </SidebarMenu>
            </SidebarHeader>

            <SidebarContent>
                {groups
                    .filter((group) => group.items.length > 0)
                    .map((group) => (
                        <SidebarGroup key={group.label}>
                            <SidebarGroupLabel>{group.label}</SidebarGroupLabel>
                            <SidebarMenu>{renderItems(group.items)}</SidebarMenu>
                        </SidebarGroup>
                    ))}

                {/* Lihat Website — menempel di atas footer (NavUser) */}
                <SidebarGroup className="mt-auto">
                    <SidebarMenu>
                        <SidebarMenuItem>
                            <SidebarMenuButton asChild>
                                <a href={siteUrl} target="_blank" rel="noopener noreferrer">
                                    <ExternalLink />
                                    <span>Kunjungi Situs</span>
                                </a>
                            </SidebarMenuButton>
                        </SidebarMenuItem>
                    </SidebarMenu>
                </SidebarGroup>
            </SidebarContent>

            <SidebarFooter>
                <NavUser />
            </SidebarFooter>

            <SidebarRail />
        </Sidebar>
    );
}
