import { Link, usePage } from '@inertiajs/react';
import {
    BookOpen,
    FolderGit2,
    LayoutGrid,
    Shield,
    Layers,
    CheckSquare,
    Milestone,
    Award,
    Users,
    History,
    Settings,
    LogOut,
    Clock,
    ListTodo,
    FileCheck
} from 'lucide-react';
import AppLogo from '@/components/app-logo';
import { NavMain } from '@/components/nav-main';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    Sidebar,
    SidebarContent,
    SidebarHeader,
    SidebarMenu,
    SidebarMenuButton,
    SidebarMenuItem,
    useSidebar,
} from '@/components/ui/sidebar';
import { usePermissions } from '@/hooks/use-permissions';
import { dashboard, logout } from '@/routes';
import { edit } from '@/routes/profile';
import type { NavItem } from '@/types';
import { prefixUrl } from '@/lib/utils';

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

export function AppSidebar() {
    const { hasPermission } = usePermissions();
    const { auth } = usePage().props;
    const { state } = useSidebar();

    const platformItems = [
        ...mainNavItems,
        ...(hasPermission('projects.view')
            ? [
                  {
                      title: 'Kanban Board',
                      href: '/kanban',
                      icon: Layers,
                  },
                  {
                      title: 'Projects',
                      href: '/settings/projects',
                      icon: FolderGit2,
                  },
                  {
                      title: 'Users',
                      href: '/settings/users',
                      icon: Users,
                  },
                  {
                      title: 'Audit Logs',
                      href: '/settings/audit-logs',
                      icon: History,
                  },
              ]
            : []),
        ...(hasPermission('rbac.manage')
            ? [
                  {
                      title: 'Roles & Permissions',
                      href: '/settings/rbac',
                      icon: Shield,
                  },
              ]
            : []),
    ].map(item => ({ ...item, href: prefixUrl(item.href) }));

    const projectOpsItems = (hasPermission('projects.view')
        ? [
              {
                  title: 'Task Updates',
                  href: '/project-tasks',
                  icon: ListTodo,
              },
              {
                  title: 'Timeline Updates',
                  href: '/project-timelines',
                  icon: Clock,
              },
              {
                  title: 'Licence Updates',
                  href: '/project-licences',
                  icon: FileCheck,
              },
          ]
        : []).map(item => ({ ...item, href: prefixUrl(item.href) }));

    const masterConfigItems = (hasPermission('projects.view')
        ? [
              {
                  title: 'Project Master',
                  href: '/settings/project-masters',
                  icon: BookOpen,
              },
              {
                  title: 'Tasks Master',
                  href: '/settings/tasks-master',
                  icon: CheckSquare,
              },
              {
                  title: 'Timeline Masters',
                  href: '/settings/timeline-masters',
                  icon: Milestone,
                  parentId: null,
              },
              {
                  title: 'Licence Master',
                  href: '/settings/licence-master',
                  icon: Award,
              },
          ]
        : []).map(item => ({ ...item, href: prefixUrl(item.href) }));

    const getInitials = (name: string) => {
        return name
            .split(' ')
            .map((n) => n[0])
            .join('')
            .toUpperCase()
            .substring(0, 2);
    };

    return (
        <Sidebar collapsible="icon" variant="inset" className="border-r border-zinc-200/50 dark:border-zinc-800/50 bg-zinc-50 dark:bg-zinc-950">
            <SidebarHeader className="border-b border-zinc-200/40 dark:border-zinc-800/40 p-4">
                <SidebarMenu>
                    <SidebarMenuItem>
                        <SidebarMenuButton size="lg" asChild className="hover:bg-transparent">
                            <Link href={dashboard()} prefetch className="flex items-center gap-2">
                                <AppLogo />
                            </Link>
                        </SidebarMenuButton>
                    </SidebarMenuItem>
                </SidebarMenu>
            </SidebarHeader>

            <SidebarContent className="p-4 space-y-6">
                
                {/* Redesigned Sidenav User Profile Card at top (copied style from new_layout) */}
                {auth.user && (
                    <div className={`relative overflow-hidden rounded-2xl bg-gradient-to-br from-indigo-950 via-zinc-900 to-indigo-900 border border-white/10 text-white transition-all duration-300 p-4 shadow-xl ${
                        state === 'collapsed' ? 'p-2 flex justify-center' : ''
                    }`}>
                        <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.1),transparent_50%)]" />
                        
                        {state === 'collapsed' ? (
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Avatar className="size-8 cursor-pointer border border-white/20 hover:scale-105 transition-all">
                                        <AvatarFallback className="text-[10px] font-extrabold bg-indigo-600 text-white">
                                            {getInitials(auth.user.name)}
                                        </AvatarFallback>
                                    </Avatar>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="start" className="w-56 rounded-xl p-1.5 shadow-2xl backdrop-blur-xl border border-zinc-200/80 dark:border-zinc-800/80 bg-white/95 dark:bg-zinc-950/95">
                                    <DropdownMenuLabel className="px-2 py-1.5 text-xs text-zinc-500 font-bold">
                                        {auth.user.name}
                                    </DropdownMenuLabel>
                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem asChild>
                                        <Link href={edit()} className="flex items-center gap-2 px-2.5 py-2 text-xs font-bold rounded-lg cursor-pointer">
                                            <Settings className="size-3.5 text-zinc-500" /> Account Settings
                                        </Link>
                                    </DropdownMenuItem>
                                    <DropdownMenuItem asChild>
                                        <Link href={logout()} as="button" method="post" className="flex items-center gap-2 w-full px-2.5 py-2 text-xs font-bold text-red-500 rounded-lg cursor-pointer">
                                            <LogOut className="size-3.5" /> Log Out
                                        </Link>
                                    </DropdownMenuItem>
                                </DropdownMenuContent>
                            </DropdownMenu>
                        ) : (
                            <div className="relative flex items-center justify-between gap-3">
                                <div className="flex items-center gap-3">
                                    <Avatar className="size-10 border-2 border-white/20 shadow-md">
                                        <AvatarFallback className="text-xs font-extrabold bg-indigo-600 text-white">
                                            {getInitials(auth.user.name)}
                                        </AvatarFallback>
                                    </Avatar>
                                    <div className="min-w-0">
                                        <h5 className="text-xs font-extrabold text-white truncate max-w-[110px]">{auth.user.name}</h5>
                                        <span className="text-[10px] font-bold text-indigo-200 block truncate max-w-[110px]">
                                            {hasPermission('rbac.manage') ? 'System Admin' : 'Workspace Manager'}
                                        </span>
                                    </div>
                                </div>
                                
                                <DropdownMenu>
                                    <DropdownMenuTrigger asChild>
                                        <Button variant="ghost" size="icon" className="size-8 rounded-lg text-indigo-200 hover:text-white hover:bg-white/10 shrink-0">
                                            <Settings className="size-4" />
                                        </Button>
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent align="end" className="w-56 rounded-xl p-1.5 shadow-2xl backdrop-blur-xl border border-zinc-200/80 dark:border-zinc-800/80 bg-white/95 dark:bg-zinc-950/95">
                                        <DropdownMenuLabel className="px-2 py-1.5">
                                            <div className="flex flex-col">
                                                <span className="text-xs font-extrabold text-zinc-900 dark:text-zinc-50">{auth.user.name}</span>
                                                <span className="text-[10px] text-zinc-400 font-medium truncate">{auth.user.email}</span>
                                            </div>
                                        </DropdownMenuLabel>
                                        <DropdownMenuSeparator />
                                        <DropdownMenuItem asChild>
                                            <Link href={edit()} className="flex items-center gap-2 px-2.5 py-2 text-xs font-bold rounded-lg cursor-pointer">
                                                <Settings className="size-3.5 text-zinc-500" /> Account Settings
                                            </Link>
                                        </DropdownMenuItem>
                                        <DropdownMenuSeparator />
                                        <DropdownMenuItem asChild>
                                            <Link href={logout()} as="button" method="post" className="flex items-center gap-2 w-full px-2.5 py-2 text-xs font-bold text-red-500 rounded-lg cursor-pointer">
                                                <LogOut className="size-3.5" /> Log Out
                                            </Link>
                                        </DropdownMenuItem>
                                    </DropdownMenuContent>
                                </DropdownMenu>
                            </div>
                        )}
                    </div>
                )}

                {/* Sidenav Items */}
                <div className="space-y-1">
                    <NavMain items={platformItems} label="Platform" />
                    {projectOpsItems.length > 0 && (
                        <NavMain items={projectOpsItems} label="Project Updates" />
                    )}
                    {masterConfigItems.length > 0 && (
                        <NavMain items={masterConfigItems} label="Control Masters" />
                    )}
                </div>
            </SidebarContent>
        </Sidebar>
    );
}
