import { useState } from "react";

const API_BASE = import.meta.env.VITE_API_BASE;

type Props = {
  caseId?: string;
  onUploaded?: () => void; // optional callback to refresh assets/status
};

export default function XrayUploader({ caseId, onUploaded }: Props) {
  const [file, setFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

    if (!caseId) {
      setError('No caseId provided. Create or load a case first.');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      // 1️⃣ Ask backend for pre-signed upload URL
      const res = await fetch(
        `${API_BASE}/cases/${caseId}/upload-url`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ view: "ap" }) // AP view for MVP
        }
      );

      if (!res.ok) {
        throw new Error("Failed to get upload URL");
      }

      const { uploadUrl } = await res.json();

      // 2️⃣ Upload file directly to S3
      const uploadRes = await fetch(uploadUrl, {
        method: "PUT",
        body: file
      });

      if (!uploadRes.ok) {
        throw new Error("Upload to S3 failed");
      }

      // 3️⃣ Notify parent to refresh assets / status
      onUploaded?.();

    } catch (err: any) {
      console.error(err);
      setError(err.message || "Upload failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{ border: "1px dashed #ccc", padding: 16 }}>
      <h3>X-ray Upload (AP View)</h3>

      <input
        type="file"
        accept=".dcm,.jpg,.png"
        onChange={(e) => setFile(e.target.files?.[0] || null)}
      />

      <div style={{ marginTop: 8 }}>
        <button
          onClick={handleUpload}
          disabled={!file || loading}
        >
          {loading ? "Uploading..." : "Upload X-ray"}
        </button>
      </div>

      {error && (
        <div style={{ color: "red", marginTop: 8 }}>
          {error}
        </div>
      )}
    </div>
  );
}
