import { useState, useEffect } from "react";
import { api, getErrorMessage } from "../api";
import StatusMessage from "./StatusMessage";
import LogViewer from "./LogViewer";

interface Props {
  onReady: (ready: boolean, info?: { vocab_size: number; sentences: number; vector_size: number }) => void;
}

export default function Word2VecPanel({ onReady }: Props) {
  const [statusChecked, setStatusChecked] = useState(false);
  const [vectorSize, setVectorSize] = useState(100);
  const [windowSize, setWindowSize] = useState(5);
  const [w2vEpochs, setW2vEpochs] = useState(50);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [initLoading, setInitLoading] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    api.w2vStatus().then(res => {
      if (res.ready) {
        onReady(true, { vocab_size: res.vocab_size!, sentences: res.sentences!, vector_size: res.vector_size! });
      }
      setStatusChecked(true);
    }).catch(() => setStatusChecked(true));
  }, []);

  async function handleTrainFromEngine() {
    setInitLoading(true); setError("");
    try {
      const res = await api.w2vInitFromEngine({
        vector_size: vectorSize,
        window: windowSize,
        epochs: w2vEpochs,
      });
      onReady(true, { vocab_size: res.vocab_size, sentences: res.sentences, vector_size: res.vector_size });
    } catch (err) {
      setError(getErrorMessage(err));
    } finally {
      setInitLoading(false);
    }
  }

  if (!statusChecked) {
    return <div className="panel"><p>Checking Word2Vec status...</p></div>;
  }

  return (
    <div>
      <div className="panel">
        <h2>Word2Vec Baseline (gensim)</h2>
        <p className="panel-desc">
          Static embeddings trained on all documents loaded in the engine. Training runs once and persists across restarts.
        </p>

        <button className="advanced-toggle" onClick={() => setShowAdvanced(!showAdvanced)}>
          {showAdvanced ? "▾" : "▸"} Advanced Settings
        </button>

        {showAdvanced && (
          <div className="advanced-section">
            <div className="form-row">
              <div className="form-group" style={{ maxWidth: 120 }}>
                <label>Vector Size</label>
                <input type="number" value={vectorSize} onChange={e => setVectorSize(+e.target.value)} min={50} max={300} />
              </div>
              <div className="form-group" style={{ maxWidth: 120 }}>
                <label>Window</label>
                <input type="number" value={windowSize} onChange={e => setWindowSize(+e.target.value)} min={2} max={15} />
              </div>
              <div className="form-group" style={{ maxWidth: 120 }}>
                <label>Epochs</label>
                <input type="number" value={w2vEpochs} onChange={e => setW2vEpochs(+e.target.value)} min={5} max={1000} />
              </div>
            </div>
          </div>
        )}

        <button className="btn btn-primary" onClick={handleTrainFromEngine}
          disabled={initLoading} style={{ marginTop: 8 }}>
          {initLoading ? <><span className="spinner" /> Training on all engine documents...</> : "Train Word2Vec"}
        </button>

        <LogViewer active={initLoading} />
      </div>

      {error && <StatusMessage type="err" message={error} />}
    </div>
  );
}
