import { Link } from 'react-router-dom';
import { Plus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { extractApiError } from '@/api/client';
import type { SimulationTemplate } from '@/api/types';
import { useDeleteTemplate, useTemplates } from '@/hooks/useTemplates';
import { useToast } from '@/hooks/useToast';
import { LoadingState } from '@/components/LoadingState';
import { ErrorState } from '@/components/ErrorState';
import { EmptyState } from '@/components/EmptyState';
import { formatDate } from '@/lib/format';

function mitreCount(t: SimulationTemplate): number {
  return t.techniques.length + t.tactics.length;
}

export function TemplatesListPage(): JSX.Element {
  const { t } = useTranslation();
  const { data, isLoading, isError, error, refetch } = useTemplates();
  const deleteMutation = useDeleteTemplate();
  const { push } = useToast();

  const onDelete = async (template: SimulationTemplate) => {
    if (!window.confirm(`${t('template.list.title')} « ${template.name} » ?`)) return;
    try {
      await deleteMutation.mutateAsync(template.id);
      push(t('template.form.toast.deleted'), 'success');
    } catch (err) {
      push(extractApiError(err, t('template.form.errorDelete')), 'error');
    }
  };

  return (
    <div className="flex flex-col gap-xl">
      <header className="flex items-end justify-between gap-md">
        <div>
          <h1 className="text-[32px] font-medium leading-none">{t('template.list.title')}</h1>
          <p className="text-charcoal text-[16px] mt-sm">
            {t('template.list.subtitle')}
          </p>
        </div>
        <Link to="/admin/templates/new" className="btn-primary">
          <Plus size={14} aria-hidden /> {t('template.list.new')}
        </Link>
      </header>

      {isLoading ? <LoadingState label={t('common.loading')} /> : null}

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

      {!isLoading && !isError && data && data.length === 0 ? (
        <EmptyState
          title={t('template.list.empty.title')}
          description={t('template.list.empty.desc')}
          action={
            <Link to="/admin/templates/new" className="btn-primary">
              <Plus size={14} aria-hidden /> {t('template.list.new')}
            </Link>
          }
        />
      ) : null}

      {!isLoading && !isError && data && data.length > 0 ? (
        <div className="card-product overflow-hidden p-0">
          <table className="table-compact w-full text-left">
            <thead className="bg-cloud border-b border-hairline">
              <tr>
                <th>{t('template.list.col.name')}</th>
                <th>{t('template.list.col.mitre')}</th>
                <th>{t('template.list.col.createdBy')}</th>
                <th>{t('template.list.col.updated')}</th>
                <th className="text-right">{t('engagement.list.col.actions')}</th>
              </tr>
            </thead>
            <tbody>
              {data.map((template) => (
                <tr key={template.id}>
                  <td>
                    <Link
                      to={`/admin/templates/${template.id}/edit`}
                      className="text-ink font-medium hover:underline"
                    >
                      {template.name}
                    </Link>
                  </td>
                  <td className="text-charcoal">
                    {mitreCount(template) === 0 ? '—' : mitreCount(template)}
                  </td>
                  <td className="text-charcoal">{template.created_by.username}</td>
                  <td className="text-charcoal font-mono">{formatDate(template.updated_at)}</td>
                  <td className="text-right">
                    <div className="inline-flex gap-sm">
                      <Link to={`/admin/templates/${template.id}/edit`} className="btn-text-link">
                        {t('template.list.edit')}
                      </Link>
                      <button
                        type="button"
                        className="btn-text-link text-bloom-deep"
                        onClick={() => onDelete(template)}
                        disabled={deleteMutation.isPending}
                      >
                        {t('template.list.delete')}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : null}
    </div>
  );
}
