import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { api } from "../lib/api";

export function CaseLoaderPage() {
  const [caseId, setCaseId] = useState("");
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const nav = useNavigate();

  const onLoad = async () => {
    setErr(null);
    setLoading(true);
    try {
      await api.getCaseStatus(caseId.trim());
      nav(`/cases/${encodeURIComponent(caseId.trim())}/status`);
    } catch (e: any) {
      setErr(e?.message || "Failed to load case");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="bf-page">
      <div className="bf-page-header">
        <div>
          <h1 className="bf-page-title">Load A Case</h1>
          <p className="bf-page-subtitle">
            Enter a case ID to view status or resume landmark capture.
          </p>
        </div>
        <div className="bf-spacer" />
        <div className="bf-toolbar">
          <button className="btn primary" disabled={!caseId.trim() || loading} onClick={onLoad}>
            {loading ? "Loading..." : "Load Case"}
          </button>
        </div>
      </div>

      <div className="card">
        <p className="muted muted--tight">
          To create a new case and upload an X-ray, use "Start A Case" in the header.
        </p>

        <div className="row gap">
          <input
            value={caseId}
            onChange={(e) => setCaseId(e.target.value)}
            placeholder="case-20260122-..."
            className="input"
          />
          <button className="btn secondary" disabled={!caseId.trim() || loading} onClick={onLoad}>
            {loading ? "Loading..." : "Load Case"}
          </button>
        </div>

        {err && <div className="error">{err}</div>}
      </div>
    </div>
  );
}
