import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { api, endpoints } from '../../api'
import { getClassColor, FALLBACK_CLASS_NAMES } from '../../class-colors'
import type { DetectionClass } from '../../types'

const FALLBACK_CLASSES: DetectionClass[] = FALLBACK_CLASS_NAMES.map((name, i) => ({
  id: i + 1,
  name,
  shortName: name.slice(0, 3),
  color: getClassColor(i),
  maxSizeM: 10,
  photoMode: 0,
}))

interface DatasetClassListProps {
  selectedClassNum: number
  onSelect: (classNum: number) => void
  counts: Record<number, number>
}

export default function DatasetClassList({ selectedClassNum, onSelect, counts }: DatasetClassListProps) {
  const { t } = useTranslation()
  const [classes, setClasses] = useState<DetectionClass[]>([])

  useEffect(() => {
    api.get<DetectionClass[]>(endpoints.annotations.classes())
      .then(list => setClasses(list?.length ? list : FALLBACK_CLASSES))
      .catch(() => setClasses(FALLBACK_CLASSES))
  }, [])

  const regularClasses = useMemo(() => classes.filter(c => c.photoMode === 0), [classes])

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      const t = e.target as HTMLElement | null
      if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
      const num = parseInt(e.key)
      if (num >= 1 && num <= 9) {
        const cls = regularClasses[num - 1]
        if (cls) onSelect(cls.id)
      }
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [regularClasses, onSelect])

  return (
    <>
      <div className="px-3 pt-3 pb-2 flex items-center justify-between border-b border-border-hair shrink-0">
        <span className="sect-head" style={{ lineHeight: 1.2 }}>{t('annotations.classes')}</span>
        <span className="mono text-[10px] text-text-muted tabular-nums">
          {regularClasses.length.toString().padStart(2, '0')}
        </span>
      </div>
      <div
        className="px-2 py-2 flex flex-col gap-0.5 overflow-y-auto"
        style={{ maxHeight: '46vh' }}
      >
        {regularClasses.map(c => {
          const isActive = c.id === selectedClassNum
          const count = counts[c.id] ?? 0
          return (
            <div
              key={c.id}
              role="button"
              tabIndex={0}
              onClick={() => onSelect(c.id)}
              onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') onSelect(c.id) }}
              className={`flex items-center gap-2.5 h-7 px-2 rounded-[2px] cursor-pointer transition-colors ${
                isActive
                  ? 'bg-surface-2 text-text-primary'
                  : 'text-text-secondary hover:bg-surface-2 hover:text-text-primary'
              }`}
            >
              <span className="swatch shrink-0" style={{ background: c.color }} />
              <span className="text-[12px] truncate flex-1">{c.name}</span>
              <span
                className={`font-mono font-medium text-[10px] tabular-nums leading-none rounded-[2px] border bg-surface-input ${
                  isActive
                    ? 'text-accent-amber border-accent-amber'
                    : 'text-text-secondary border-border-hair'
                }`}
                style={{ padding: '2px 6px' }}
              >
                {count.toLocaleString()}
              </span>
            </div>
          )
        })}
      </div>
    </>
  )
}
