import { Link, usePage } from '@inertiajs/react';
import { LayoutGrid, Plus, Ticket, ClipboardList, Users, Wrench } from 'lucide-react';
import { NavFooter } from '@/components/nav-footer';
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 type { NavItem, User } from '@/types';
import AppLogo from './app-logo';

export function AppSidebar() {
    const { auth } = usePage<{ auth: { user: User } }>().props;
    const user = auth.user;
    const isStaff = user.role === 'admin' || user.role === 'technician';
    const isAdmin = user.role === 'admin';

    const mainNavItems: NavItem[] = [
        {
            title: 'Dashboard',
            href: '/dashboard',
            icon: LayoutGrid,
        },
    ];

    // Only non-admin users see 'New Ticket' and 'My Tickets'
    if (!isAdmin) {
        mainNavItems.push(
            {
                title: 'New Ticket',
                href: '/tickets/create',
                icon: Plus,
            },
            {
                title: 'My Tickets',
                href: '/tickets?filter=mine',
                icon: Ticket,
            }
        );
    }

    // Staff can view all tickets
    if (isStaff) {
        mainNavItems.push({
            title: 'All Tickets',
            href: '/tickets',
            icon: ClipboardList,
        });
    }

    // Admin can manage users
    if (isAdmin) {
        mainNavItems.push({
            title: 'User Management',
            href: '/admin/users',
            icon: Users,
        });
    }

    const footerNavItems: NavItem[] = [];

    // Only non-admin users see 'ICT Support' footer link
    if (!isAdmin) {
        footerNavItems.push({
            title: 'ICT Support',
            href: '/tickets/create',
            icon: Wrench,
        });
    }

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

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

            <SidebarFooter>
                <NavFooter items={footerNavItems} className="mt-auto" />
                <NavUser />
            </SidebarFooter>
        </Sidebar>
    );
}
