// Command palette — scenarios, steps, scenes, recents, real actions.
import { useEffect, useMemo } from "react";
import { Command } from "cmdk";
import { useApp, scenarioById } from "../state/store";
import { Play, Branch, Bot, Check, Home, HistoryIcon, Layers, Search, Refresh, Cog, User } from "./icons";

export default function CommandBar() {
  const open = useApp((s) => s.cmdOpen);
  const setOpen = useApp((s) => s.setCmdOpen);
  const setScenarioId = useApp((s) => s.setScenarioId);
  const setSelectedStepId = useApp((s) => s.setSelectedStepId);
  const setScene = useApp((s) => s.setScene);
  const recents = useApp((s) => s.recents);
  const scenarioId = useApp((s) => s.scenarioId);
  const pushRecent = useApp((s) => s.pushRecent);
  const scenarios = useApp((s) => s.scenarios);
  const mode = useApp((s) => s.mode);
  const setMode = useApp((s) => s.setMode);
  const refreshLive = useApp((s) => s.refreshLive);
  const startInstance = useApp((s) => s.startInstance);
  const executeAction = useApp((s) => s.executeAction);
  const pushToast = useApp((s) => s.pushToast);
  const setConsoleOpen = useApp((s) => s.setConsoleOpen);
  const setTheme = useApp((s) => s.setTheme);
  const theme = useApp((s) => s.theme);
  const actor = useApp((s) => s.actor);

  const sc = scenarioById(scenarioId);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setOpen(!open);
      }
      if (e.key === "Escape" && open) setOpen(false);
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, setOpen]);

  const stepItems = useMemo(() => sc?.steps ?? [], [sc]);

  if (!open) return null;

  const close = () => setOpen(false);

  const canActLive = mode === "live" && actor?.user_id && sc?.live && sc.headlineTx;
  const firstActionId = sc?.steps.find((s) => s.state === "running")?.actions?.[0]?.id;

  return (
    <div className="cmd-overlay" onClick={close}>
      <Command className="cmd" onClick={(e) => e.stopPropagation()} label="Command bar">
        <div className="cmd-input-row">
          <Search size={14} />
          <Command.Input autoFocus placeholder="Switch scenario · jump to step · start instance · execute action…" />
          <kbd className="kbd-hint">esc</kbd>
        </div>
        <Command.List>
          <Command.Empty>No matches.</Command.Empty>

          {recents.length > 0 && (
            <Command.Group heading="Recent">
              {recents.map((r, i) => (
                <Command.Item key={`r-${i}-${r}`} onSelect={() => { pushRecent(r); close(); }}>
                  <HistoryIcon size={13} /> {r}
                </Command.Item>
              ))}
            </Command.Group>
          )}

          <Command.Group heading="Scenes">
            <Command.Item onSelect={() => { setScene("landing"); close(); }}>
              <Home size={13} /> Landing
            </Command.Item>
            <Command.Item onSelect={() => { setScene("mission"); close(); }}>
              <Layers size={13} /> Mission Control
            </Command.Item>
            <Command.Item onSelect={() => { setScene("history"); close(); }}>
              <HistoryIcon size={13} /> Run History
            </Command.Item>
            <Command.Item onSelect={() => { setScene("studio"); close(); }}>
              <Branch size={13} /> Process Wizard
              <span className="cmd-hint">design & publish a new process</span>
            </Command.Item>
            <Command.Item onSelect={() => { setScene("settings"); close(); }}>
              <Cog size={13} /> Settings
            </Command.Item>
          </Command.Group>

          <Command.Group heading="Data mode">
            {mode === "live" ? (
              <Command.Item onSelect={() => { refreshLive(); close(); }}>
                <Refresh size={13} /> Refresh live scenarios
                <span className="cmd-hint">re-fetch demo.flow-master.ai</span>
              </Command.Item>
            ) : (
              <Command.Item onSelect={() => { setMode("live"); close(); }}>
                <Refresh size={13} /> Switch to LIVE mode (fetch demo.flow-master.ai)
                <span className="cmd-hint">in-browser</span>
              </Command.Item>
            )}
            <Command.Item onSelect={() => { setMode("snapshot"); close(); }}>
              <Layers size={13} /> Switch to SNAPSHOT mode
              <span className="cmd-hint">bundled JSON</span>
            </Command.Item>
            <Command.Item onSelect={() => { setConsoleOpen(true); close(); }}>
              <Layers size={13} /> Open live API console
              <span className="cmd-hint">stream every fetch</span>
            </Command.Item>
            <Command.Item onSelect={() => { setTheme(theme === "dark" ? "light" : "dark"); close(); }}>
              <Cog size={13} /> Toggle theme
              <span className="cmd-hint">{theme === "dark" ? "→ light" : "→ dark"}</span>
            </Command.Item>
          </Command.Group>

          <Command.Group heading="Real actions">
            {sc?.live ? (
              <Command.Item
                onSelect={async () => {
                  close();
                  if (mode !== "live") { pushToast("warn", "Switch to LIVE mode to start a real instance."); return; }
                  await startInstance(sc.defKey, `Started via Mission Control · ${new Date().toLocaleString()}`);
                }}
              >
                <Play size={13} /> Start new instance of "{sc.defName}"
                <span className="cmd-hint">POST /api/runtime/transactions</span>
              </Command.Item>
            ) : (
              <Command.Item disabled>
                <Play size={13} /> Start new instance
                <span className="cmd-hint">switch to a LIVE scenario first</span>
              </Command.Item>
            )}
            {canActLive && firstActionId && (
              <Command.Item
                onSelect={async () => { close(); await executeAction(sc!.headlineTx!, firstActionId); }}
              >
                <Check size={13} /> Execute "{firstActionId}" on headline tx
                <span className="cmd-hint">{sc?.headlineTx?.slice(0, 8)} · real</span>
              </Command.Item>
            )}
            <Command.Item onSelect={() => { setScene("settings"); close(); }}>
              <User size={13} /> Sign in as different user
              <span className="cmd-hint">Settings → identity</span>
            </Command.Item>
          </Command.Group>

          <Command.Group heading="Scenarios">
            {scenarios.map((s) => (
              <Command.Item
                key={s.id}
                value={`scenario ${s.id} ${s.family.label} ${s.defName}`}
                onSelect={() => { setScenarioId(s.id); setScene("mission"); close(); }}
              >
                <Branch size={13} style={{ color: s.family.accent }} />
                {s.family.label}
                <span className="cmd-hint">{s.live ? "live" : "blueprint"} · {s.defName}</span>
              </Command.Item>
            ))}
          </Command.Group>

          {sc && (
            <Command.Group heading="Jump to step">
              {stepItems.map((st) => (
                <Command.Item
                  key={st.id}
                  value={`step ${st.id} ${st.name} ${st.kind}`}
                  onSelect={() => { setSelectedStepId(st.id); setScene("mission"); close(); }}
                >
                  <span className={`dot dot-${st.state}`} aria-hidden /> {st.name}
                  <span className="cmd-hint mono">{st.kind}</span>
                </Command.Item>
              ))}
            </Command.Group>
          )}

          <Command.Group heading="Agent">
            <Command.Item
              onSelect={async () => {
                close();
                pushToast("info", `Sidekick dispatch endpoint not yet wired — see Studio for process-level changes.`);
              }}
            >
              <Bot size={13} /> Dispatch sidekick agent
              <span className="cmd-hint">coming soon</span>
            </Command.Item>
          </Command.Group>
        </Command.List>
      </Command>
    </div>
  );
}
