function RunEvalModal({ dataset, agents, models, onClose, onStarted }) {
  const [agentId, setAgentId] = React.useState(agents[0]?.agent_id || "");
  const selectedAgent = agents.find((agent) => agent.agent_id === agentId) || null;
  const compatibleCatalogModels = (models || []).filter((model) => {
    const provider = selectedAgent?.modelProvider;
    return !provider || model.provider === provider || (model.providers || []).includes(provider);
  });
  const defaultModel = selectedAgent?.model || compatibleCatalogModels[0]?.id || "";
  const compatibleModels = compatibleCatalogModels.some((item) => item.id === defaultModel)
    ? compatibleCatalogModels
    : [{ id: defaultModel, label: defaultModel }, ...compatibleCatalogModels].filter((item) => item.id);
  const [model, setModel] = React.useState(defaultModel);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");

  React.useEffect(() => {
    setModel(defaultModel);
  }, [agentId]);
  React.useEffect(() => {
    const closeOnEscape = (event) => { if (event.key === "Escape") onClose(); };
    document.addEventListener("keydown", closeOnEscape);
    return () => document.removeEventListener("keydown", closeOnEscape);
  }, [onClose]);

  const start = async () => {
    if (!agentId || !model || submitting) return;
    setSubmitting(true);
    setError("");
    try {
      const run = await window.api.createEvalRun({
        dataset_id: dataset.id,
        agent_id: agentId,
        model,
      });
      pushToast({ content: <span>Started eval run on <strong>{dataset.name}</strong></span> });
      await onStarted?.(run);
      onClose();
    } catch (err) {
      setError(err.message || String(err));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="modal-backdrop" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>
      <div className="modal" style={{ maxWidth: 520 }} onMouseDown={(event) => event.stopPropagation()}>
        <div className="head">
          <div><h2>Run evaluation</h2><div className="sub">{dataset.name} · {dataset.cases.length} cases</div></div>
          <button className="close" onClick={onClose} title="Close"><Icon name="x" size={16} /></button>
        </div>
        <div className="body">
          <div className="mform-group">
            <div className="lbl">Agent</div>
            <select className="input-lg" value={agentId} onChange={(event) => setAgentId(event.target.value)} disabled={submitting}>
              {agents.map((agent) => <option key={agent.agent_id} value={agent.agent_id}>{agent.name}</option>)}
            </select>
          </div>
          <div className="mform-group" style={{ marginBottom: 0 }}>
            <div className="lbl">Model</div>
            <select className="input-lg" value={model} onChange={(event) => setModel(event.target.value)} disabled={submitting || !selectedAgent}>
              {compatibleModels.map((item) => <option key={item.id} value={item.id}>{item.label || item.id}</option>)}
            </select>
          </div>
          {error && <div style={{ marginTop: 12, color: "#b91c1c", fontSize: 12 }}>{error}</div>}
        </div>
        <div className="foot">
          <span className="hint">Runs cases serially.</span><div className="spacer" />
          <button className="btn" onClick={onClose} disabled={submitting}>Cancel</button>
          <button className="btn primary" onClick={start} disabled={!agentId || !model || submitting}>
            <Icon name="play" size={11} /> {submitting ? "Starting..." : "Run eval"}
          </button>
        </div>
      </div>
    </div>
  );
}

window.RunEvalModal = RunEvalModal;
