"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { api, Workflow } from "@/lib/api";
import { Button, Modal } from "@/components/ui";

const inputClass =
  "w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary focus:border-signal focus:outline-none focus:ring-1 focus:ring-signal";

export function EditWorkflowModal({ open, workflow, onSaved, onClose }: { open: boolean; workflow: Workflow; onSaved: (w: Workflow) => void; onClose: () => void }) {
  const router = useRouter();
  const [name, setName] = useState(workflow.name);
  const [targets, setTargets] = useState<string[]>(workflow.target_server_ids);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { data: servers } = useQuery({ queryKey: ["servers"], queryFn: api.listServers });

  useEffect(() => {
    if (open) {
      setName(workflow.name);
      setTargets(workflow.target_server_ids);
    }
  }, [open, workflow]);

  const toggle = (id: string) => setTargets((t) => (t.includes(id) ? t.filter((x) => x !== id) : [...t, id]));

  const save = async () => {
    setBusy(true); setError(null);
    try {
      const updated = await api.updateWorkflow(workflow.workflow_id, { ...workflow, name, target_server_ids: targets });
      onSaved(updated); onClose();
    } catch (e) { setError((e as Error).message); } finally { setBusy(false); }
  };

  const del = async () => {
    if (!window.confirm("Delete this workflow? This cannot be undone.")) return;
    setBusy(true); setError(null);
    try { await api.deleteWorkflow(workflow.workflow_id); router.push("/workflows"); }
    catch (e) { setError((e as Error).message); setBusy(false); }
  };

  return (
    <Modal open={open} onClose={onClose} title="Edit workflow">
      <div className="space-y-4">
        {error && <div className="rounded border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">{error}</div>}
        <div>
          <label className="mb-1 block text-xs uppercase text-text-secondary">Name</label>
          <input className={inputClass} value={name} onChange={(e) => setName(e.target.value)} />
        </div>
        <div>
          <label className="mb-1 block text-xs uppercase text-text-secondary">Target servers</label>
          <div className="flex flex-wrap gap-2">
            {servers?.map((s) => {
              const on = targets.includes(s.server_id);
              return (
                <label key={s.server_id} className={`flex cursor-pointer items-center gap-2 rounded-lg border px-2 py-1 text-sm ${on ? "border-signal bg-signal/10 text-text-primary" : "border-border text-text-secondary"}`}>
                  <input type="checkbox" className="accent-signal" checked={on} onChange={() => toggle(s.server_id)} />
                  {s.hostname}
                </label>
              );
            })}
            {servers && servers.length === 0 && <p className="text-xs text-text-secondary">No servers registered.</p>}
          </div>
        </div>
        <div className="flex items-center justify-between pt-2">
          <Button variant="danger" onClick={del} loading={busy}>Delete workflow</Button>
          <div className="flex gap-2">
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <Button variant="primary" onClick={save} loading={busy} disabled={!name.trim()}>Save</Button>
          </div>
        </div>
      </div>
    </Modal>
  );
}
