"use client";

import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { api, WorkflowStep, InputParam } 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 placeholder-text-secondary/50 focus:border-signal focus:outline-none focus:ring-1 focus:ring-signal";

export function EditStepModal({ open, step, onClose }: { open: boolean; step: WorkflowStep | null; onClose: () => void }) {
  const qc = useQueryClient();
  const [name, setName] = useState(step?.name ?? "");
  const [interpreter, setInterpreter] = useState<"bash" | "powershell">(step?.interpreter ?? "bash");
  const [script, setScript] = useState(step?.script ?? "");
  const [inputs, setInputs] = useState<InputParam[]>(step?.declared_inputs ?? []);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Default steps are re-seeded from the image on every boot, so the server
  // refuses to update or delete them. The form mirrors that rather than
  // offering buttons that can only 409.
  const locked = step?.source === "default";

  const save = async () => {
    setBusy(true); setError(null);
    try {
      const payload: Partial<WorkflowStep> = {
        name: name.trim(), description: step?.description ?? "", interpreter, script,
        declared_inputs: inputs.filter((i) => i.name.trim() !== ""),
        secret_refs: step?.secret_refs ?? [],
      };
      if (step) await api.updateStep(step.step_id, payload);
      else await api.createStep(payload);
      qc.invalidateQueries({ queryKey: ["steps"] });
      onClose();
    } catch (e) { setError((e as Error).message); } finally { setBusy(false); }
  };

  const del = async () => {
    if (!step || !window.confirm("Delete this step? It will be removed from every workflow that uses it.")) return;
    setBusy(true); setError(null);
    try {
      await api.deleteStep(step.step_id);
      qc.invalidateQueries({ queryKey: ["steps"] });
      qc.invalidateQueries({ queryKey: ["workflow"] });
      onClose();
    } catch (e) { setError((e as Error).message); } finally { setBusy(false); }
  };

  return (
    <Modal open={open} onClose={onClose} title={locked ? "Default step" : step ? "Edit base step" : "New step"} wide>
      <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>}
        {locked ? (
          <p className="rounded border border-border bg-surface-2 px-3 py-2 text-xs text-text-secondary">
            This step ships with Vantage and is read-only. It is re-seeded on every upgrade. Export it and import a copy to make your own version.
          </p>
        ) : (
          <p className="text-xs text-text-secondary">Reusable steps are shared across all workflows. Editing here changes it everywhere.</p>
        )}
        <div>
          <label className="mb-1 block text-xs uppercase text-text-secondary">Name</label>
          <input className={inputClass} value={name} readOnly={locked} onChange={(e) => setName(e.target.value)} />
        </div>
        <div>
          <label className="mb-1 block text-xs uppercase text-text-secondary">Interpreter</label>
          <select className={inputClass} value={interpreter} disabled={locked} onChange={(e) => setInterpreter(e.target.value as "bash" | "powershell")}>
            <option value="bash">bash</option>
            <option value="powershell">powershell</option>
          </select>
        </div>
        <div>
          <label className="mb-1 block text-xs uppercase text-text-secondary">Script</label>
          <textarea className={`${inputClass} h-40 font-mono text-xs`} value={script} readOnly={locked} onChange={(e) => setScript(e.target.value)} />
          <p className="mt-1 text-xs text-text-secondary">Write <code className="text-signal">KEY=value</code> to <code className="text-signal">$WORKFLOW_ENV</code> to expose it to later steps.</p>
        </div>
        <div>
          <label className="mb-1 block text-xs uppercase text-text-secondary">Outputs</label>
          <div className="mb-1 flex flex-wrap gap-1">
            {(step?.declared_outputs ?? []).length === 0 && (
              <p className="text-xs text-text-secondary">No declared outputs.</p>
            )}
            {(step?.declared_outputs ?? []).map((o) => (
              <span key={o} className="flex items-center gap-1 rounded bg-signal px-2 py-0.5 font-mono text-[11px] text-signal-ink">
                {o}
              </span>
            ))}
          </div>
          <p className="text-xs text-text-secondary">Outputs are detected automatically from lines writing to $WORKFLOW_ENV.</p>
        </div>
        <div>
          <label className="mb-1 block text-xs uppercase text-text-secondary">Inputs</label>
          <div className="space-y-2">
            {inputs.map((inp, i) => (
              <div key={i} className="flex gap-2">
                <input className={inputClass} readOnly={locked} placeholder="name" value={inp.name} onChange={(e) => setInputs(inputs.map((x, j) => j === i ? { ...x, name: e.target.value } : x))} />
                <input className={inputClass} readOnly={locked} placeholder="default" value={inp.default} onChange={(e) => setInputs(inputs.map((x, j) => j === i ? { ...x, default: e.target.value } : x))} />
                <input className={inputClass} readOnly={locked} placeholder="description" value={inp.description} onChange={(e) => setInputs(inputs.map((x, j) => j === i ? { ...x, description: e.target.value } : x))} />
                {!locked && <Button variant="ghost" size="sm" onClick={() => setInputs(inputs.filter((_, j) => j !== i))}>✕</Button>}
              </div>
            ))}
          </div>
          {!locked && (
            <Button variant="ghost" size="sm" className="mt-2" onClick={() => setInputs([...inputs, { name: "", default: "", description: "" }])}>Add input</Button>
          )}
        </div>
        <div className="flex items-center justify-between pt-2">
          {step && !locked ? <Button variant="danger" onClick={del} loading={busy}>Delete step</Button> : <span />}
          <div className="flex gap-2">
            <Button variant="ghost" onClick={onClose}>{locked ? "Close" : "Cancel"}</Button>
            {!locked && <Button variant="primary" onClick={save} loading={busy} disabled={!name.trim()}>Save</Button>}
          </div>
        </div>
      </div>
    </Modal>
  );
}
