// Manual add-case modal (used from Evals → Dataset → Cases tab)
// Reuses styles from evals-styles.css

function AddCaseModal({ dataset, toolOptions = [], onClose, onAdded }) {
  const [input, setInput] = React.useState("");
  const [expected, setExpected] = React.useState("");
  const [expectedTools, setExpectedTools] = React.useState([]);
  const [toolName, setToolName] = React.useState("");
  const [tags, setTags] = React.useState("");

  const addTool = (value) => {
    const name = String(value || "").trim();
    if (!name) return;
    setExpectedTools((current) => current.includes(name) ? current : [...current, name]);
    setToolName("");
  };
  const removeTool = (name) => setExpectedTools((current) => current.filter((item) => item !== name));

  // Esc to close
  React.useEffect(() => {
    const fn = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", fn);
    return () => document.removeEventListener("keydown", fn);
  }, [onClose]);

  const save = async () => {
    if (!input.trim()) return;
    try {
      const apiCase = await window.api.addDatasetCase(dataset.id, {
        input: input.trim(),
        expected: expected.trim() || null,
        tools: expectedTools,
        tags: tags.split(",").map((t) => t.trim()).filter(Boolean),
        source: { type: "manual" },
      });
      onAdded?.({ dataset, case: apiCase });
      pushToast({ content: <span>Added to <strong>{dataset.name}</strong></span>, duration: 3000 });
    } catch (err) {
      alert("Save case failed: " + (err.message || err));
    }
    onClose();
  };

  return (
    <div className="modal-backdrop" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" onMouseDown={(e) => e.stopPropagation()}>
        <div className="head">
          <div>
            <h2>New case</h2>
            <div className="sub">Adding to <strong>{dataset.name}</strong></div>
          </div>
          <button className="close" onClick={onClose} title="Close (Esc)"><Icon name="x" size={16} /></button>
        </div>
        <div className="body">
          <div className="mform-group">
            <div className="lbl">Input <span className="opt">— the user message · required</span></div>
            <textarea
              className="textarea-lg"
              style={{ minHeight: 64 }}
              autoFocus
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="e.g. How do I reset my password?"
            />
          </div>

          <div className="mform-group">
            <div className="lbl">Expected output <span className="opt">— optional reference answer</span></div>
            <textarea
              className="textarea-lg"
              style={{ minHeight: 100 }}
              value={expected}
              onChange={(e) => setExpected(e.target.value)}
              placeholder="Leave blank to rely on LLM-as-judge / trajectory graders only."
            />
          </div>

          <div className="mform-group">
            <div className="lbl">Expected tool calls <span className="opt">— what the agent should call</span></div>
            <div className="tool-call-controls">
              <select className="input-lg" value="" onChange={(event) => addTool(event.target.value)} aria-label="Select an available tool">
                <option value="">{toolOptions.length ? "Select an available tool" : "No tool suggestions available"}</option>
                {toolOptions.map((tool) => <option key={tool.id} value={tool.name}>{tool.label || tool.name}</option>)}
              </select>
              <input
                className="input-lg"
                value={toolName}
                placeholder="Enter a tool name"
                onChange={(event) => setToolName(event.target.value)}
                onKeyDown={(event) => {
                  if (event.key === "Enter" || event.key === ",") {
                    event.preventDefault();
                    addTool(toolName);
                  }
                }}
              />
              <button className="btn" title="Add tool" onClick={() => addTool(toolName)} disabled={!toolName.trim()}><Icon name="plus" size={12} /></button>
            </div>
            <div className="tool-multi" aria-label="Selected expected tool calls">
              {expectedTools.length ? expectedTools.map((name) => (
                <span className="selected-tool" key={name}>
                  {name}
                  <button title={`Remove ${name}`} onClick={() => removeTool(name)}><Icon name="x" size={11} /></button>
                </span>
              )) : <span className="tool-multi-empty">Select a suggestion or enter a tool name.</span>}
            </div>
            <div className="hint">Used by <span className="mono">tool_called</span> / <span className="mono">trajectory_match</span> graders.</div>
          </div>

          <div className="mform-group">
            <div className="lbl">Tags <span className="opt">— comma separated</span></div>
            <input
              className="input-lg"
              value={tags}
              placeholder="e.g. auth, p0, regression"
              onChange={(e) => setTags(e.target.value)}
            />
          </div>
        </div>
        <div className="foot">
          <span className="hint">Source: <span className="mono">manual</span></span>
          <div className="spacer" />
          <button className="btn" onClick={onClose}>Cancel</button>
          <button
            className="btn primary"
            disabled={!input.trim()}
            onClick={save}
          >
            <Icon name="plus" size={11} /> Add case
          </button>
        </div>
      </div>
    </div>
  );
}

window.AddCaseModal = AddCaseModal;
