import { useEffect, useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { ChevronDown, Plus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { extractApiError } from '@/api/client';
import type { SimulationTemplate } from '@/api/types';
import { useAuth } from '@/hooks/useAuth';
import { useEngagementSimulations, useCreateSimulation } from '@/hooks/useSimulations';
import { useToast } from '@/hooks/useToast';
import { formatDateTime } from '@/lib/format';
import { LoadingState } from './LoadingState';
import { ErrorState } from './ErrorState';
import { EmptyState } from './EmptyState';
import { SimulationStatusBadge } from './SimulationStatusBadge';
import { TemplatePickerModal } from './TemplatePickerModal';

interface SimulationListProps {
  engagementId: number;
}

function NewSimulationDropdown({ engagementId }: { engagementId: number }): JSX.Element {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { push } = useToast();
  const [open, setOpen] = useState(false);
  const [showPicker, setShowPicker] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const createMutation = useCreateSimulation(engagementId);

  useEffect(() => {
    if (!open) return;
    const onPointerDown = (e: PointerEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setOpen(false);
    };
    document.addEventListener('pointerdown', onPointerDown);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('pointerdown', onPointerDown);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [open]);

  const handleBlank = () => {
    setOpen(false);
    navigate(`/engagements/${engagementId}/simulations/new`);
  };

  const handleFromTemplate = () => {
    setOpen(false);
    setShowPicker(true);
  };

  const handleSelectTemplate = async (template: SimulationTemplate) => {
    try {
      const sim = await createMutation.mutateAsync({ name: template.name, template_id: template.id });
      setShowPicker(false);
      push(t('simulation.form.toast.created'), 'success');
      navigate(`/engagements/${engagementId}/simulations/${sim.id}/edit`);
    } catch (err) {
      push(extractApiError(err, t('simulation.form.error.create')), 'error');
    }
  };

  return (
    <div className="relative" ref={ref}>
      <div className="inline-flex">
        <button
          type="button"
          className="btn-primary border-r border-primary-deep"
          onClick={handleBlank}
          data-testid="new-simulation-btn"
        >
          <Plus size={14} aria-hidden /> {t('simulation.list.new')}
        </button>
        <button
          type="button"
          aria-label="More options"
          aria-expanded={open}
          className="btn-primary px-sm"
          onClick={() => setOpen((v) => !v)}
          data-testid="new-simulation-dropdown-toggle"
        >
          <ChevronDown size={14} aria-hidden />
        </button>
      </div>

      {open ? (
        <div
          className="absolute right-0 top-full mt-xxs bg-paper border border-hairline rounded-none z-20 min-w-[180px]"
          role="menu"
        >
          <button
            type="button"
            role="menuitem"
            className="w-full text-left px-md py-sm text-[14px] text-ink hover:bg-cloud dark:hover:bg-fog"
            onClick={handleBlank}
          >
            Blank
          </button>
          <button
            type="button"
            role="menuitem"
            className="w-full text-left px-md py-sm text-[14px] text-ink hover:bg-cloud dark:hover:bg-fog"
            onClick={handleFromTemplate}
            data-testid="from-template-btn"
          >
            From template…
          </button>
        </div>
      ) : null}

      {showPicker ? (
        <TemplatePickerModal
          engagementId={engagementId}
          onClose={() => setShowPicker(false)}
          onInstantiated={(simId) => {
            setShowPicker(false);
            navigate(`/engagements/${engagementId}/simulations/${simId}/edit`);
          }}
          onSelectTemplate={handleSelectTemplate}
          isPending={createMutation.isPending}
        />
      ) : null}
    </div>
  );
}

export function SimulationList({ engagementId }: SimulationListProps): JSX.Element {
  const { t } = useTranslation();
  const { data, isLoading, isError, error, refetch } = useEngagementSimulations(engagementId);
  const { canEditEngagements } = useAuth();
  const navigate = useNavigate();

  if (isLoading) return <LoadingState label={t('common.loading')} />;

  if (isError) {
    return (
      <ErrorState
        message={extractApiError(error, t('simulation.list.error'))}
        onRetry={() => refetch()}
      />
    );
  }

  if (!data || data.length === 0) {
    return (
      <EmptyState
        title={t('simulation.list.empty.title')}
        description={t('simulation.list.empty.desc')}
        action={
          canEditEngagements ? (
            <NewSimulationDropdown engagementId={engagementId} />
          ) : undefined
        }
      />
    );
  }

  return (
    <div className="flex flex-col gap-md">
      <div className="flex items-center justify-between">
        <h2 className="text-[24px] font-medium text-ink">{t('engagement.detail.tabs.simulations')}</h2>
        {canEditEngagements ? (
          <NewSimulationDropdown engagementId={engagementId} />
        ) : null}
      </div>

      <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('simulation.list.col.name')}</th>
              <th>{t('simulation.list.col.mitre')}</th>
              <th>{t('simulation.list.col.status')}</th>
              <th>{t('simulation.list.col.executedAt')}</th>
            </tr>
          </thead>
          <tbody>
            {data.map((sim) => (
              <tr
                key={sim.id}
                className="hover:bg-cloud cursor-pointer"
                onClick={() =>
                  navigate(`/engagements/${engagementId}/simulations/${sim.id}/edit`)
                }
              >
                <td>
                  <Link
                    to={`/engagements/${engagementId}/simulations/${sim.id}/edit`}
                    className="text-ink font-medium hover:underline"
                    onClick={(e) => e.stopPropagation()}
                  >
                    {sim.name}
                  </Link>
                </td>
                <td className="text-charcoal font-mono">
                  {(() => {
                    const items = [
                      ...(sim.tactics ?? []).map((tactic) => tactic.id),
                      ...sim.techniques.map((tech) => tech.id),
                    ];
                    if (items.length === 0) return '—';
                    if (items.length === 1) return items[0];
                    return `${items[0]} +${items.length - 1}`;
                  })()}
                </td>
                <td>
                  <SimulationStatusBadge status={sim.status} />
                </td>
                <td className="text-charcoal font-mono">
                  {sim.executed_at ? formatDateTime(sim.executed_at) : '—'}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
