import { useMemo, useState } from "react";
import { useParams } from "react-router-dom";
import { api } from "../lib/api";

/**
 * UI flow:
 * 1) If no caseId: create a new case
 * 2) Request presigned upload URL for AP view
 * 3) PUT file to S3 using uploadUrl
 * 4) Upload only; generation happens on demand
 *
 * Notes:
 * - Generation is triggered manually from the case page
 * - For PoC we upload only "ap". You can add "lat" later.
 */
export default function XrayUploadPage({
  caseId: propCaseId,
  onCaseCreated,
  onUploaded,
}: {
  caseId?: string;
  onCaseCreated?: (caseId: string) => void;
  onUploaded?: (info: { caseId: string; s3Key: string }) => void;
}) {
  // Support both prop and URL param for caseId
  const { caseId: paramCaseId } = useParams();
  const caseId = propCaseId || paramCaseId;
  const [file, setFile] = useState<File | null>(null);
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);

  const canUpload = useMemo(() => !!file && !busy, [file, busy]);

  async function ensureCase(): Promise<string> {
    if (caseId?.trim()) return caseId.trim();

    // Create case
    const createdAny: any = await api.createCase({ notes: "UI-created case" });
    const newId = createdAny.caseId || createdAny.case?.case_id || createdAny.id; // tolerate different shapes
    if (!newId) throw new Error("createCase response did not include caseId");

    onCaseCreated?.(newId);
    return newId;
  }

  async function onUpload() {
    if (!file) return;

    setBusy(true);
    setMsg(null);

    try {
      const id = await ensureCase();

      // 1) Presigned PUT URL
      const presign = await api.getUploadUrl(id, {
        view: "ap",
        // optional but helpful to pass through
        contentType: file.type || "application/octet-stream",
        filename: file.name,
      } as any);

      const uploadUrl: string = presign.uploadUrl;
      const s3Key: string | undefined = (presign as any).s3Key || (presign as any).key;

      if (!uploadUrl || !s3Key) throw new Error("getUploadUrl response missing uploadUrl/key");

      // 2) Upload file bytes to S3
      const putRes = await fetch(uploadUrl, {
        method: "PUT",
        headers: {
          // Important: if your presign expects a content-type, keep it consistent.
          "Content-Type": file.type || "application/octet-stream",
        },
        body: file,
      });

      if (!putRes.ok) {
        const text = await putRes.text().catch(() => "");
        throw new Error(`S3 upload failed (${putRes.status}). ${text}`);
      }

      setMsg("Uploaded OK. Open the case and click Generate Brace to run the pipeline.");

      onUploaded?.({ caseId: id, s3Key });
    } catch (e: any) {
      setMsg(e?.message || "Upload failed");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="bf-page bf-page--wide">
      <div className="bf-page-header">
        <div>
          <h1 className="bf-page-title">Start A Case</h1>
          <p className="bf-page-subtitle">
            Upload an AP X-ray. We will create a case automatically if needed.
          </p>
        </div>
      </div>

      <div className="card">
        <div className="muted muted--tight">
          Case: <strong>{caseId ?? "New (created on upload)"}</strong>
        </div>

        <div className="row gap bf-mt-12">
          <input
            type="file"
            accept=".dcm,image/*"
            onChange={(e) => setFile(e.target.files?.[0] ?? null)}
          />
          <button className="btn secondary" disabled={!canUpload} onClick={onUpload}>
            {busy ? "Uploading..." : "Upload X-ray"}
          </button>
        </div>

        {msg && (
          <div className="notice bf-mt-12">
            {msg}
          </div>
        )}
      </div>
    </div>
  );
}
