import { useEffect, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { X, Loader2 } from "lucide-react";
import { createModificationRequest, type CampaignTest } from "../api/campaigns";

interface Props {
  campaignId: string;
  tests: CampaignTest[];
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

export default function RequestCampaignModificationModal({
  campaignId,
  tests,
  open,
  onClose,
  onSuccess,
}: Props) {
  const queryClient = useQueryClient();
  const [action, setAction] = useState<"add_test" | "remove_test">("remove_test");
  const [testId, setTestId] = useState("");
  const [justification, setJustification] = useState("");

  useEffect(() => {
    if (!open) {
      setAction("remove_test");
      setTestId("");
      setJustification("");
    }
  }, [open]);

  const mutation = useMutation({
    mutationFn: () =>
      createModificationRequest(campaignId, {
        action,
        test_id: testId,
        justification: justification.trim(),
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["campaign-modification-requests", campaignId] });
      onSuccess();
      onClose();
    },
  });

  if (!open) return null;

  const canSubmit = testId && justification.trim().length > 0 && !mutation.isPending;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
      <div className="w-full max-w-lg rounded-xl border border-gray-800 bg-gray-900 p-6">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-white">Request Campaign Modification</h2>
          <button onClick={onClose} className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-800 hover:text-white">
            <X className="h-5 w-5" />
          </button>
        </div>

        <div className="space-y-4">
          <div>
            <label className="mb-1.5 block text-sm font-medium text-gray-300">Action</label>
            <select
              value={action}
              onChange={(e) => setAction(e.target.value as "add_test" | "remove_test")}
              className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-300 focus:border-cyan-500 focus:outline-none"
            >
              <option value="remove_test">Remove a test from this campaign</option>
              <option value="add_test">Add an existing test to this campaign</option>
            </select>
          </div>

          {action === "remove_test" ? (
            <div>
              <label className="mb-1.5 block text-sm font-medium text-gray-300">Test to remove</label>
              <select
                value={testId}
                onChange={(e) => setTestId(e.target.value)}
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-300 focus:border-cyan-500 focus:outline-none"
              >
                <option value="">Select a test…</option>
                {tests.map((t) => (
                  <option key={t.test_id} value={t.test_id}>
                    {t.test_name || t.test_id}
                  </option>
                ))}
              </select>
            </div>
          ) : (
            <div>
              <label className="mb-1.5 block text-sm font-medium text-gray-300">Test ID to add</label>
              <input
                value={testId}
                onChange={(e) => setTestId(e.target.value)}
                placeholder="Paste the existing test's ID"
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 placeholder-gray-500 focus:border-cyan-500 focus:outline-none"
              />
            </div>
          )}

          <div>
            <label className="mb-1.5 block text-sm font-medium text-gray-300">
              Justification <span className="text-red-400">*</span>
            </label>
            <textarea
              value={justification}
              onChange={(e) => setJustification(e.target.value)}
              rows={3}
              placeholder="Why does this campaign need to change?"
              className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 placeholder-gray-500 focus:border-cyan-500 focus:outline-none"
            />
          </div>

          {mutation.isError && (
            <div className="rounded-lg border border-red-500/30 bg-red-900/20 p-3 text-sm text-red-400">
              {(mutation.error as Error)?.message || "Failed to submit request"}
            </div>
          )}
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <button
            onClick={onClose}
            className="rounded-lg border border-gray-700 px-4 py-2 text-sm text-gray-400 hover:bg-gray-800 transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={() => mutation.mutate()}
            disabled={!canSubmit}
            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 transition-colors"
          >
            {mutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
            Submit Request
          </button>
        </div>
      </div>
    </div>
  );
}
