import { Link, usePage } from '@inertiajs/react';
import {
    FileText,
    LayoutGrid,
    Megaphone,
    Smartphone,
    MessageSquare,
    Users,
    UserCog,
    Workflow,
} from 'lucide-react';
import AppLogo from '@/components/app-logo';
import { NavMain } from '@/components/nav-main';
import {
    Sidebar,
    SidebarContent,
    SidebarHeader,
    SidebarMenu,
    SidebarMenuButton,
    SidebarMenuItem,
} from '@/components/ui/sidebar';
import type { NavItem, User } from '@/types';

interface RoleNavItem extends NavItem {
    roles?: string[];
}

const allNavItems: RoleNavItem[] = [
    {
        title: 'Dashboard',
        href: '/dashboard',
        icon: LayoutGrid,
        roles: ['client', 'owner', 'admin'],
    },
    {
        title: 'Nomor WhatsApp',
        href: '/dashboard/whatsapp-accounts',
        icon: Smartphone,
        roles: ['client', 'owner', 'admin'],
    },
    {
        title: 'Kotak Masuk',
        href: '/dashboard/inbox',
        icon: MessageSquare,
        roles: ['client', 'owner', 'admin', 'staff'],
    },
    {
        title: 'Otomasi (Bot)',
        href: '/dashboard/automations',
        icon: Workflow,
        roles: ['client', 'owner', 'admin'],
    },
    {
        title: 'Kontak & Grup',
        href: '/dashboard/contacts',
        icon: Users,
        roles: ['client', 'owner', 'admin', 'staff'],
    },
    {
        title: 'Template Pesan',
        href: '/dashboard/templates',
        icon: FileText,
        roles: ['client', 'owner', 'admin', 'staff'],
    },
    {
        title: 'Kampanye Siaran',
        href: '/dashboard/campaigns',
        icon: Megaphone,
        roles: ['client', 'owner', 'admin', 'staff'],
    },
    {
        title: 'Manajemen Pengguna',
        href: '/dashboard/users',
        icon: UserCog,
        roles: ['client', 'owner', 'admin'],
    },
];

export function ClientSidebar() {
    const page = usePage();
    const user = (page.props.auth as any)?.user as User | undefined;
    const userRole = user?.role || 'client';
    const isOwner = userRole === 'client' || userRole === 'owner';

    const visibleNavItems: NavItem[] = allNavItems.filter((item) => {
        if (!item.roles) {
            return true;
        }
        if (isOwner) {
            return true;
        }
        return item.roles.includes(userRole);
    });

    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={visibleNavItems} />
            </SidebarContent>
        </Sidebar>
    );
}
