import { useEffect, useState, type FormEvent } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { Save, Grid2x2 } from 'lucide-react';
import { extractApiError } from '@/api/client';
import type { MitreTechnique, MitreTacticRef } from '@/api/types';
import { useToast } from '@/hooks/useToast';
import { useCreateTemplate, useDeleteTemplate, useTemplate, useUpdateTemplate } from '@/hooks/useTemplates';
import { FormField, TextArea, TextInput } from '@/components/FormField';
import { LoadingState } from '@/components/LoadingState';
import { ErrorState } from '@/components/ErrorState';
import { ConfirmDialog } from '@/components/ConfirmDialog';
import { MitreTechniqueTag, MitreTacticTag } from '@/components/MitreTechniqueTag';
import { MitreTechniquePicker } from '@/components/MitreTechniquePicker';
import { MitreMatrixModal } from '@/components/MitreMatrixModal';
import type { MatrixSelection } from '@/components/MitreMatrixModal';

interface FormState {
  name: string;
  description: string;
  commands: string;
  prerequisites: string;
}

const EMPTY: FormState = { name: '', description: '', commands: '', prerequisites: '' };

export function TemplateFormPage(): JSX.Element {
  const { id } = useParams<{ id: string }>();
  const templateId = id ? Number(id) : undefined;
  const isNew = !templateId;

  const navigate = useNavigate();
  const { push } = useToast();

  const existing = useTemplate(templateId);
  const createMutation = useCreateTemplate();
  const updateMutation = useUpdateTemplate(templateId ?? 0);
  const deleteMutation = useDeleteTemplate();

  const [form, setForm] = useState<FormState>(EMPTY);
  const [techniques, setTechniques] = useState<MitreTechnique[]>([]);
  const [tactics, setTactics] = useState<MitreTacticRef[]>([]);
  const [formError, setFormError] = useState<string | null>(null);
  const [showMatrix, setShowMatrix] = useState(false);
  const [showPicker, setShowPicker] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  useEffect(() => {
    if (existing.data) {
      const t = existing.data;
      setForm({
        name: t.name,
        description: t.description ?? '',
        commands: t.commands ?? '',
        prerequisites: t.prerequisites ?? '',
      });
      setTechniques(t.techniques);
      setTactics(t.tactics);
    }
  }, [existing.data]);

  const isPending = createMutation.isPending || updateMutation.isPending;

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setFormError(null);
    if (!form.name.trim()) {
      setFormError('Name is required');
      return;
    }
    const payload = {
      name: form.name.trim(),
      description: form.description.trim() || null,
      commands: form.commands.trim() || null,
      prerequisites: form.prerequisites.trim() || null,
      technique_ids: techniques.map((t) => t.id),
      tactic_ids: tactics.map((t) => t.id),
    };
    try {
      if (isNew) {
        const created = await createMutation.mutateAsync(payload);
        push('Template created', 'success');
        navigate(`/admin/templates/${created.id}/edit`, { replace: true });
      } else {
        await updateMutation.mutateAsync(payload);
        push('Template saved', 'success');
      }
    } catch (err) {
      setFormError(extractApiError(err, 'Could not save template'));
    }
  };

  const onDelete = async () => {
    if (!templateId) return;
    try {
      await deleteMutation.mutateAsync(templateId);
      push('Template deleted', 'success');
      navigate('/admin/templates', { replace: true });
    } catch (err) {
      push(extractApiError(err, 'Could not delete template'), 'error');
    }
    setShowDeleteConfirm(false);
  };

  const handleMatrixApply = ({ techniques: newTech, tactics: newTac }: MatrixSelection) => {
    setShowMatrix(false);
    setTechniques(newTech);
    setTactics(newTac);
  };

  const handlePickerSelect = (technique: MitreTechnique) => {
    if (techniques.some((t) => t.id === technique.id)) return;
    setTechniques((prev) => [...prev, technique]);
    setShowPicker(false);
  };

  if (!isNew && existing.isLoading) return <LoadingState label="Loading template…" />;
  if (!isNew && existing.isError) {
    return (
      <ErrorState
        message={extractApiError(existing.error, 'Could not load template')}
        onRetry={() => existing.refetch()}
      />
    );
  }

  return (
    <div className="flex flex-col gap-xl">
      <header className="flex items-start justify-between gap-md">
        <div className="flex flex-col gap-sm">
          <Link to="/admin/templates" className="btn-text-link text-[14px]">
            ← Back to templates
          </Link>
          <h1 className="text-[32px] font-medium leading-none">
            {isNew ? 'New template' : (existing.data?.name ?? 'Edit template')}
          </h1>
        </div>
        {!isNew ? (
          <button
            type="button"
            className="btn-text-link text-bloom-deep"
            onClick={() => setShowDeleteConfirm(true)}
            disabled={deleteMutation.isPending}
          >
            Delete
          </button>
        ) : null}
      </header>

      <form onSubmit={onSubmit} className="card-product flex flex-col gap-lg max-w-2xl">
        <FormField label="Name" htmlFor="tpl-name" required error={formError}>
          <TextInput
            id="tpl-name"
            value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
            disabled={isPending}
          />
        </FormField>

        <FormField label="Description" htmlFor="tpl-desc">
          <TextArea
            id="tpl-desc"
            value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })}
            disabled={isPending}
            placeholder="What does this simulation cover?"
          />
        </FormField>

        <FormField label="Commands" htmlFor="tpl-commands" hint="One command per line">
          <TextArea
            id="tpl-commands"
            value={form.commands}
            onChange={(e) => setForm({ ...form, commands: e.target.value })}
            disabled={isPending}
            placeholder="e.g. mimikatz.exe&#10;sekurlsa::logonpasswords"
            className="font-mono text-[14px]"
          />
        </FormField>

        <FormField label="Prerequisites" htmlFor="tpl-prereqs">
          <TextArea
            id="tpl-prereqs"
            value={form.prerequisites}
            onChange={(e) => setForm({ ...form, prerequisites: e.target.value })}
            disabled={isPending}
            placeholder="e.g. Local admin access required"
          />
        </FormField>

        <div className="flex flex-col gap-sm">
          <span className="text-[14px] font-medium text-ink">MITRE Techniques &amp; Tactics</span>

          {techniques.length === 0 && tactics.length === 0 ? (
            <p className="text-[13px] text-graphite">No techniques selected</p>
          ) : (
            <div className="flex flex-wrap gap-xs" data-testid="techniques-tag-list">
              {tactics.map((t) => (
                <MitreTacticTag
                  key={t.id}
                  tactic={t}
                  onRemove={() => setTactics((prev) => prev.filter((x) => x.id !== t.id))}
                />
              ))}
              {techniques.map((t) => (
                <MitreTechniqueTag
                  key={t.id}
                  technique={t}
                  onRemove={() => setTechniques((prev) => prev.filter((x) => x.id !== t.id))}
                />
              ))}
            </div>
          )}

          <div className="flex items-center gap-xs max-w-sm">
            <div className="flex-1">
              {showPicker ? (
                <MitreTechniquePicker onSelect={handlePickerSelect} />
              ) : (
                <button
                  type="button"
                  className="text-input h-9 text-[13px] text-graphite text-left cursor-text w-full"
                  onClick={() => setShowPicker(true)}
                >
                  Search technique (e.g. T1059)…
                </button>
              )}
            </div>
            <button
              type="button"
              aria-label="Open MITRE matrix"
              onClick={() => { setShowPicker(false); setShowMatrix(true); }}
              className="flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-none border border-steel text-graphite hover:text-ink hover:border-ink"
            >
              <Grid2x2 size={16} />
            </button>
          </div>
        </div>

        <div className="flex items-center gap-md pt-xs border-t border-hairline">
          <button type="submit" className="btn-primary" disabled={isPending}>
            <Save size={14} aria-hidden /> {isPending ? 'Saving…' : 'Save'}
          </button>
          <Link to="/admin/templates" className="btn-outline-ink">
            Cancel
          </Link>
        </div>
      </form>

      <MitreMatrixModal
        isOpen={showMatrix}
        initialTechniques={techniques}
        initialTactics={tactics}
        onApply={handleMatrixApply}
        onCancel={() => setShowMatrix(false)}
      />

      {showDeleteConfirm ? (
        <ConfirmDialog
          title="Delete template"
          description={`Delete "${existing.data?.name ?? 'this template'}"? This cannot be undone. Simulations already created from it are unaffected.`}
          confirmLabel="Delete"
          onConfirm={onDelete}
          onCancel={() => setShowDeleteConfirm(false)}
          destructive
        />
      ) : null}
    </div>
  );
}
