"use client";

import { useState, useEffect } from "react";
import { Save, Plus, Minus } from "lucide-react";
import type { McpServerDefinition } from "@/lib/types";
import { AgentToggleRow } from "./AgentToggleRow";

interface McpDetailProps {
  server: McpServerDefinition;
  onUpdate: (name: string, updates: { description?: string; command?: string; args?: string[]; env?: Record<string, string> }) => Promise<void>;
  onToggleAgent: (agentName: string, enabled: boolean) => void;
}

export function McpDetail({ server, onUpdate, onToggleAgent }: McpDetailProps) {
  const [description, setDescription] = useState(server.description);
  const [command, setCommand] = useState(server.command);
  const [args, setArgs] = useState<string[]>(server.args);
  const [envPairs, setEnvPairs] = useState<{ key: string; value: string }[]>([]);
  const [saving, setSaving] = useState(false);
  const [dirty, setDirty] = useState(false);

  // Reset form only when selecting a different server (server.name changes)
  useEffect(() => {
    setDescription(server.description);
    setCommand(server.command);
    setArgs([...server.args]);
    setEnvPairs(
      Object.entries(server.env).map(([key, value]) => ({ key, value }))
    );
    setDirty(false);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [server.name]);

  const handleSave = async () => {
    setSaving(true);
    try {
      const env: Record<string, string> = {};
      for (const pair of envPairs) {
        if (pair.key.trim()) env[pair.key.trim()] = pair.value;
      }
      await onUpdate(server.name, {
        description,
        command,
        args: args.filter((a) => a.trim()),
        env,
      });
      setDirty(false);
    } finally {
      setSaving(false);
    }
  };

  const markDirty = () => setDirty(true);

  return (
    <div className="flex h-full flex-col overflow-y-auto p-6">
      <div className="mb-6 flex items-start justify-between">
        <div>
          <h2 className="text-xl font-bold text-zinc-900 dark:text-zinc-100">{server.name}</h2>
        </div>
        <button
          onClick={handleSave}
          disabled={!dirty || saving}
          className="flex items-center gap-1.5 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
        >
          <Save size={14} />
          {saving ? "Saving..." : "Save"}
        </button>
      </div>

      <div className="mb-4">
        <label className="mb-1 block text-xs font-semibold uppercase tracking-wider text-zinc-400">Description</label>
        <input
          value={description}
          onChange={(e) => { setDescription(e.target.value); markDirty(); }}
          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 className="mb-4">
        <label className="mb-1 block text-xs font-semibold uppercase tracking-wider text-zinc-400">Command</label>
        <input
          value={command}
          onChange={(e) => { setCommand(e.target.value); markDirty(); }}
          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"
        />
      </div>

      <div className="mb-4">
        <label className="mb-1 block text-xs font-semibold uppercase tracking-wider text-zinc-400">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); markDirty(); }}
              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)); markDirty(); }} className="text-zinc-400 hover:text-red-500">
              <Minus size={14} />
            </button>
          </div>
        ))}
        <button onClick={() => { setArgs([...args, ""]); markDirty(); }} 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 className="mb-6">
        <label className="mb-1 block text-xs font-semibold uppercase tracking-wider text-zinc-400">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); markDirty(); }}
              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); markDirty(); }}
              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)); markDirty(); }} className="text-zinc-400 hover:text-red-500">
              <Minus size={14} />
            </button>
          </div>
        ))}
        <button onClick={() => { setEnvPairs([...envPairs, { key: "", value: "" }]); markDirty(); }} className="mt-1 flex items-center gap-1 text-xs text-blue-600 hover:text-blue-700">
          <Plus size={12} /> Add variable
        </button>
      </div>

      <AgentToggleRow assignedAgents={server.agents} onToggle={onToggleAgent} />
    </div>
  );
}
