"use client";

import { useState } from "react";
import { X, Plus, Minus } from "lucide-react";

interface McpAddModalProps {
  onClose: () => void;
  onAdd: (server: { name: string; description: string; command: string; args: string[]; env: Record<string, string> }) => Promise<void>;
}

export function McpAddModal({ onClose, onAdd }: McpAddModalProps) {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [command, setCommand] = useState("");
  const [args, setArgs] = useState<string[]>([""]);
  const [envPairs, setEnvPairs] = useState<{ key: string; value: string }[]>([{ key: "", value: "" }]);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    setError(null);
    if (!name.trim() || !command.trim()) {
      setError("Name and command are required");
      return;
    }
    setSubmitting(true);
    try {
      const env: Record<string, string> = {};
      for (const pair of envPairs) {
        if (pair.key.trim()) env[pair.key.trim()] = pair.value;
      }
      await onAdd({
        name: name.trim(),
        description: description.trim(),
        command: command.trim(),
        args: args.filter((a) => a.trim()),
        env,
      });
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to add server");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="w-full max-w-lg rounded-xl bg-white p-6 shadow-xl dark:bg-zinc-900">
        <div className="mb-4 flex items-center justify-between">
          <h3 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">Add MCP Server</h3>
          <button onClick={onClose} className="text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300">
            <X size={20} />
          </button>
        </div>

        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-xs font-medium text-zinc-500">Name</label>
              <input
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="w-full rounded-lg border border-zinc-200 px-3 py-2 text-sm dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
                placeholder="my-server"
              />
            </div>
            <div>
              <label className="mb-1 block text-xs font-medium text-zinc-500">Description</label>
              <input
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                className="w-full rounded-lg border border-zinc-200 px-3 py-2 text-sm dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
              />
            </div>
          </div>

          <div>
            <label className="mb-1 block text-xs font-medium text-zinc-500">Command</label>
            <input
              value={command}
              onChange={(e) => setCommand(e.target.value)}
              className="w-full rounded-lg border border-zinc-200 px-3 py-2 font-mono text-sm dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
              placeholder="/usr/bin/python3"
            />
          </div>

          <div>
            <label className="mb-1 block text-xs font-medium text-zinc-500">Args</label>
            {args.map((arg, i) => (
              <div key={i} className="mb-1 flex items-center gap-1">
                <input
                  value={arg}
                  onChange={(e) => { const a = [...args]; a[i] = e.target.value; setArgs(a); }}
                  className="flex-1 rounded-lg border border-zinc-200 px-3 py-1.5 font-mono text-sm dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
                />
                <button onClick={() => setArgs(args.filter((_, j) => j !== i))} className="text-zinc-400 hover:text-red-500">
                  <Minus size={14} />
                </button>
              </div>
            ))}
            <button onClick={() => setArgs([...args, ""])} className="mt-1 flex items-center gap-1 text-xs text-blue-600 hover:text-blue-700">
              <Plus size={12} /> Add arg
            </button>
          </div>

          <div>
            <label className="mb-1 block text-xs font-medium text-zinc-500">Environment Variables</label>
            {envPairs.map((pair, i) => (
              <div key={i} className="mb-1 flex items-center gap-1">
                <input
                  value={pair.key}
                  onChange={(e) => { const p = [...envPairs]; p[i] = { ...p[i], key: e.target.value }; setEnvPairs(p); }}
                  placeholder="KEY"
                  className="w-1/3 rounded-lg border border-zinc-200 px-2 py-1.5 font-mono text-sm dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
                />
                <input
                  value={pair.value}
                  onChange={(e) => { const p = [...envPairs]; p[i] = { ...p[i], value: e.target.value }; setEnvPairs(p); }}
                  placeholder="value"
                  className="flex-1 rounded-lg border border-zinc-200 px-2 py-1.5 font-mono text-sm dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
                />
                <button onClick={() => setEnvPairs(envPairs.filter((_, j) => j !== i))} className="text-zinc-400 hover:text-red-500">
                  <Minus size={14} />
                </button>
              </div>
            ))}
            <button onClick={() => setEnvPairs([...envPairs, { key: "", value: "" }])} className="mt-1 flex items-center gap-1 text-xs text-blue-600 hover:text-blue-700">
              <Plus size={12} /> Add variable
            </button>
          </div>
        </div>

        {error && <p className="mt-2 text-sm text-red-500">{error}</p>}

        <div className="mt-4 flex justify-end gap-2">
          <button onClick={onClose} className="rounded-lg px-4 py-2 text-sm text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800">
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={submitting}
            className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
          >
            {submitting ? "Adding..." : "Add Server"}
          </button>
        </div>
      </div>
    </div>
  );
}
