"use client";

import { useState, useEffect } from "react";
import { Save, RotateCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import type { MCPServerConfig, MCPServerInfo } from "@/lib/api/mcp";

type EditServerDialogProps = {
  server: MCPServerInfo | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: (name: string, config: Partial<MCPServerConfig>, restart: boolean) => Promise<void>;
};

function envToText(env?: Record<string, string>): string {
  if (!env) return "";
  return Object.entries(env).map(([k, v]) => `${k}=${v}`).join("\n");
}

function textToEnv(text: string): Record<string, string> | undefined {
  const trimmed = text.trim();
  if (!trimmed) return undefined;
  const env: Record<string, string> = {};
  for (const line of trimmed.split("\n")) {
    const idx = line.indexOf("=");
    if (idx > 0) {
      env[line.slice(0, idx).trim()] = line.slice(idx + 1).trim();
    }
  }
  return Object.keys(env).length > 0 ? env : undefined;
}

function headersToText(headers?: Record<string, string>): string {
  if (!headers) return "";
  return Object.entries(headers).map(([k, v]) => `${k}: ${v}`).join("\n");
}

function textToHeaders(text: string): Record<string, string> | undefined {
  const trimmed = text.trim();
  if (!trimmed) return undefined;
  const headers: Record<string, string> = {};
  for (const line of trimmed.split("\n")) {
    const idx = line.indexOf(":");
    if (idx > 0) {
      headers[line.slice(0, idx).trim()] = line.slice(idx + 1).trim();
    }
  }
  return Object.keys(headers).length > 0 ? headers : undefined;
}

export function EditServerDialog({ server, open, onOpenChange, onSave }: EditServerDialogProps) {
  const [command, setCommand] = useState("");
  const [args, setArgs] = useState("");
  const [env, setEnv] = useState("");
  const [url, setUrl] = useState("");
  const [headers, setHeaders] = useState("");
  const [saving, setSaving] = useState(false);
  const [saveAndRestart, setSaveAndRestart] = useState(false);

  useEffect(() => {
    if (server && open) {
      setCommand(server.config.command || "");
      setArgs((server.config.args || []).join(", "));
      setEnv(envToText(server.config.env));
      setUrl(server.config.url || "");
      setHeaders(headersToText(server.config.headers));
    }
  }, [server, open]);

  if (!server) return null;

  const isStdio = server.config.transport === "stdio";

  const handleSave = async (restart: boolean) => {
    setSaving(true);
    setSaveAndRestart(restart);
    try {
      const updates: Partial<MCPServerConfig> = {};

      if (isStdio) {
        updates.command = command.trim();
        updates.args = args.split(",").map((a) => a.trim()).filter(Boolean);
        updates.env = textToEnv(env) || {};
      } else {
        updates.url = url.trim();
        if (server.config.transport === "streamable-http") {
          updates.headers = textToHeaders(headers) || {};
        }
      }

      await onSave(server.name, updates, restart);
      onOpenChange(false);
    } catch (err) {
      console.error("Failed to update server:", err);
    } finally {
      setSaving(false);
      setSaveAndRestart(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] bg-sidebar border-foreground/10 text-foreground p-0 overflow-hidden max-h-[90vh] overflow-y-auto">
        <div className="h-1.5 w-full bg-[repeating-linear-gradient(45deg,var(--primary),var(--primary)_10px,transparent_10px,transparent_20px)]" />
        <div className="p-8 space-y-6">
          <DialogHeader>
            <DialogTitle className="text-2xl font-black uppercase tracking-tighter text-foreground">
              {server.name}
            </DialogTitle>
            <DialogDescription className="text-foreground/60 font-medium uppercase text-[10px] tracking-widest pt-1">
              {server.config.transport} transport — Edit server configuration
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-6">
            {isStdio ? (
              <>
                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Command</Label>
                  <Input
                    value={command}
                    onChange={(e) => setCommand(e.target.value)}
                    placeholder="e.g. npx, uvx, node"
                    className="bg-black/20 border-foreground/10 h-11 text-sm font-mono"
                  />
                </div>

                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Args (comma-separated)</Label>
                  <Input
                    value={args}
                    onChange={(e) => setArgs(e.target.value)}
                    placeholder="e.g. -y, @modelcontextprotocol/server-everything"
                    className="bg-black/20 border-foreground/10 h-11 text-xs font-mono"
                  />
                </div>

                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                    Environment Variables
                    <span className="text-foreground/30 font-normal normal-case ml-2">KEY=VALUE, 한 줄에 하나</span>
                  </Label>
                  <textarea
                    value={env}
                    onChange={(e) => setEnv(e.target.value)}
                    placeholder={"INVOICE_INPUT_FOLDER=/path/to/input\nINVOICE_OUTPUT_FOLDER=/path/to/output"}
                    className="bg-black/20 border border-foreground/10 rounded-md p-3 text-xs font-mono text-foreground min-h-[140px] resize-y focus:outline-none focus:border-primary/50 transition-colors leading-relaxed"
                    spellCheck={false}
                  />
                  <p className="text-[9px] text-muted-foreground/40 font-mono">
                    경로 등을 사용자 환경에 맞게 수정하세요. 저장 후 Restart 하면 적용됩니다.
                  </p>
                </div>
              </>
            ) : (
              <>
                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">URL</Label>
                  <Input
                    value={url}
                    onChange={(e) => setUrl(e.target.value)}
                    placeholder="e.g. http://localhost:3001/sse"
                    className="bg-black/20 border-foreground/10 h-11 text-xs font-mono"
                  />
                </div>

                {server.config.transport === "streamable-http" && (
                  <div className="grid gap-3">
                    <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                      Headers
                      <span className="text-foreground/30 font-normal normal-case ml-2">Key: Value, 한 줄에 하나</span>
                    </Label>
                    <textarea
                      value={headers}
                      onChange={(e) => setHeaders(e.target.value)}
                      placeholder="Authorization: Bearer xxx"
                      className="bg-black/20 border border-foreground/10 rounded-md p-3 text-xs font-mono text-foreground min-h-[100px] resize-y focus:outline-none focus:border-primary/50 transition-colors"
                      spellCheck={false}
                    />
                  </div>
                )}
              </>
            )}
          </div>

          <DialogFooter className="pt-6 border-t border-foreground/10 flex gap-3 sm:flex-row">
            <Button
              variant="outline"
              onClick={() => handleSave(false)}
              disabled={saving}
              className="flex-1 h-12 rounded-none border-2 font-black uppercase tracking-widest hover:bg-foreground/5"
            >
              <Save className="w-4 h-4 mr-2" />
              {saving && !saveAndRestart ? "Saving..." : "Save"}
            </Button>
            <Button
              onClick={() => handleSave(true)}
              disabled={saving}
              className="flex-1 h-12 rounded-none bg-primary text-primary-foreground font-black uppercase tracking-widest hover:opacity-90"
            >
              <RotateCw className={`w-4 h-4 mr-2 ${saving && saveAndRestart ? "animate-spin" : ""}`} />
              {saving && saveAndRestart ? "Restarting..." : "Save & Restart"}
            </Button>
          </DialogFooter>
        </div>
      </DialogContent>
    </Dialog>
  );
}
