import { useEffect, useState } from 'react'
import type { BackendTag } from '../../functions/BackendTypes'
import { BackendFetch } from '../../functions/Backend'
import { routeTo } from '../../functions/Route'
import VectorIconStar from '../../vectors/star.svg'
import VectorIconFeed from '../../vectors/feed.svg'

import SidebarCategory from '../layout/SidebarCategory'
import SidebarItemLogo from '../layout/SidebarItemLogo'
import SidebarItemText from '../layout/SidebarItemText'
import SidebarItemIcon from '../layout/SidebarItemIcon'
import SidebarItemTag from '../layout/SidebarItemTag'
import InputTags from '../inputs/Tags'

export default function PaneSidebar() {
    const [childrenTags, setChildrenTags] = useState([<a className="item-tag dummy">... LOADING ...</a>])

    useEffect(() => {
        BackendFetch<BackendTag[]>('/tags/popular?limit=5').then((resp) => {
            if (!resp.success) {
                console.error('Tags Unavailable:', resp)
                setChildrenTags([
                    <a className="item-tag dummy">... ERROR ...</a>,
                    <a className="item-tag dummy">VIEW CONSOLE FOR DETAILS</a>,
                ])
                return
            }
            setChildrenTags(
                resp.json.map((i) => <SidebarItemTag key={i.id} id={i.id} usage={i.usage} label={i.label} />),
            )
        })
    }, [])

    function onTagChange(tags: BackendTag[]) {
        const query = tags.map((t) => `tag=${t.id}`).join('&')
        routeTo(`/search?${query}`)
    }

    return (
        <nav className="layout-sidebar layout-scrolling">
            <SidebarCategory label="Main">
                <SidebarItemLogo />
                <InputTags label="" allowCustom={false} onChange={onTagChange} />
            </SidebarCategory>

            <SidebarCategory label="Sections">
                <SidebarItemIcon
                    icon={VectorIconFeed}
                    label="Upload"
                    description="Submit new animation"
                    location="/upload"
                />
                <SidebarItemIcon
                    icon={VectorIconStar}
                    label="Personal"
                    description="From this device"
                    location="/personal"
                />
            </SidebarCategory>

            <SidebarCategory label="Popular" header={true}>
                {childrenTags}
            </SidebarCategory>

            <SidebarCategory label="Links" header={true}>
                <SidebarItemText label="Terms of Service" location="/text/terms-of-service" />
                <SidebarItemText label="Privacy Policy" location="/text/privacy-policy" />
                <SidebarItemText label="API Guide" location="/text/api-guide" />
                <SidebarItemText label="Settings" location="/settings" />
            </SidebarCategory>
        </nav>
    )
}
