"use client";

// Client island: triggers the agent-driven diligence pipeline for a project and
// renders live phase-by-phase progress streamed over /api/events/stream as
// `mines_diligence` events. On completion, links into the dashboard space.

import { useCallback, useEffect, useRef, useState } from "react";

const PHASE_LABEL = {
  start: "Starting",
  extract: "Extracting facts (LLM)",
  valuation: "Valuation",
  narrative: "Authoring narrative (LLM)",
  package: "Investor presentation",
  reports: "Reports",
  complete: "Complete",
};

const STATUS_COLOR = { running: "#68707b", done: "#2A5C45", warn: "#c2452a" };

function IconSpark() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
      <path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5L18 18M18 6l-2.5 2.5M8.5 15.5L6 18" strokeLinecap="round" />
    </svg>
  );
}

export default function DiligenceButton({ minesProjectId }) {
  const [running, setRunning] = useState(false);
  const [steps, setSteps] = useState([]);
  const [artifacts, setArtifacts] = useState([]);
  const [spaceName, setSpaceName] = useState(null);
  const [error, setError] = useState(null);
  const esRef = useRef(null);
  const runIdRef = useRef(null);

  const closeStream = useCallback(() => {
    if (esRef.current) { try { esRef.current.close(); } catch {} esRef.current = null; }
  }, []);

  const attachStream = useCallback(() => {
    closeStream();
    const es = new EventSource("/api/events/stream");
    esRef.current = es;
    es.addEventListener("mines_diligence", (ev) => {
      let d;
      try { d = JSON.parse(ev.data); } catch { return; }
      if (d.project_id !== minesProjectId) return;
      if (runIdRef.current && d.run_id && d.run_id !== runIdRef.current) return;
      setSteps((prev) => [...prev, { phase: d.phase, status: d.status, message: d.message }]);
      if (d.phase === "complete") {
        setArtifacts(Array.isArray(d.artifacts) ? d.artifacts : []);
        setSpaceName(d.space_name || null);
        setRunning(false);
        closeStream();
      }
    });
    es.onerror = () => { /* browser auto-reconnects; keep UI as-is */ };
  }, [minesProjectId, closeStream]);

  // If a run is already in flight (e.g. page reloaded), reattach to it.
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch(`/api/mines/projects/${minesProjectId}/diligence`, { cache: "no-store" });
        const json = await res.json().catch(() => ({}));
        if (!cancelled && json?.running) {
          runIdRef.current = json.run_id || null;
          setRunning(true);
          setSteps([{ phase: "start", status: "running", message: "Resuming in-progress run…" }]);
          attachStream();
        }
      } catch { /* ignore */ }
    })();
    return () => { cancelled = true; closeStream(); };
  }, [minesProjectId, attachStream, closeStream]);

  const start = useCallback(async () => {
    setError(null);
    setArtifacts([]);
    setSteps([]);
    setRunning(true);
    try {
      const res = await fetch(`/api/mines/projects/${minesProjectId}/diligence`, { method: "POST" });
      const json = await res.json().catch(() => ({}));
      if (res.status === 202 || json?.status === "started") {
        runIdRef.current = json.run_id || null;
        attachStream();
      } else if (res.status === 409 || json?.status === "already_running") {
        runIdRef.current = json.run_id || null;
        setSteps([{ phase: "start", status: "running", message: "A run is already in progress — following it." }]);
        attachStream();
      } else {
        setRunning(false);
        setError(json?.reason || json?.error || "Could not start diligence run.");
      }
    } catch (err) {
      setRunning(false);
      setError(err?.message || "Network error starting diligence run.");
    }
  }, [minesProjectId, attachStream]);

  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 10 }}>
      <button
        type="button"
        onClick={start}
        disabled={running}
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 8,
          padding: "10px 18px",
          borderRadius: 10,
          border: "none",
          background: running ? "#9aa0aa" : "#2A5C45",
          color: "#fff",
          fontSize: 13,
          fontWeight: 800,
          letterSpacing: "-.01em",
          cursor: running ? "wait" : "pointer",
          boxShadow: running ? "none" : "0 6px 18px rgba(42,92,69,.28)",
        }}
      >
        <IconSpark />
        {running ? "Generating…" : "Generate diligence package"}
      </button>

      {error && (
        <p aria-live="polite" style={{ margin: 0, fontSize: 12, color: "#c2452a", fontWeight: 700, maxWidth: 340, textAlign: "right" }}>
          {error}
        </p>
      )}

      {steps.length > 0 && (
        <div
          style={{
            width: 360,
            maxWidth: "100%",
            border: "1px solid rgba(17,19,24,.10)",
            borderRadius: 12,
            background: "#fff",
            padding: "10px 12px",
            boxShadow: "0 10px 30px rgba(17,19,24,.07)",
          }}
        >
          <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 6 }}>
            {steps.map((s, i) => (
              <li key={i} style={{ display: "flex", gap: 8, alignItems: "baseline", fontSize: 12 }}>
                <span style={{ fontFamily: "ui-monospace, Menlo, monospace", fontSize: 9.5, fontWeight: 800, letterSpacing: ".08em", textTransform: "uppercase", color: STATUS_COLOR[s.status] || "#8a8f99", minWidth: 132 }}>
                  {PHASE_LABEL[s.phase] || s.phase}
                </span>
                <span style={{ color: "#313740", lineHeight: 1.45 }}>{s.message}</span>
              </li>
            ))}
          </ul>

          {artifacts.length > 0 && (
            <div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid rgba(17,19,24,.08)" }}>
              <span style={{ display: "block", fontSize: 10, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: "#8a8f99", marginBottom: 6 }}>
                {artifacts.length} artifact{artifacts.length === 1 ? "" : "s"}{spaceName ? ` in “${spaceName}”` : ""}
              </span>
              <ul style={{ listStyle: "none", margin: "0 0 10px", padding: 0, display: "flex", flexDirection: "column", gap: 3 }}>
                {artifacts.map((a) => (
                  <li key={a.id} style={{ fontSize: 12, color: "#111318", display: "flex", gap: 6, alignItems: "baseline" }}>
                    <span style={{ width: 4, height: 4, borderRadius: 4, background: "#c2452a", flexShrink: 0, transform: "translateY(-2px)" }} />
                    {a.title}
                  </li>
                ))}
              </ul>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                <a href="/" style={{ fontSize: 12, fontWeight: 700, color: "#2A5C45", textDecoration: "none" }}>Open dashboard space →</a>
                <a href={`/mines/${minesProjectId}/results`} style={{ fontSize: 12, fontWeight: 700, color: "#2A5C45", textDecoration: "none" }}>Open diligence results →</a>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
