import { Link } from 'react-router-dom';
import { Plus } from 'lucide-react';
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';

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

function formatDate(value: string | null): string {
  if (!value) return '—';
  return value.slice(0, 10);
}

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

  const onDelete = async (t: SimulationTemplate) => {
    if (!window.confirm(`Delete template "${t.name}"? This cannot be undone.`)) return;
    try {
      await deleteMutation.mutateAsync(t.id);
      push('Template deleted', 'success');
    } catch (err) {
      push(extractApiError(err, 'Could not delete template'), '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">Templates</h1>
          <p className="text-charcoal text-[16px] mt-sm">
            Reusable simulation blueprints for red team operations.
          </p>
        </div>
        <Link to="/admin/templates/new" className="btn-primary">
          <Plus size={14} aria-hidden /> New
        </Link>
      </header>

      {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 yet"
          description="Create your first template to speed up simulation setup."
          action={
            <Link to="/admin/templates/new" className="btn-primary">
              <Plus size={14} aria-hidden /> New template
            </Link>
          }
        />
      ) : null}

      {!isLoading && !isError && data && data.length > 0 ? (
        <div className="card-product overflow-hidden p-0">
          <table className="w-full text-left">
            <thead className="bg-cloud border-b border-hairline">
              <tr className="text-[12px] uppercase tracking-[0.5px] text-graphite">
                <th className="px-xl py-md">Name</th>
                <th className="px-xl py-md">MITRE</th>
                <th className="px-xl py-md">Created by</th>
                <th className="px-xl py-md">Updated</th>
                <th className="px-xl py-md text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {data.map((t) => (
                <tr key={t.id} className="border-b border-hairline last:border-0">
                  <td className="px-xl py-md">
                    <Link
                      to={`/admin/templates/${t.id}/edit`}
                      className="text-ink font-medium hover:underline"
                    >
                      {t.name}
                    </Link>
                  </td>
                  <td className="px-xl py-md text-charcoal text-[14px]">
                    {mitreCount(t) === 0 ? '—' : mitreCount(t)}
                  </td>
                  <td className="px-xl py-md text-charcoal">{t.created_by.username}</td>
                  <td className="px-xl py-md text-charcoal font-mono">{formatDate(t.updated_at)}</td>
                  <td className="px-xl py-md text-right">
                    <div className="inline-flex gap-sm">
                      <Link to={`/admin/templates/${t.id}/edit`} className="btn-text-link">
                        Edit
                      </Link>
                      <button
                        type="button"
                        className="btn-text-link text-bloom-deep"
                        onClick={() => onDelete(t)}
                        disabled={deleteMutation.isPending}
                      >
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : null}
    </div>
  );
}
