import { useBasedTranslation } from '@based/i18n'
import { useTypedRoute } from 'src/app/router'
import { useMeta } from '../../metaExtractor/metaContext'
import type { TranslationsType } from '../i18n'
import { Sidebar } from './sidebar'

export const MetaSidebar = () => {
  const meta = useMeta()
  const t = useBasedTranslation<TranslationsType>()
  const { params } = useTypedRoute()
  const { section: sectionRouter } = params

  const transformMetaToGroups = (
    metaResult: Based.UI.Extractor.MetaResult,
    prioritizedGroups: string[],
  ): Based.UI.Playground.Sidebar.Props['groups'] => {
    const groupsMap: Record<string, Based.UI.Playground.Sidebar.Group> =
      Object.values(metaResult).reduce(
        (acc, { meta }) => {
          const { group = '', section, name, icon = '', id } = meta

          if (!group) return acc
          if (section !== sectionRouter) return acc

          if (!acc[group]) {
            acc[group] = { name: group, components: [] }
          }

          acc[group].components.push({ name, icon, id })

          return acc
        },
        {} as Record<string, Based.UI.Playground.Sidebar.Group>,
      )

    const matchesPriority = (name: string, keywords: string[]) => {
      return keywords.some((keyword) =>
        name.toLowerCase().includes(keyword.toLowerCase()),
      )
    }

    const sortedGroups = Object.values(groupsMap).sort((a, b) => {
      const aPriority = matchesPriority(a.name, prioritizedGroups)
      const bPriority = matchesPriority(b.name, prioritizedGroups)

      if (aPriority && bPriority) {
        return a.name.localeCompare(b.name)
      }
      if (aPriority) return -1
      if (bPriority) return 1
      return a.name.localeCompare(b.name)
    })

    sortedGroups.forEach((group) => {
      group.components.sort((a, b) => a.name.localeCompare(b.name))
    })

    return sortedGroups
  }

  const prioritizedGroups = t('sidebar.prioritizedGroups')

  return <Sidebar groups={transformMetaToGroups(meta, prioritizedGroups)} />
}
