import { useState } from 'react';
import { Link, router, usePage } from '@inertiajs/react';

import { BadgeCheck, ChevronsUpDown, Star, History, ChevronDown, LogOut, Search, Book, TableOfContents, House, HardDriveDownload } from 'lucide-react';

import { Avatar, AvatarFallback  } from '@/components/ui/avatar';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarMenu, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem } from '@/components/ui/sidebar';

export function AppSidebar({ auth }) {
    const { tags } = usePage().props;

    const [search, setSearch] = useState('');

    const searchOnSubmitHandler = (e) => {
        e.preventDefault();
        // Visit the search page
        router.get(route('comics.search', [search]), {}, {

        });
    }

    const SidebarItem = (props) => {
        const searchParams = new URL(window.location).searchParams;
        const isActive = (!searchParams.has(props.query) && props.name === 'All') || (searchParams.has(props.query) && searchParams.get(props.query) === props.path_word);

        // To current, replace
        if (searchParams.has(props.query)) {
            searchParams.set(props.query, props.path_word);
        } else {
            searchParams.set(props.query, props.path_word);
        }

        return (
            <SidebarMenuItem>
                <SidebarMenuButton asChild isActive={ isActive }>
                    <Link href={ "/?" + searchParams.toString() } onClick={ (e) => setSearch("") }>
                        <span>{ props.name }</span>
                    </Link>
                </SidebarMenuButton>
                { props.count && <SidebarMenuBadge>{ props.count }</SidebarMenuBadge> }
            </SidebarMenuItem>
        );
    };

    return (
        <Sidebar>
            <SidebarContent>
                <SidebarHeader>
                    <SidebarMenu>
                        <SidebarMenuItem>
                            <SidebarMenuButton size="lg" asChild>
                                <Link href={ route('comics.index')}>
                                    <div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
                                        <Book className="size-4" />
                                    </div>
                                    <div className="flex flex-col gap-0.5 leading-none">
                                        <span className="font-semibold">Comic</span>
                                        <span>0.1.1</span>
                                    </div>
                                </Link>
                            </SidebarMenuButton>
                        </SidebarMenuItem>
                    </SidebarMenu>
                    <SidebarGroup className="py-0">
                        <SidebarGroupContent className="relative" tabIndex="0">
                            <form autoCorrect="false" onSubmit={ (e) => searchOnSubmitHandler(e) }>
                                <label htmlFor="search" className="sr-only">Search</label>
                                <SidebarInput onChange={ (e) => setSearch(e.target.value) } id="search"
                                              placeholder="Search" className="pl-8" />
                                <Search
                                    className="pointer-events-none absolute left-2 top-1/2 size-4 -translate-y-1/2 select-none opacity-50" />
                            </form>
                        </SidebarGroupContent>
                    </SidebarGroup>
                </SidebarHeader>
                <SidebarGroup>
                    <SidebarGroupLabel>Others</SidebarGroupLabel>
                    <SidebarGroupContent>
                        <SidebarMenu>
                            <SidebarMenuItem>
                                <SidebarMenuButton asChild>
                                    <Link href={ route('comics.index')}>
                                        <House />
                                        <span>Index</span>
                                    </Link>
                                </SidebarMenuButton>
                            </SidebarMenuItem>
                            <SidebarMenuItem>
                                <SidebarMenuButton asChild>
                                    <Link href={ route('pages.show', ['Installation'])}>
                                        <HardDriveDownload />
                                        <span>Installation</span>
                                    </Link>
                                </SidebarMenuButton>
                            </SidebarMenuItem>
                            <SidebarMenuItem>
                                <SidebarMenuButton asChild>
                                    <Link href={ route('pages.show', ['Updates'])}>
                                        <TableOfContents />
                                        <span>Updates and notes</span>
                                    </Link>
                                </SidebarMenuButton>
                            </SidebarMenuItem>
                        </SidebarMenu>
                    </SidebarGroupContent>
                </SidebarGroup>
                <Collapsible defaultOpen className="group/collapsible">
                    <SidebarGroup>
                        <SidebarGroupLabel asChild>
                            <CollapsibleTrigger>
                                Tags <ChevronDown className="ml-auto transition-transform group-data-[state=open]/collapsible:rotate-180" />
                            </CollapsibleTrigger>
                        </SidebarGroupLabel>
                        <CollapsibleContent>
                            <SidebarGroupContent>
                                <SidebarMenu>
                                    <SidebarItem path_word="all" query="tag" name="All" />
                                    { tags.theme.map(item => <SidebarItem query="tag" key={ item.path_word } { ...item } />) }
                                </SidebarMenu>
                            </SidebarGroupContent>
                        </CollapsibleContent>
                    </SidebarGroup>
                </Collapsible>

                <Collapsible className="group/collapsible">
                    <SidebarGroup>
                        <SidebarGroupLabel asChild>
                            <CollapsibleTrigger>
                                Region <ChevronDown className="ml-auto transition-transform group-data-[state=open]/collapsible:rotate-180" />
                            </CollapsibleTrigger>
                        </SidebarGroupLabel>
                        <CollapsibleContent>
                            <SidebarGroupContent>
                                <SidebarMenu>
                                    <SidebarItem path_word="all" query="top" name="All" />
                                    { tags.top.map(item => <SidebarItem query="top" key={ item.path_word } { ...item } />) }
                                </SidebarMenu>
                            </SidebarGroupContent>
                        </CollapsibleContent>
                    </SidebarGroup>
                </Collapsible>
            </SidebarContent>
            <SidebarFooter>
                <SidebarMenu>
                    <SidebarMenuItem>
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <SidebarMenuButton
                                    size="lg"
                                    className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
                                >
                                    <Avatar className="h-8 w-8 rounded-lg">
                                        <AvatarFallback className="rounded-lg">
                                            { auth.user.name.slice(0, 1).toLocaleUpperCase() }
                                        </AvatarFallback>
                                    </Avatar>
                                        <div className="grid flex-1 text-left text-sm leading-tight">
                                            <span className="truncate font-semibold">
                                                { auth.user.name }
                                            </span>
                                        </div>
                                    <ChevronsUpDown className="ml-auto size-4" />
                                </SidebarMenuButton>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent
                                className="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg"
                                side="bottom"
                                align="end"
                                sideOffset={ 4 }
                            >
                                <DropdownMenuLabel className="p-0 font-normal">
                                    <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
                                        <Avatar className="h-8 w-8 rounded-lg">
                                            <AvatarFallback className="rounded-lg">
                                                { auth.user.name.slice(0, 1).toLocaleUpperCase() }
                                            </AvatarFallback>
                                        </Avatar>
                                        <div className="grid flex-1 text-left text-sm leading-tight">
                                            <span className="truncate font-semibold">
                                                { auth.user.name }
                                            </span>
                                        </div>
                                    </div>
                                </DropdownMenuLabel>
                                <DropdownMenuSeparator />
                                <DropdownMenuGroup>
                                    <DropdownMenuItem asChild><Link href={ route('profile.edit') }><BadgeCheck /> Profile</Link></DropdownMenuItem>
                                    <DropdownMenuItem asChild><Link href={ route('comics.favourites') }><Star /> Favourites</Link></DropdownMenuItem>
                                    <DropdownMenuItem asChild><Link href={ route('comics.histories') }><History /> History</Link></DropdownMenuItem>
                                </DropdownMenuGroup>
                                <DropdownMenuSeparator />
                                <DropdownMenuItem asChild><Link method="post" href={ route('logout') }><LogOut /> Log out</Link></DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    </SidebarMenuItem>
                </SidebarMenu>
            </SidebarFooter>
        </Sidebar>
    )
}
