import { createFileRoute, Link } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { useRecords } from '@/api/queries'

export const Route = createFileRoute('/dictionaries/$name')({
  component: DictionaryDetail,
})

function DictionaryDetail() {
  const { name } = Route.useParams()
  const { t } = useTranslation()
  const { data, isLoading, error } = useRecords(name, 'PUBLIC,INTERNAL,RESTRICTED')

  return (
    <div>
      <div className="flex items-center gap-2 mb-6">
        <Link to="/dictionaries" className="text-sm text-zinc-500 hover:text-brand-700">
          ← {t('nav.dictionaries')}
        </Link>
      </div>
      <h1 className="text-2xl font-semibold mb-1">{name}</h1>
      <p className="text-sm text-zinc-500 mb-4">
        {data?.length ?? 0} {t('dict.list.records')}
      </p>

      {isLoading && <p className="text-zinc-500">{t('loading')}</p>}
      {error && <p className="text-red-600">{t('error.failed')}</p>}

      {data && data.length === 0 && (
        <p className="text-zinc-500 italic">{t('dict.empty')}</p>
      )}

      {data && data.length > 0 && (
        <div className="overflow-x-auto bg-white border border-zinc-200 rounded-lg">
          <table className="w-full text-sm">
            <thead className="bg-zinc-50 text-zinc-600">
              <tr>
                <th className="text-left px-4 py-2 font-medium">{t('dict.col.businessKey')}</th>
                <th className="text-left px-4 py-2 font-medium">name / code</th>
                <th className="text-left px-4 py-2 font-medium">{t('dict.col.scope')}</th>
                <th className="text-left px-4 py-2 font-medium">{t('dict.col.locale')}</th>
                <th className="text-left px-4 py-2 font-medium">{t('dict.col.validFrom')}</th>
              </tr>
            </thead>
            <tbody>
              {data.map((r) => (
                <tr key={r.id} className="border-t border-zinc-100 hover:bg-zinc-50">
                  <td className="px-4 py-2 font-mono text-xs">{r.businessKey}</td>
                  <td className="px-4 py-2">
                    {String((r.data as Record<string, unknown>).name ?? (r.data as Record<string, unknown>).code ?? '—')}
                  </td>
                  <td className="px-4 py-2">
                    <span className="text-xs px-2 py-0.5 rounded bg-zinc-100">{r.dataScope}</span>
                  </td>
                  <td className="px-4 py-2 text-zinc-500 text-xs">{r._meta?.locale ?? '—'}</td>
                  <td className="px-4 py-2 text-zinc-500 text-xs">
                    {new Date(r.validFrom).toLocaleDateString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
