import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { api } from "../lib/api";
import type { CaseStatus } from "../lib/api";

export function CaseStatusPage() {
  const { caseId } = useParams();
  const id = caseId || "";
  const nav = useNavigate();

  const [data, setData] = useState<CaseStatus | null>(null);
  const [err, setErr] = useState<string | null>(null);

  async function load() {
    setErr(null);
    try {
      const res = await api.getCaseStatus(id);
      setData(res);
    } catch (e: any) {
      setErr(e?.message || "Failed to load status");
    }
  }

  useEffect(() => {
    load();
    const t = setInterval(load, 4000);
    return () => clearInterval(t);
  }, [id]);

  return (
    <div className="bf-page bf-page--wide">
      <div className="bf-page-header">
        <div>
          <h1 className="bf-page-title">Case Status</h1>
          <p className="bf-page-subtitle">Track pipeline progress and jump to the next step.</p>
        </div>
        <div className="bf-spacer" />
        <div className="bf-toolbar">
          <button className="btn secondary" onClick={load}>
            Refresh
          </button>
          <button
            className="btn primary"
            onClick={() => nav(`/cases/${encodeURIComponent(id)}/landmarks`)}
          >
            Landmark Tool
          </button>
        </div>
      </div>

      <div className="card">
        <div className="muted muted--tight">
          Case: <strong>{id}</strong>
        </div>

        {err && <div className="error">{err}</div>}
        {!data ? (
          <div className="muted">Loading status...</div>
        ) : (
          <>
            <div className="bf-summary-grid">
              <div className="bf-summary-item">
                <span className="bf-summary-label">Status</span>
                <span className="bf-summary-value">{data.case.status}</span>
              </div>
              <div className="bf-summary-item">
                <span className="bf-summary-label">Current Step</span>
                <span className="bf-summary-value">{data.case.current_step || "-"}</span>
              </div>
              <div className="bf-summary-item">
                <span className="bf-summary-label">Last Updated</span>
                <span className="bf-summary-value">
                  {new Date(data.case.updated_at).toLocaleString()}
                </span>
              </div>
            </div>

            <table className="table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Step</th>
                  <th>Status</th>
                  <th>Started</th>
                  <th>Finished</th>
                </tr>
              </thead>
              <tbody>
                {data.steps.map((s) => (
                  <tr key={s.step_name}>
                    <td>{s.step_order}</td>
                    <td>{s.step_name}</td>
                    <td>
                      <span className={`tag ${s.status}`}>{s.status}</span>
                    </td>
                    <td>{s.started_at ? new Date(s.started_at).toLocaleString() : "-"}</td>
                    <td>{s.finished_at ? new Date(s.finished_at).toLocaleString() : "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table>

            <div className="muted">
              Step3 output (classification.json) display can be added next (optional for first demo).
            </div>
          </>
        )}
      </div>
    </div>
  );
}
