import { useEffect, useRef, useState } from "react";
import { open as openDialog } from "@tauri-apps/plugin-dialog";
import { PresetPicker, PRESETS } from "./PresetPicker";
import { openWorkspace, applyPreset, whichAgents } from "./socketBridge";
import { KNOWN_AGENTS, SHELL, CUSTOM, agentLabel, specForChoice } from "./agents";

export function Wizard({ onDone, onCancel }: { onDone: (workspaceId: string) => void; onCancel: () => void }) {
  const [path, setPath] = useState(".");
  const [preset, setPreset] = useState("2x2");
  const [agents, setAgents] = useState<string[]>([]);
  const [customCmds, setCustomCmds] = useState<string[]>([]);
  const [installed, setInstalled] = useState<string[]>([]);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const pathRef = useRef<HTMLInputElement>(null);
  const slots = PRESETS.find((p) => p.id === preset)?.slots ?? 1;
  const agentChoices = [SHELL, ...installed, CUSTOM];

  // Grab focus on open — otherwise keystrokes leak to the xterm panel behind us
  // (its helper textarea sits at z-index 1000 and keeps the live focus).
  useEffect(() => {
    pathRef.current?.focus();
    pathRef.current?.select();
  }, []);

  // Only offer agents the user actually has installed.
  useEffect(() => { void whichAgents(KNOWN_AGENTS).then(setInstalled).catch(() => {}); }, []);

  // Native folder picker — fills the path field with the chosen absolute directory.
  async function browse() {
    try {
      const picked = await openDialog({ directory: true, multiple: false, title: "Select project folder" });
      if (typeof picked === "string") setPath(picked);
    } catch { /* user cancelled or dialog unavailable */ }
  }

  // Close on Escape regardless of which element holds focus (the inner div's
  // onKeyDown misses it once focus moves to a preset button / select).
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") { e.preventDefault(); onCancel(); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onCancel]);

  async function create() {
    if (busy) return;
    setBusy(true);
    setError(null);
    try {
      const ws = await openWorkspace(path);
      const slotSpecs = Array.from({ length: slots }, (_, i) => specForChoice(agents[i] ?? SHELL, customCmds[i] ?? ""));
      await applyPreset(ws, preset, slotSpecs);
      onDone(ws);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
      setBusy(false);
    }
  }

  // Keep keyboard events inside the modal and add the obvious shortcuts.
  function onKeyDown(e: React.KeyboardEvent) {
    e.stopPropagation();
    if (e.key === "Escape") { e.preventDefault(); onCancel(); }
    else if (e.key === "Enter" && (e.target as HTMLElement).tagName !== "SELECT") { e.preventDefault(); void create(); }
  }

  return (
    <div
      onMouseDown={onCancel}
      style={{ position: "fixed", inset: 0, zIndex: 2000, background: "#000A", display: "flex", alignItems: "center", justifyContent: "center" }}
    >
      <div
        onMouseDown={(e) => e.stopPropagation()}
        onKeyDown={onKeyDown}
        style={{ width: 480, background: "#0E1116", border: "1px solid #323C49", borderRadius: 14, padding: 24, color: "#E6EDF3" }}
      >
        <div style={{ fontWeight: 700, fontSize: 16, marginBottom: 16 }}>New workspace</div>
        <label style={{ fontSize: 12, color: "#8B97A6" }}>Project folder</label>
        <div style={{ display: "flex", gap: 8, margin: "6px 0 16px" }}>
          <input ref={pathRef} value={path} onChange={(e) => setPath(e.target.value)} style={{ flex: 1, minWidth: 0, padding: 8, background: "#0A0D12", color: "#E6EDF3", border: "1px solid #323C49", borderRadius: 8 }} />
          <button onClick={() => void browse()} style={{ flex: "0 0 auto", padding: "8px 14px", background: "#1A2029", color: "#E6EDF3", border: "1px solid #323C49", borderRadius: 8, fontWeight: 600 }}>Browse…</button>
        </div>
        <label style={{ fontSize: 12, color: "#8B97A6" }}>Layout</label>
        <div style={{ margin: "8px 0 16px" }}><PresetPicker selected={preset} onSelect={setPreset} /></div>
        <label style={{ fontSize: 12, color: "#8B97A6" }}>Agents</label>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, margin: "8px 0 20px" }}>
          {Array.from({ length: slots }, (_, i) => {
            const val = agents[i] ?? SHELL;
            return (
              <div key={i} style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <select value={val} onChange={(e) => setAgents((a) => { const n = [...a]; n[i] = e.target.value; return n; })}
                  style={{ padding: 8, background: "#1A2029", color: "#E6EDF3", border: "1px solid #323C49", borderRadius: 6 }}>
                  {agentChoices.map((c) => <option key={c} value={c}>{agentLabel(c)}</option>)}
                </select>
                {val === CUSTOM && (
                  <input value={customCmds[i] ?? ""} placeholder="e.g. npm run dev"
                    onChange={(e) => setCustomCmds((c) => { const n = [...c]; n[i] = e.target.value; return n; })}
                    style={{ padding: 8, background: "#0A0D12", color: "#E6EDF3", border: "1px solid #4C8DFF", borderRadius: 6, fontFamily: "monospace", fontSize: 12 }} />
                )}
              </div>
            );
          })}
        </div>
        {error && <div style={{ margin: "0 0 14px", padding: "8px 10px", background: "#3A1418", border: "1px solid #6B2230", borderRadius: 8, fontSize: 12, color: "#FF9AA6" }}>{error}</div>}
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
          <button onClick={onCancel} style={{ padding: "8px 16px" }}>Cancel</button>
          <button onClick={() => void create()} disabled={busy} style={{ padding: "8px 16px", background: "#4C8DFF", color: "#0A0D12", border: "none", borderRadius: 8, fontWeight: 700, opacity: busy ? 0.6 : 1 }}>
            {busy ? "Creating…" : "Create workspace"}
          </button>
        </div>
      </div>
    </div>
  );
}
