import { useTranslation } from 'react-i18next';
import { extractApiError } from '@/api/client';
import type { SimulationTemplate } from '@/api/types';
import { useTemplates } from '@/hooks/useTemplates';
import { LoadingState } from './LoadingState';
import { ErrorState } from './ErrorState';
import { EmptyState } from './EmptyState';

interface TemplatePickerModalProps {
  engagementId: number;
  onClose: () => void;
  onInstantiated: (simId: number) => void;
  onSelectTemplate: (template: SimulationTemplate) => void;
  isPending?: boolean;
}

function mitreCount(t: SimulationTemplate): string {
  const count = t.techniques.length + t.tactics.length;
  return count === 0 ? '—' : String(count);
}

export function TemplatePickerModal({
  onClose,
  onSelectTemplate,
  isPending = false,
}: TemplatePickerModalProps): JSX.Element {
  const { t } = useTranslation();
  const { data, isLoading, isError, error, refetch } = useTemplates();

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="tpl-picker-title"
      className="fixed inset-0 z-50 flex items-center justify-center"
    >
      <div className="modal-backdrop absolute inset-0" onClick={onClose} aria-hidden="true" />

      <div className="relative card-product max-w-xl w-full mx-md flex flex-col gap-md max-h-[80vh] overflow-hidden">
        <div className="flex items-center justify-between">
          <h2 id="tpl-picker-title" className="text-[20px] font-medium text-ink">
            {t('template.picker.title')}
          </h2>
          <button
            type="button"
            aria-label={t('common.close')}
            onClick={onClose}
            className="text-graphite hover:text-ink text-[20px] leading-none"
          >
            ×
          </button>
        </div>

        <div className="overflow-y-auto flex-1 -mx-xl px-xl">
          {isLoading ? <LoadingState label={t('template.picker.loading')} /> : null}

          {isError ? (
            <ErrorState
              message={extractApiError(error, t('template.form.errorLoad'))}
              onRetry={() => refetch()}
            />
          ) : null}

          {!isLoading && !isError && data && data.length === 0 ? (
            <EmptyState
              title={t('template.picker.empty')}
            />
          ) : null}

          {!isLoading && !isError && data && data.length > 0 ? (
            <table className="w-full text-left" data-testid="template-picker-table">
              <thead className="bg-cloud border-b border-hairline">
                <tr className="text-[12px] uppercase tracking-[0.5px] text-graphite">
                  <th className="px-md py-sm">{t('template.list.col.name')}</th>
                  <th className="px-md py-sm">{t('simulation.list.col.mitre')}</th>
                  <th className="px-md py-sm">{t('template.list.col.createdBy')}</th>
                </tr>
              </thead>
              <tbody>
                {data.map((template) => (
                  <tr
                    key={template.id}
                    className="border-b border-hairline last:border-0 hover:bg-cloud cursor-pointer"
                    onClick={() => !isPending && onSelectTemplate(template)}
                    data-testid={`template-row-${template.id}`}
                  >
                    <td className="px-md py-sm text-ink font-medium">{template.name}</td>
                    <td className="px-md py-sm text-charcoal text-[14px]">{mitreCount(template)}</td>
                    <td className="px-md py-sm text-charcoal text-[14px]">{template.created_by.username}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : null}
        </div>

        <div className="border-t border-hairline pt-sm">
          <button type="button" className="btn-outline-ink" onClick={onClose}>
            {t('common.cancel')}
          </button>
        </div>
      </div>
    </div>
  );
}
