import { useState, useCallback } from "react";
import UploadPanel from "../components/rigo/UploadPanel";
import BraceViewer from "../components/rigo/BraceViewer";
import { rigoApi } from "../api/rigoApi";

// Helper to trigger file download
function downloadFile(url: string, filename: string) {
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

export default function ShellGenerationPage() {
  const [modelUrl, setModelUrl] = useState<string | null>(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleUpload = useCallback(async (file: File) => {
    setIsGenerating(true);
    setError(null);

    try {
      // Step 1: Analyze the X-ray
      const response = await rigoApi.analyze(file);

      if (!response.success) {
        throw new Error("Generation failed");
      }

      const analysis = response.analysis;

      // Step 2: Generate full brace with shell
      const regenResult = await rigoApi.regenerate({
        pressure_pad_level: analysis.apex,
        pressure_pad_depth: analysis.cobb_angle > 40 ? "aggressive" : analysis.cobb_angle > 20 ? "moderate" : "standard",
        expansion_window_side: analysis.pelvic_tilt === "Left" ? "right" : "left",
        lumbar_support: true,
        include_shell: true,
      });

      if (regenResult.success && regenResult.model_url) {
        const fullUrl = regenResult.model_url.startsWith("http")
          ? regenResult.model_url
          : `${rigoApi.getBaseUrl()}${regenResult.model_url}`;
        
        setModelUrl(fullUrl);

        // Auto-download the STL file
        const stlUrl = fullUrl.replace(".glb", ".stl");
        const filename = `brace_${analysis.apex}_${analysis.cobb_angle}deg.stl`;
        
        setTimeout(() => {
          downloadFile(stlUrl, filename);
        }, 1000);
      } else if (response.model_url) {
        const fullUrl = response.model_url.startsWith("http")
          ? response.model_url
          : `${rigoApi.getBaseUrl()}${response.model_url}`;
        setModelUrl(fullUrl);
      }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Generation failed. Please try again.";
      setError(message);
      console.error("Generation error:", err);
    } finally {
      setIsGenerating(false);
    }
  }, []);

  const handleReset = useCallback(() => {
    setModelUrl(null);
    setError(null);
  }, []);

  return (
    <div className="bf-page bf-page--wide">
      <div className="bf-page-header">
        <div>
          <h1 className="bf-page-title">Generate Shell</h1>
          <p className="bf-page-subtitle">
            Upload an X-ray, generate a brace shell, and preview it in 3D.
          </p>
        </div>
      </div>

      <div className="rigo-shell-page rigo-shell-page--two-col">
        {/* Left Panel - Upload */}
        <aside className="rigo-panel">
          <div className="rigo-panel-header">
            <h2 className="rigo-panel-title">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                <polyline points="17 8 12 3 7 8" />
                <line x1="12" y1="3" x2="12" y2="15" />
              </svg>
              Upload X-Ray
            </h2>
          </div>
          <div className="rigo-panel-content">
            <UploadPanel
              onUpload={handleUpload}
              isAnalyzing={isGenerating}
              onReset={handleReset}
              hasResults={!!modelUrl}
            />
            {error && (
              <div
                className="rigo-error-message"
                style={{
                  marginTop: 16,
                  padding: 12,
                  background: "rgba(255,0,0,0.1)",
                  borderRadius: 8,
                  color: "#f87171",
                }}
              >
                {error}
              </div>
            )}
          </div>
        </aside>

        {/* Main - 3D Viewer */}
        <main className="rigo-viewer-container">
          <BraceViewer modelUrl={modelUrl} isLoading={isGenerating} />
        </main>
      </div>
    </div>
  );
}
