import {useMemo} from 'react';
import {useLocation, useNavigate} from 'react-router-dom';
import {cn} from '@/lib/utils';
import {useProject} from '@/contexts';
import {Avatar, AvatarFallback, AvatarImage} from '@/components/ui/avatar';
import {Tooltip, TooltipContent, TooltipProvider, TooltipTrigger} from '@/components/ui/tooltip';
import {SidebarSystem} from '@/components/layout/sidebar-system';
import {SidebarUser} from '@/components/layout/sidebar-user';
import {useSidebarCollapse} from '@/hooks/use-sidebar-collapse';
import {
    ChevronLeft,
    ChevronRight,
    CircleDot,
    GitBranch,
    LayoutGrid,
    MessageCircle,
    Package2,
    Settings,
    Users,
    Wrench,
} from 'lucide-react';

type SidebarItem = {
    title: string;
    icon: React.ReactNode;
    url: string;
    adminOnly?: boolean;
    exact?: boolean;
};

export function ProjectSidebar() {
    const {project} = useProject();
    const navigate = useNavigate();
    const location = useLocation();
    const {collapsed, setCollapsed} = useSidebarCollapse();

    const projectName = project?.name ?? '';
    const isAdmin = project?.role === 'Owner' || project?.role === 'Admin';

    const items: SidebarItem[] = useMemo(
        () => [
            {
                title: 'Overview',
                icon: <GitBranch className="h-4 w-4"/>,
                url: `/project/${projectName}`,
                exact: true,
            },
            {
                title: 'Rooms',
                icon: <MessageCircle className="h-4 w-4"/>,
                url: `/project/${projectName}/room`,
            },
            {
                title: 'Repositories',
                icon: <Package2 className="h-4 w-4"/>,
                url: `/project/${projectName}/repositories`,
            },
            {
                title: 'Issues',
                icon: <CircleDot className="h-4 w-4"/>,
                url: `/project/${projectName}/issues`,
            },
            {
                title: 'Boards',
                icon: <LayoutGrid className="h-4 w-4"/>,
                url: `/project/${projectName}/boards`,
            },
            // { title: 'Articles', icon: <FileText className="h-4 w-4"/>, url: `/project/${projectName}/articles` },
            // { title: 'Resources', icon: <Wrench className="h-4 w-4"/>, url: `/project/${projectName}/resources` },
            {
                title: 'Members',
                icon: <Users className="h-4 w-4"/>,
                url: `/project/${projectName}/members`,
            },
            {
                title: 'Skills',
                icon: <Wrench className="h-4 w-4"/>,
                url: `/project/${projectName}/skills`,
            },
            {
                title: 'Settings',
                icon: <Settings className="h-4 w-4"/>,
                url: `/project/${projectName}/settings`,
                adminOnly: true,
            },
        ],
        [projectName],
    );

    if (!project) {
        return null;
    }

    return (
        <TooltipProvider>
            <aside
                className={cn(
                    'hidden md:flex h-full flex-col border-r bg-background transition-all duration-200',
                    collapsed ? 'w-16' : 'w-64',
                )}
            >
                <div
                    className={cn('border-b px-3 h-12 flex items-center', collapsed ? 'justify-center' : 'justify-between')}>
                    {!collapsed && (
                        <div className="flex min-w-0 items-center gap-3 overflow-hidden">
                            <Avatar className="h-8 w-8">
                                <AvatarImage src={project.avatar_url || ''}/>
                                <AvatarFallback>
                                    {projectName.charAt(0).toUpperCase()}
                                </AvatarFallback>
                            </Avatar>
                            <div className="min-w-0 flex-1 truncate text-sm font-semibold">
                                {project.display_name}
                            </div>
                        </div>
                    )}

                    <button
                        type="button"
                        className="flex h-9 w-9 items-center justify-center rounded-md hover:bg-muted cursor-pointer bg-transparent border-0"
                        onClick={() => setCollapsed(!collapsed)}
                    >
                        {collapsed ? (
                            <ChevronRight className="h-4 w-4"/>
                        ) : (
                            <ChevronLeft className="h-4 w-4"/>
                        )}
                    </button>
                </div>

                <nav className="flex-1 p-2">
                    <ul className="space-y-1">
                        {items
                            .filter((item) => !item.adminOnly || isAdmin)
                            .map((item) => {
                                const isActive = item.exact
                                    ? location.pathname === item.url
                                    : location.pathname === item.url ||
                                    location.pathname.startsWith(`${item.url}/`);

                                const content = (
                                    <button
                                        type="button"
                                        onClick={() => navigate(item.url)}
                                        className={cn(
                                            'flex w-full h-9 justify-start items-center rounded-md font-medium hover:bg-muted cursor-pointer bg-transparent border-0 text-left text-sm',
                                            isActive && 'bg-primary/10 text-primary',
                                            collapsed ? 'justify-center px-0' : 'justify-start px-2',
                                        )}
                                    >
                                        <span
                                            className={cn('flex h-6 items-center shrink-0', collapsed ? 'w-6 justify-center' : 'w-6')}>
                                            {item.icon}
                                        </span>
                                        {!collapsed && item.title}
                                    </button>
                                );

                                return (
                                    <li key={item.title}>
                                        {collapsed ? (
                                            <Tooltip>
                                                <TooltipTrigger
                                                    className={cn(
                                                        'flex h-9 w-full justify-center items-center rounded-md font-medium hover:bg-muted cursor-pointer bg-transparent border-0',
                                                        isActive && 'bg-primary/10 text-primary',
                                                    )}
                                                    onClick={() => navigate(item.url)}
                                                >
                                                    <span className="flex h-6 w-6 items-center justify-center shrink-0">
                                                        {item.icon}
                                                    </span>
                                                </TooltipTrigger>
                                                <TooltipContent side="right">
                                                    {item.title}
                                                </TooltipContent>
                                            </Tooltip>
                                        ) : (
                                            <Tooltip>
                                                <TooltipTrigger className="w-full">{content}</TooltipTrigger>
                                                <TooltipContent side="right">
                                                    {item.title}
                                                </TooltipContent>
                                            </Tooltip>
                                        )}
                                    </li>
                                );
                            })}
                    </ul>
                </nav>

                <div className="border-t flex flex-col justify-end">
                    <SidebarSystem collapsed={collapsed}/>
                    <SidebarUser collapsed={collapsed}/>
                </div>
            </aside>
        </TooltipProvider>
    );
}
