// @design-system: domain/admin/LanguageRegistryTable
/**
 * LanguageRegistryTable — admin table for the languages registry.
 *
 * Renders a list of configured languages with code, native name, English name,
 * direction, search config (postgres regconfig), active toggle, default badge,
 * and edit / deactivate action buttons.
 *
 * States: loading skeleton · empty · populated table.
 *
 * Props:
 *   languages      — array of Language rows
 *   loading        — show skeleton rows
 *   onEdit         — called with the Language to edit
 *   onToggleActive — called with (code, nextValue) when active switch changes
 *   onAdd          — called when "Add language" is pressed
 *
 * a11y: table with role=table, Switch has aria-label, action buttons labelled.
 * RTL: all spacing via logical props (ps-/pe-/ms-/me-).
 * i18n: all strings via useT('admin_languages').
 */

import { useT } from '@/lib/i18n/react';
import { Button } from '@/components/ui/primitives/Button';
import { Switch } from '@/components/ui/primitives/Switch';
import { Skeleton } from '@/components/ui/feedback/Skeleton';
import { type KNOWN_REGCONFIGS } from '@/server/schemas/languages';
import { cn } from '@/lib/cn';
import { Table } from '@/components/ui/primitives/Table';

// ─── Types ────────────────────────────────────────────────────────────────────

export interface Language {
  code: string;
  nameNative: string;
  nameEnglish: string;
  direction: 'rtl' | 'ltr';
  /** Must be one of KNOWN_REGCONFIGS from Task 14 */
  searchConfig: (typeof KNOWN_REGCONFIGS)[number];
  isActive: boolean;
  isDefault: boolean;
  sortOrder: number;
}

export interface LanguageRegistryTableProps {
  languages: Language[];
  loading?: boolean;
  onEdit: (lang: Language) => void;
  onToggleActive: (code: string, next: boolean) => void;
  onAdd: () => void;
  className?: string;
}

// ─── Skeleton rows ────────────────────────────────────────────────────────────

const SKELETON_CELL_KEYS = [
  'code',
  'name-native',
  'name-english',
  'direction',
  'search',
  'active',
  'default',
  'actions',
] as const;

function SkeletonRow() {
  return (
    <Table.Row>
      {SKELETON_CELL_KEYS.map((cellKey) => (
        <Table.Cell key={cellKey}>
          <Skeleton className="h-4 w-full rounded" />
        </Table.Cell>
      ))}
    </Table.Row>
  );
}

// ─── Component ────────────────────────────────────────────────────────────────

export function LanguageRegistryTable({
  languages,
  loading = false,
  onEdit,
  onToggleActive,
  onAdd,
  className,
}: LanguageRegistryTableProps) {
  const t = useT('admin_languages');

  return (
    <section
      className={cn('flex flex-col gap-4', className)}
      aria-labelledby="lang-registry-heading"
    >
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex min-w-0 flex-col gap-1">
          <h1 id="lang-registry-heading" className="text-lg font-semibold text-neutral-900">
            {t('title')}
          </h1>
          <a
            href="/admin/translations"
            className="text-text-secondary hover:text-text-primary text-sm hover:underline"
          >
            {t('cross_link_translations')}
          </a>
        </div>
        <Button variant="primary" size="sm" onClick={onAdd}>
          {t('add')}
        </Button>
      </div>

      {/* Table */}
      <Table className="border-border-default bg-surface-base rounded-lg border">
        <Table.Head>
          <Table.Row className="border-border-default border-b bg-neutral-50">
            <Table.HeadCell className="text-text-muted py-3 ps-4 pe-3 font-medium">
              {t('col_code')}
            </Table.HeadCell>
            <Table.HeadCell className="text-text-muted font-medium">
              {t('col_name_native')}
            </Table.HeadCell>
            <Table.HeadCell className="text-text-muted font-medium">
              {t('col_name_english')}
            </Table.HeadCell>
            <Table.HeadCell className="text-text-muted font-medium">
              {t('col_direction')}
            </Table.HeadCell>
            <Table.HeadCell className="text-text-muted font-medium">
              {t('col_search_config')}
            </Table.HeadCell>
            <Table.HeadCell className="text-text-muted text-center font-medium">
              {t('col_active')}
            </Table.HeadCell>
            <Table.HeadCell className="text-text-muted font-medium">
              {t('col_default')}
            </Table.HeadCell>
            <Table.HeadCell className="text-text-muted py-3 ps-3 pe-4 text-end font-medium">
              {t('col_actions')}
            </Table.HeadCell>
          </Table.Row>
        </Table.Head>
        <Table.Body>
          {loading ? (
            Array.from({ length: 3 }).map((_, i) => <SkeletonRow key={i} />)
          ) : languages.length === 0 ? (
            <Table.Row>
              <Table.Cell colSpan={8} className="text-text-muted py-10 text-center">
                {t('empty')}
              </Table.Cell>
            </Table.Row>
          ) : (
            languages.map((lang) => (
              <Table.Row
                key={lang.code}
                className="border-b border-neutral-100 transition-colors last:border-0 hover:bg-neutral-50"
              >
                {/* Code */}
                <Table.Cell
                  className="py-3 ps-4 pe-3 font-mono font-medium text-neutral-800"
                  data-user-displayname
                >
                  {lang.code}
                </Table.Cell>

                {/* Native name */}
                <Table.Cell className="text-neutral-800" dir={lang.direction} data-user-displayname>
                  {lang.nameNative}
                </Table.Cell>

                {/* English name */}
                <Table.Cell className="text-neutral-800" data-user-displayname>
                  {lang.nameEnglish}
                </Table.Cell>

                {/* Direction */}
                <Table.Cell className="text-text-muted">
                  {lang.direction === 'rtl' ? t('dir_rtl') : t('dir_ltr')}
                </Table.Cell>

                {/* Search config */}
                <Table.Cell className="text-text-muted font-mono" data-user-displayname>
                  {lang.searchConfig}
                </Table.Cell>

                {/* Active toggle */}
                <Table.Cell>
                  <div className="flex justify-center">
                    <Switch
                      id={`lang-active-${lang.code}`}
                      checked={lang.isActive}
                      onCheckedChange={(next) => onToggleActive(lang.code, next)}
                      aria-label={t('aria_toggle_active').replace('{{name}}', lang.nameEnglish)}
                      disabled={lang.isDefault}
                    />
                  </div>
                </Table.Cell>

                {/* Default badge */}
                <Table.Cell>
                  {lang.isDefault && (
                    <span className="bg-brand-primary-100 text-brand-primary-700 inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium">
                      {t('badge_default')}
                    </span>
                  )}
                </Table.Cell>

                {/* Actions */}
                <Table.Cell className="py-3 ps-3 pe-4">
                  <div className="flex justify-end gap-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onEdit(lang)}
                      aria-label={`${t('edit')} ${lang.nameEnglish}`}
                    >
                      {t('edit')}
                    </Button>
                  </div>
                </Table.Cell>
              </Table.Row>
            ))
          )}
        </Table.Body>
      </Table>
    </section>
  );
}
