import { useState } from 'react';
import { useGraph } from '../store';
import { api } from '../api';
import { runPipeline } from '../runner';
import { pipelineTotal, formatPrice } from '../pricing';

export function Toolbar() {
  const addNode = useGraph((s) => s.addNode);
  const setRuntime = useGraph((s) => s.setRuntime);
  const importGraph = useGraph((s) => s.importGraph);
  const reset = useGraph((s) => s.reset);
  const nodes = useGraph((s) => s.nodes);
  const characters = useGraph((s) => s.characters);
  const [running, setRunning] = useState(false);

  const place = () => ({ x: 80 + Math.round((useGraph.getState().nodes.length % 5) * 60), y: 90 });
  const total = pipelineTotal(nodes);

  const onRunAll = async () => {
    setRunning(true);
    try { await runPipeline(() => useGraph.getState(), setRuntime, api); }
    catch (e) { alert(`Cannot run pipeline: ${(e as Error).message}`); }
    finally { setRunning(false); }
  };

  const onExport = () => {
    const { nodes: n, edges, characters: chars } = useGraph.getState();
    const blob = new Blob([JSON.stringify({ nodes: n, edges, characters: chars }, null, 2)], { type: 'application/json' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob); a.download = 'workflow.json'; a.click();
  };
  const onImport = async (file?: File) => {
    if (!file) return;
    try { importGraph(JSON.parse(await file.text())); }
    catch { alert('Could not import: invalid workflow file.'); }
  };

  return (
    <div className="flex items-center gap-2 px-3 py-2 text-sm">
      <button onClick={() => addNode('t2i', place())} className="rounded bg-zinc-700 px-3 py-1 hover:bg-zinc-600">+ Box</button>
      <div className="mx-1 h-5 w-px bg-zinc-700" />
      <button onClick={onRunAll} disabled={running} className="rounded bg-indigo-600 px-3 py-1 font-semibold hover:bg-indigo-500 disabled:opacity-50">
        {running ? 'Running…' : `Run pipeline · ${formatPrice(total)}`}
      </button>
      <div className="mx-1 h-5 w-px bg-zinc-700" />
      <button onClick={onExport} className="rounded bg-zinc-700 px-3 py-1 hover:bg-zinc-600">Export</button>
      <label className="cursor-pointer rounded bg-zinc-700 px-3 py-1 hover:bg-zinc-600">Import<input type="file" accept="application/json" hidden onChange={(e) => onImport(e.target.files?.[0])} /></label>
      <button onClick={() => { if (confirm('Clear the canvas?')) reset(); }} className="rounded bg-zinc-800 px-3 py-1 hover:bg-red-700">Clear</button>
      <div className="ml-auto text-[11px] text-zinc-500">{nodes.length} box{nodes.length !== 1 ? 'es' : ''} · {characters.length} character{characters.length !== 1 ? 's' : ''}</div>
    </div>
  );
}
