import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { X, Loader2 } from "lucide-react";
import { createTemplate, type CreateTemplatePayload } from "../api/test-templates";
import { proposeTemplate } from "../api/template-suggestions";
import { getTechniques, type TechniqueSummary } from "../api/techniques";
import { useToast } from "./Toast";

const SEVERITY_OPTIONS = ["low", "medium", "high", "critical"];
const PLATFORM_OPTIONS = ["windows", "linux", "macos", "azure-ad", "office-365", "containers"];

/** Leads create a template directly into the live catalog; operators
 * (red_tech/blue_tech) propose one instead — it lands in the review
 * queue for a lead on their team to approve (with optional edits) or
 * discard, rather than going live immediately. */
export default function CreateTemplateModal({
  canCreateDirectly,
  onClose,
}: {
  canCreateDirectly: boolean;
  onClose: () => void;
}) {
  const queryClient = useQueryClient();
  const { showToast } = useToast();

  const { data: techniques, isLoading: techniquesLoading } = useQuery({
    queryKey: ["techniques"],
    queryFn: () => getTechniques(),
  });

  const [form, setForm] = useState<CreateTemplatePayload>({
    mitre_technique_id: "",
    name: "",
    description: "",
    source: "custom",
    attack_procedure: "",
    expected_detection: "",
    platform: "",
    severity: "",
  });

  const set = (field: keyof CreateTemplatePayload, value: string) =>
    setForm((f) => ({ ...f, [field]: value }));

  const directMutation = useMutation({
    mutationFn: () => createTemplate(form),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["test-templates"] });
      queryClient.invalidateQueries({ queryKey: ["test-templates-count"] });
      showToast("success", "Template created and added to the catalog");
      onClose();
    },
    onError: () => showToast("error", "Failed to create template"),
  });

  const proposeMutation = useMutation({
    mutationFn: () => proposeTemplate(form),
    onSuccess: () => {
      showToast("success", "Template proposed — a lead will review it before it's added to the catalog");
      onClose();
    },
    onError: () => showToast("error", "Failed to propose template"),
  });

  const isPending = directMutation.isPending || proposeMutation.isPending;
  const canSubmit = form.mitre_technique_id.trim() !== "" && form.name.trim() !== "";

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!canSubmit) return;
    if (canCreateDirectly) {
      directMutation.mutate();
    } else {
      proposeMutation.mutate();
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
      <div className="w-full max-w-2xl rounded-xl border border-gray-800 bg-gray-900 shadow-xl">
        <div className="flex items-center justify-between border-b border-gray-800 px-6 py-4">
          <h2 className="text-lg font-semibold text-white">
            {canCreateDirectly ? "Create Test Template" : "Propose Test Template"}
          </h2>
          <button onClick={onClose} className="rounded-lg p-1 text-gray-400 hover:bg-gray-800 hover:text-white">
            <X className="h-5 w-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="max-h-[70vh] space-y-4 overflow-y-auto px-6 py-4">
          {!canCreateDirectly && (
            <p className="rounded-lg border border-cyan-500/30 bg-cyan-500/10 px-3 py-2 text-xs text-cyan-300">
              This will be submitted for review — a lead on your team must approve it before it appears in the catalog.
            </p>
          )}

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-xs font-medium text-gray-500">
                MITRE Technique <span className="text-red-400">*</span>
              </label>
              <select
                required
                disabled={techniquesLoading}
                value={form.mitre_technique_id}
                onChange={(e) => set("mitre_technique_id", e.target.value)}
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 focus:border-cyan-500 focus:outline-none"
              >
                <option value="">Select a technique</option>
                {techniques?.map((tech: TechniqueSummary) => (
                  <option key={tech.id} value={tech.mitre_id}>
                    {tech.mitre_id} - {tech.name}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-medium text-gray-500">
                Name <span className="text-red-400">*</span>
              </label>
              <input
                required
                value={form.name}
                onChange={(e) => set("name", e.target.value)}
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 focus:border-cyan-500 focus:outline-none"
              />
            </div>
          </div>

          <div>
            <label className="mb-1 block text-xs font-medium text-gray-500">Description</label>
            <textarea
              rows={2}
              value={form.description || ""}
              onChange={(e) => set("description", e.target.value)}
              className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 focus:border-cyan-500 focus:outline-none"
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-xs font-medium text-gray-500">Platform</label>
              <select
                value={form.platform || ""}
                onChange={(e) => set("platform", e.target.value)}
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 focus:border-cyan-500 focus:outline-none"
              >
                <option value="">Unspecified</option>
                {PLATFORM_OPTIONS.map((p) => (
                  <option key={p} value={p}>{p}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-medium text-gray-500">Severity</label>
              <select
                value={form.severity || ""}
                onChange={(e) => set("severity", e.target.value)}
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 focus:border-cyan-500 focus:outline-none"
              >
                <option value="">Unspecified</option>
                {SEVERITY_OPTIONS.map((s) => (
                  <option key={s} value={s}>{s}</option>
                ))}
              </select>
            </div>
          </div>

          <div>
            <label className="mb-1 block text-xs font-medium text-gray-500">Suggested Attack Procedure</label>
            <textarea
              rows={3}
              value={form.attack_procedure || ""}
              onChange={(e) => set("attack_procedure", e.target.value)}
              className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 font-mono text-sm text-gray-200 focus:border-cyan-500 focus:outline-none"
            />
          </div>

          <div>
            <label className="mb-1 block text-xs font-medium text-gray-500">Expected Detection</label>
            <textarea
              rows={3}
              value={form.expected_detection || ""}
              onChange={(e) => set("expected_detection", e.target.value)}
              className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 font-mono text-sm text-gray-200 focus:border-cyan-500 focus:outline-none"
            />
          </div>

          <div className="flex justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="rounded-lg border border-gray-700 px-4 py-2 text-sm text-gray-400 hover:bg-gray-800"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={!canSubmit || isPending}
              className="flex items-center gap-1.5 rounded-lg bg-cyan-600 px-4 py-2 text-sm font-medium text-white hover:bg-cyan-500 disabled:opacity-50"
            >
              {isPending && <Loader2 className="h-4 w-4 animate-spin" />}
              {canCreateDirectly ? "Create Template" : "Submit for Review"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
