'use client'

import { useMemo, useState } from 'react'
import { ICON_CATEGORIES } from '@/lib/icon-catalog'
import { ICON_PREFIX, iconEntry, searchIcons } from '@/lib/icons'
import ProductIcon from '@/components/ProductIcon'

/** Selector de íconos del set UghPass, con búsqueda y categorías. */
export default function IconPicker({ value, suggested, onChange }: {
  value: string; suggested: string | null; onChange: (v: string) => void
}) {
  const [q, setQ] = useState('')
  const [cat, setCat] = useState<string | null>(null)
  const list = useMemo(() => searchIcons(q).filter(i => !cat || i.cat === cat), [q, cat])
  const current = value || suggested
  const entry = iconEntry(current)

  return (
    <div>
      <div className="mb-2 flex items-center gap-3">
        <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-control bg-ink-900 text-2xl">
          <ProductIcon icon={current} size="80%" />
        </span>
        <div className="min-w-0 text-sm">
          <p className="font-medium">{entry?.name ?? (current ? 'Ícono propio' : 'Sin ícono')}</p>
          <p className="text-xs text-gray-400">{!value && suggested ? 'Elegido automáticamente por el nombre' : value ? 'Elegido a mano' : 'Escribí el nombre y lo elegimos solos'}</p>
        </div>
        {value && <button type="button" onClick={() => onChange('')} className="ml-auto text-xs text-gray-500 hover:text-gray-900">Automático</button>}
      </div>
      <input value={q} onChange={e => setQ(e.target.value)} placeholder="Buscar: fernet, jarra, choripán, termo…" className="input py-2.5" aria-label="Buscar ícono" />
      <div className="mt-2 flex gap-1.5 overflow-x-auto pb-1 [scrollbar-width:none]">
        {[null, ...ICON_CATEGORIES].map(c => (
          <button key={c ?? 'todas'} type="button" onClick={() => setCat(c)}
            className={`whitespace-nowrap rounded-full px-3 py-1 text-xs ${cat === c ? 'bg-ink-950 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>{c ?? 'Todas'}</button>
        ))}
      </div>
      <div className="mt-2 grid max-h-56 grid-cols-6 gap-1.5 overflow-y-auto rounded-control bg-ink-950 p-2 sm:grid-cols-7">
        {list.map(i => {
          const v = ICON_PREFIX + i.key
          const on = current === v
          return (
            <button key={i.key} type="button" title={i.name} aria-label={i.name} onClick={() => onChange(v)}
              className={`flex aspect-square items-center justify-center rounded-lg transition active:scale-90 ${on ? 'bg-brand-500/25 ring-2 ring-brand-500' : 'hover:bg-ink-800'}`}>
              <ProductIcon icon={v} size="82%" />
            </button>
          )
        })}
        {list.length === 0 && <p className="col-span-full py-6 text-center text-xs text-gray-400">No encontramos ese ícono. Probá con otra palabra.</p>}
      </div>
    </div>
  )
}
