import { useBasedTranslation } from '@based/i18n'
import { Sidebar as AppSidebar, TextInput } from '@based/ui'
import { useState } from 'react'
import { useRouter } from 'react-router5'
import type { TranslationsType } from '../i18n'
import { useTypedRoute } from '../router'

export const Sidebar = ({ groups }: Based.UI.Playground.Sidebar.Props) => {
  const t = useBasedTranslation<TranslationsType>()
  const { params } = useTypedRoute()
  const { section, component } = params
  const [search, setSearch] = useState('')
  const router = useRouter()

  const filteredGroups = groups
    .map((group) => ({
      ...group,
      components: group.components.filter((component) =>
        component.name.toLowerCase().includes(search.toLowerCase()),
      ),
    }))
    .filter((group) => group.components.length > 0)

  const handleItem = (component: string) => {
    setSearch('')

    router.navigate('components', {
      section,
      component,
    })
  }

  return (
    <AppSidebar value={component} onChange={handleItem}>
      <AppSidebar.Header>
        <TextInput
          value={search}
          onChange={setSearch}
          leadIcon="search"
          keyHint="Cmd+K"
          placeholder={t('sidebar.searchInput.placeholder')}
        />
      </AppSidebar.Header>
      <AppSidebar.Items>
        {filteredGroups.map((group: any) => (
          <AppSidebar.Group key={group.name} title={group.name}>
            {group.components.map((component: any) => (
              <AppSidebar.Item key={component.id} value={component.id}>
                {component.name}
              </AppSidebar.Item>
            ))}
          </AppSidebar.Group>
        ))}
      </AppSidebar.Items>
    </AppSidebar>
  )
}
