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 { 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 shadow-floating dark:shadow-floating-dark 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">
            From template…
          </h2>
          <button
            type="button"
            aria-label="Close"
            onClick={onClose}
            className="text-graphite hover:text-ink transition-colors text-[20px] leading-none"
          >
            ×
          </button>
        </div>

        <div className="overflow-y-auto flex-1 -mx-xl px-xl">
          {isLoading ? <LoadingState label="Loading templates…" /> : null}

          {isError ? (
            <ErrorState
              message={extractApiError(error, 'Could not load templates')}
              onRetry={() => refetch()}
            />
          ) : null}

          {!isLoading && !isError && data && data.length === 0 ? (
            <EmptyState
              title="No templates available"
              description="Create one from the Templates page."
            />
          ) : 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">Name</th>
                  <th className="px-md py-sm">MITRE</th>
                  <th className="px-md py-sm">Created by</th>
                </tr>
              </thead>
              <tbody>
                {data.map((t) => (
                  <tr
                    key={t.id}
                    className="border-b border-hairline last:border-0 hover:bg-cloud cursor-pointer"
                    onClick={() => !isPending && onSelectTemplate(t)}
                    data-testid={`template-row-${t.id}`}
                  >
                    <td className="px-md py-sm text-ink font-medium">{t.name}</td>
                    <td className="px-md py-sm text-charcoal text-[14px]">{mitreCount(t)}</td>
                    <td className="px-md py-sm text-charcoal text-[14px]">{t.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}>
            Cancel
          </button>
        </div>
      </div>
    </div>
  );
}
