import { Link, usePage } from '@inertiajs/react';
import {
    BadgeCheck,
    Banknote,
    CalendarDays,
    ClipboardCheck,
    FlagTriangleRight,
    LayoutGrid,
    ReceiptText,
    Trophy,
    UsersRound,
    UserRoundCog,
    Newspaper,
    Ticket,
    Database,
    Fingerprint,
} from 'lucide-react';
import AppLogo from '@/components/app-logo';
import { NavMain } from '@/components/nav-main';
import { NavUser } from '@/components/nav-user';
import {
    Sidebar,
    SidebarContent,
    SidebarFooter,
    SidebarHeader,
    SidebarMenu,
    SidebarMenuButton,
    SidebarMenuItem,
} from '@/components/ui/sidebar';
import { index as paymentMethodsIndex } from '@/actions/App/Http/Controllers/Admin/PaymentMethodsController';
import type { NavItem } from '@/types';
import type { Auth } from '@/types/auth';

const adminNavItems: NavItem[] = [
    { title: 'Overview', href: '/super-admin', icon: LayoutGrid },
    { title: 'Users & access', href: '/admin/users', icon: UserRoundCog },
    { title: 'Racers & drivers', href: '/admin/profiles', icon: UsersRound },
    {
        title: 'Profile applications',
        href: '/admin/profile-applications',
        icon: ClipboardCheck,
    },
    { title: 'Race events', href: '/admin/events', icon: CalendarDays },
    { title: 'Entries & results', href: '/admin/entries', icon: Trophy },
    { title: 'Teams', href: '/admin/teams', icon: FlagTriangleRight },
    { title: 'Organizers', href: '/admin/organizers', icon: UserRoundCog },
    { title: 'Content', href: '/admin/content', icon: Newspaper },
    { title: 'Ticket orders', href: '/admin/orders', icon: ReceiptText },
    { title: 'Tickets & pricing', href: '/admin/tickets', icon: Ticket },
    { title: 'Verification', href: '/admin/verification', icon: BadgeCheck },
    {
        title: 'Payment methods',
        href: paymentMethodsIndex.url(),
        icon: Banknote,
    },
    { title: 'System backups', href: '/super-admin/backups', icon: Database },
    {
        title: 'Ticket signing',
        href: '/super-admin/ticket-signing',
        icon: Fingerprint,
    },
];

const organizerNavItems: NavItem[] = [
    { title: 'Organizer overview', href: '/organizer', icon: LayoutGrid },
    {
        title: 'Ticket orders & refunds',
        href: '/organizer/orders',
        icon: ReceiptText,
    },
    {
        title: 'Events & operations',
        href: '/organizer/events',
        icon: CalendarDays,
    },
    {
        title: 'Verification queue',
        href: '/organizer/verification',
        icon: BadgeCheck,
    },
];

const racerNavItems: NavItem[] = [
    { title: 'Racer workspace', href: '/racer', icon: UsersRound },
    { title: 'My orders & passes', href: '/orders', icon: ReceiptText },
];

const staffPermissionNavItems: Record<string, NavItem[]> = {
    inquiries: [
        {
            title: 'User inquiries',
            href: '/staff/inquiries',
            icon: ClipboardCheck,
        },
    ],
    verification: [
        {
            title: 'Racer verification',
            href: '/moderation/documents',
            icon: BadgeCheck,
        },
    ],
    content: [
        { title: 'Site content', href: '/admin/content', icon: Newspaper },
    ],
    events: [
        { title: 'Race events', href: '/admin/events', icon: CalendarDays },
        { title: 'Entries & results', href: '/admin/entries', icon: Trophy },
        { title: 'Teams', href: '/admin/teams', icon: FlagTriangleRight },
        { title: 'Organizers', href: '/admin/organizers', icon: UserRoundCog },
    ],
    tickets: [
        { title: 'Tickets & pricing', href: '/admin/tickets', icon: Ticket },
    ],
    orders: [
        { title: 'Ticket orders', href: '/admin/orders', icon: ReceiptText },
        {
            title: 'Transfer reviews',
            href: '/admin/payment-methods',
            icon: Banknote,
        },
    ],
};

export function AppSidebar() {
    const { auth } = usePage<{ auth: Auth }>().props;
    const user = auth.user;
    const role = user?.role;
    const permissions = user?.staff_permissions ?? [];
    const isSuperAdmin = role === 'admin';
    const isStaff = role === 'moderator';
    const canOrganize = user?.has_organizer_workspace === true;
    const organizerCounts = user?.organizer_counts;
    const organizerWorkNavItems = organizerNavItems.map((item) =>
        item.href === '/organizer/orders'
            ? {
                  ...item,
                  badge:
                      (organizerCounts?.payment_reviews ?? 0) +
                      (organizerCounts?.refunds ?? 0),
              }
            : item,
    );
    const mainNavItems = isSuperAdmin
        ? adminNavItems
        : isStaff
          ? [
                { title: 'Staff overview', href: '/staff', icon: LayoutGrid },
                ...permissions.flatMap(
                    (permission) => staffPermissionNavItems[permission] ?? [],
                ),
            ].filter(
                (item, index, items) =>
                    items.findIndex(
                        (candidate) => candidate.href === item.href,
                    ) === index,
            )
          : [...racerNavItems, ...(canOrganize ? organizerWorkNavItems : [])];
    const workspaceLabel = isSuperAdmin
        ? 'Super Admin workspace'
        : isStaff
          ? 'Staff workspace'
          : canOrganize
            ? 'Racer & organizer workspaces'
            : 'Racer workspace';
    const homeHref = isSuperAdmin
        ? '/super-admin'
        : isStaff
          ? '/staff'
          : canOrganize
            ? '/organizer'
            : '/racer';

    return (
        <Sidebar collapsible="icon" variant="inset">
            <SidebarHeader>
                <SidebarMenu>
                    <SidebarMenuItem>
                        <SidebarMenuButton size="lg" asChild>
                            <Link href={homeHref} prefetch>
                                <AppLogo />
                            </Link>
                        </SidebarMenuButton>
                    </SidebarMenuItem>
                </SidebarMenu>
            </SidebarHeader>

            <SidebarContent>
                <NavMain items={mainNavItems} label={workspaceLabel} />
            </SidebarContent>

            <SidebarFooter>
                <NavUser />
            </SidebarFooter>
        </Sidebar>
    );
}
