import { Link } from 'react-router-dom';
import { extractApiError } from '@/api/client';
import type { Engagement } from '@/api/types';
import { useDeleteEngagement, useEngagementsList } from '@/hooks/useEngagements';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/hooks/useToast';
import { LoadingState } from '@/components/LoadingState';
import { ErrorState } from '@/components/ErrorState';
import { EmptyState } from '@/components/EmptyState';
import { StatusBadge } from '@/components/StatusBadge';

function formatDate(value: string | null): string {
  if (!value) return '—';
  return value;
}

export function EngagementsListPage(): JSX.Element {
  const { data, isLoading, isError, error, refetch } = useEngagementsList();
  const { canEditEngagements } = useAuth();
  const { push } = useToast();
  const deleteMutation = useDeleteEngagement();

  const onDelete = async (eng: Engagement) => {
    if (!window.confirm(`Delete engagement "${eng.name}"? This cannot be undone.`)) return;
    try {
      await deleteMutation.mutateAsync(eng.id);
      push('Engagement supprimé', 'success');
    } catch (err) {
      push(extractApiError(err, 'Suppression impossible'), 'error');
    }
  };

  return (
    <div className="flex flex-col gap-xl">
      <header className="flex items-end justify-between gap-md">
        <div>
          <h1 className="text-[44px] font-medium leading-none">Engagements</h1>
          <p className="text-charcoal text-[16px] mt-sm">
            Red team missions and their lifecycle status.
          </p>
        </div>
        {canEditEngagements ? (
          <Link to="/engagements/new" className="btn-primary">
            New engagement
          </Link>
        ) : null}
      </header>

      {isLoading ? <LoadingState label="Loading engagements…" /> : null}

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

      {!isLoading && !isError && data && data.length === 0 ? (
        <EmptyState
          title="No engagements yet"
          description="Create your first engagement to start tracking red team missions."
          action={
            canEditEngagements ? (
              <Link to="/engagements/new" className="btn-primary">
                Create engagement
              </Link>
            ) : undefined
          }
        />
      ) : 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">Status</th>
                <th className="px-xl py-md">Start</th>
                <th className="px-xl py-md">End</th>
                <th className="px-xl py-md">Created by</th>
                <th className="px-xl py-md text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {data.map((eng) => (
                <tr key={eng.id} className="border-b border-hairline last:border-0">
                  <td className="px-xl py-md">
                    <Link to={`/engagements/${eng.id}`} className="text-ink font-medium hover:underline">
                      {eng.name}
                    </Link>
                  </td>
                  <td className="px-xl py-md">
                    <StatusBadge status={eng.status} />
                  </td>
                  <td className="px-xl py-md text-charcoal">{formatDate(eng.start_date)}</td>
                  <td className="px-xl py-md text-charcoal">{formatDate(eng.end_date)}</td>
                  <td className="px-xl py-md text-charcoal">{eng.created_by.username}</td>
                  <td className="px-xl py-md text-right">
                    <div className="inline-flex gap-sm">
                      <Link to={`/engagements/${eng.id}`} className="btn-text-link">
                        View
                      </Link>
                      {canEditEngagements ? (
                        <>
                          <Link to={`/engagements/${eng.id}/edit`} className="btn-text-link">
                            Edit
                          </Link>
                          <button
                            type="button"
                            className="btn-text-link text-bloom-deep"
                            onClick={() => onDelete(eng)}
                            disabled={deleteMutation.isPending}
                          >
                            Delete
                          </button>
                        </>
                      ) : null}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : null}
    </div>
  );
}
