import { useEffect, useState, type FormEvent } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { Save, Grid2x2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
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 { BackLink } from '@/components/BackLink';
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 { t } = useTranslation();
  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 tpl = existing.data;
      setForm({
        name: tpl.name,
        description: tpl.description ?? '',
        commands: tpl.commands ?? '',
        prerequisites: tpl.prerequisites ?? '',
      });
      setTechniques(tpl.techniques);
      setTactics(tpl.tactics);
    }
  }, [existing.data]);

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

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setFormError(null);
    if (!form.name.trim()) {
      setFormError(t('template.form.validation.nameRequired'));
      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((tech) => tech.id),
      tactic_ids: tactics.map((tac) => tac.id),
    };
    try {
      if (isNew) {
        const created = await createMutation.mutateAsync(payload);
        push(t('template.form.toast.created'), 'success');
        navigate(`/admin/templates/${created.id}/edit`, { replace: true });
      } else {
        await updateMutation.mutateAsync(payload);
        push(t('template.form.toast.saved'), 'success');
      }
    } catch (err) {
      setFormError(extractApiError(err, t('template.form.errorSave')));
    }
  };

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

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

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

  if (!isNew && existing.isLoading) return <LoadingState label={t('template.form.loading')} />;
  if (!isNew && existing.isError) {
    return (
      <ErrorState
        message={extractApiError(existing.error, t('template.form.errorLoad'))}
        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">
          <BackLink to="/admin/templates">{t('engagement.detail.backTo')}</BackLink>
          <h1 className="text-[32px] font-medium leading-none">
            {isNew ? t('template.form.title.new') : (existing.data?.name ?? t('template.form.title.edit'))}
          </h1>
        </div>
        {!isNew ? (
          <button
            type="button"
            className="btn-text-link text-bloom-deep"
            onClick={() => setShowDeleteConfirm(true)}
            disabled={deleteMutation.isPending}
          >
            {t('template.form.btn.delete')}
          </button>
        ) : null}
      </header>

      <form onSubmit={onSubmit} className="card-product flex flex-col gap-lg max-w-2xl">
        <FormField label={t('template.form.field.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={t('template.form.field.description')} htmlFor="tpl-desc">
          <TextArea
            id="tpl-desc"
            value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })}
            disabled={isPending}
            placeholder={t('template.form.field.descriptionPlaceholder')}
          />
        </FormField>

        <FormField label={t('template.form.field.commands')} htmlFor="tpl-commands" hint={t('template.form.field.commandsHint')}>
          <TextArea
            id="tpl-commands"
            value={form.commands}
            onChange={(e) => setForm({ ...form, commands: e.target.value })}
            disabled={isPending}
            placeholder={t('template.form.field.commandsPlaceholder')}
            className="font-mono text-[14px]"
          />
        </FormField>

        <FormField label={t('template.form.field.prerequisites')} htmlFor="tpl-prereqs">
          <TextArea
            id="tpl-prereqs"
            value={form.prerequisites}
            onChange={(e) => setForm({ ...form, prerequisites: e.target.value })}
            disabled={isPending}
            placeholder={t('template.form.field.prerequisitesPlaceholder')}
          />
        </FormField>

        <div className="flex flex-col gap-sm">
          <span className="text-[14px] font-medium text-ink">{t('template.form.field.mitre')}</span>

          {techniques.length === 0 && tactics.length === 0 ? (
            <p className="text-[13px] text-graphite">{t('template.form.field.mitreEmpty')}</p>
          ) : (
            <div className="flex flex-wrap gap-xs" data-testid="techniques-tag-list">
              {tactics.map((tac) => (
                <MitreTacticTag
                  key={tac.id}
                  tactic={tac}
                  onRemove={() => setTactics((prev) => prev.filter((x) => x.id !== tac.id))}
                />
              ))}
              {techniques.map((tech) => (
                <MitreTechniqueTag
                  key={tech.id}
                  technique={tech}
                  onRemove={() => setTechniques((prev) => prev.filter((x) => x.id !== tech.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)}
                >
                  {t('template.form.field.mitreSearch')}
                </button>
              )}
            </div>
            <button
              type="button"
              aria-label={t('template.form.field.mitreOpenMatrix')}
              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 ? t('template.form.btn.saving') : t('template.form.btn.save')}
          </button>
          <Link to="/admin/templates" className="btn-outline-ink">
            {t('template.form.btn.cancel')}
          </Link>
        </div>
      </form>

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

      {showDeleteConfirm ? (
        <ConfirmDialog
          title={t('template.form.deleteConfirm.title')}
          description={t('template.form.deleteConfirm.desc')}
          confirmLabel={t('template.form.deleteConfirm.confirm')}
          cancelLabel={t('template.form.deleteConfirm.cancel')}
          onConfirm={onDelete}
          onCancel={() => setShowDeleteConfirm(false)}
          destructive
        />
      ) : null}
    </div>
  );
}
