import { useState } from "react";
import { rigoApi, type AnalysisResult } from "../../api/rigoApi";

interface AnalysisResultsProps {
  data: AnalysisResult | null;
  modelUrl: string | null;
  isLoading: boolean;
  error: string | null;
  onModelUpdate: (url: string) => void;
}

export default function AnalysisResults({ data, modelUrl, isLoading, error, onModelUpdate }: AnalysisResultsProps) {
  const [showPadsOnly, setShowPadsOnly] = useState(true);
  const [isRegenerating, setIsRegenerating] = useState(false);

  const handleTogglePadsOnly = async () => {
    if (!data || !onModelUpdate) return;

    setIsRegenerating(true);
    const newShowPadsOnly = !showPadsOnly;

    try {
      const result = await rigoApi.regenerate({
        pressure_pad_level: data.apex,
        pressure_pad_depth: data.cobb_angle > 40 ? "aggressive" : data.cobb_angle > 20 ? "moderate" : "standard",
        expansion_window_side: data.pelvic_tilt === "Left" ? "right" : "left",
        lumbar_support: true,
        include_shell: !newShowPadsOnly,
      });

      if (result.success) {
        // Construct full URL from relative path
        const fullUrl = result.model_url.startsWith("http")
          ? result.model_url
          : `${rigoApi.getBaseUrl()}${result.model_url}`;
        onModelUpdate(fullUrl);
        setShowPadsOnly(newShowPadsOnly);
      }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Unknown error";
      alert(`Failed to regenerate: ${message}`);
    } finally {
      setIsRegenerating(false);
    }
  };

  const handleDownloadGLB = () => {
    if (modelUrl) {
      const link = document.createElement("a");
      link.href = modelUrl;
      link.download = `brace_${data?.apex || "custom"}.glb`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      alert("3D model generation requires Blender. The placeholder model is for visualization only.");
    }
  };

  const handleDownloadSTL = () => {
    if (modelUrl) {
      const stlUrl = modelUrl.replace(".glb", ".stl");
      const link = document.createElement("a");
      link.href = stlUrl;
      link.download = `brace_${data?.apex || "custom"}.stl`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      alert("3D model generation requires Blender. The placeholder model is for visualization only.");
    }
  };

  if (error) {
    return (
      <div className="rigo-analysis-error">
        <div className="rigo-analysis-card" style={{ borderColor: "#ef4444", background: "rgba(239, 68, 68, 0.1)" }}>
          <div className="rigo-analysis-label" style={{ color: "#f87171" }}>
            Error
          </div>
          <div className="rigo-analysis-value" style={{ color: "#f87171", fontSize: "1rem" }}>
            {error}
          </div>
          <div className="rigo-analysis-description">Please try uploading a clearer X-ray image.</div>
        </div>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="rigo-analysis-loading">
        <div className="rigo-analysis-card">
          <div className="rigo-loading-skeleton" style={{ height: "20px", marginBottom: "8px", width: "40%" }}></div>
          <div className="rigo-loading-skeleton" style={{ height: "36px", width: "60%" }}></div>
        </div>
        <div className="rigo-analysis-grid">
          <div className="rigo-analysis-card">
            <div className="rigo-loading-skeleton" style={{ height: "16px", marginBottom: "8px", width: "50%" }}></div>
            <div className="rigo-loading-skeleton" style={{ height: "28px", width: "40%" }}></div>
          </div>
          <div className="rigo-analysis-card">
            <div className="rigo-loading-skeleton" style={{ height: "16px", marginBottom: "8px", width: "50%" }}></div>
            <div className="rigo-loading-skeleton" style={{ height: "28px", width: "40%" }}></div>
          </div>
        </div>
        <p style={{ textAlign: "center", color: "#64748b", marginTop: "24px", fontSize: "0.875rem" }}>
          <span className="rigo-spinner" style={{ display: "inline-block", marginRight: "8px", verticalAlign: "middle" }}></span>
          Analyzing X-ray with Claude Vision...
        </p>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="rigo-analysis-empty">
        <div style={{ textAlign: "center", padding: "32px", color: "#64748b" }}>
          <svg
            width="64"
            height="64"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1"
            style={{ margin: "0 auto 16px", opacity: 0.3 }}
          >
            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
            <polyline points="14 2 14 8 20 8" />
            <line x1="16" y1="13" x2="8" y2="13" />
            <line x1="16" y1="17" x2="8" y2="17" />
            <polyline points="10 9 9 9 8 9" />
          </svg>
          <p>Upload an EOS X-ray to see the analysis results here.</p>
        </div>
      </div>
    );
  }

  // Determine severity based on Cobb angle
  const getSeverity = (angle: number) => {
    if (angle < 20) return { level: "Mild", class: "success" };
    if (angle < 40) return { level: "Moderate", class: "highlight" };
    return { level: "Severe", class: "warning" };
  };

  const severity = getSeverity(data.cobb_angle);

  return (
    <div className="rigo-analysis-results">
      {/* Diagnosis */}
      <div className="rigo-analysis-card">
        <div className="rigo-analysis-label">Diagnosis</div>
        <div className="rigo-analysis-value highlight">
          {data.pattern === "Type_3C" ? "Right Thoracic Scoliosis" : data.pattern}
        </div>
        <div className="rigo-analysis-description">
          Rigo-Cheneau Classification: <strong>Type 3C</strong>
        </div>
      </div>

      {/* Thoracic Measurements */}
      <div className="rigo-analysis-grid">
        <div className="rigo-analysis-card">
          <div className="rigo-analysis-label">Thoracic Cobb</div>
          <div className={`rigo-analysis-value ${severity.class}`}>{data.cobb_angle}°</div>
          <div className="rigo-analysis-description">{severity.level} curve</div>
        </div>

        <div className="rigo-analysis-card">
          <div className="rigo-analysis-label">Apex Vertebra</div>
          <div className="rigo-analysis-value">{data.apex}</div>
          <div className="rigo-analysis-description">Curve apex location</div>
        </div>
      </div>

      {/* Thoracic Convexity & Lumbar Cobb */}
      <div className="rigo-analysis-grid">
        <div className="rigo-analysis-card">
          <div className="rigo-analysis-label">Thoracic Convexity</div>
          <div className="rigo-analysis-value">{data.thoracic_convexity || "Right"}</div>
          <div className="rigo-analysis-description">Curve direction</div>
        </div>

        <div className="rigo-analysis-card">
          <div className="rigo-analysis-label">Lumbar Cobb</div>
          <div className="rigo-analysis-value">{data.lumbar_cobb_deg != null ? `${data.lumbar_cobb_deg}°` : "—"}</div>
          <div className="rigo-analysis-description">Compensatory curve</div>
        </div>
      </div>

      {/* L4/L5 Tilt */}
      <div className="rigo-analysis-grid">
        <div className="rigo-analysis-card">
          <div className="rigo-analysis-label">L4 Tilt</div>
          <div className="rigo-analysis-value">{data.l4_tilt_deg != null ? `${data.l4_tilt_deg.toFixed(1)}°` : "—"}</div>
          <div className="rigo-analysis-description">Vertebra angle</div>
        </div>

        <div className="rigo-analysis-card">
          <div className="rigo-analysis-label">L5 Tilt</div>
          <div className="rigo-analysis-value">{data.l5_tilt_deg != null ? `${data.l5_tilt_deg.toFixed(1)}°` : "—"}</div>
          <div className="rigo-analysis-description">Vertebra angle</div>
        </div>
      </div>

      {/* Pelvic Tilt */}
      <div className="rigo-analysis-card">
        <div className="rigo-analysis-label">Pelvic Tilt</div>
        <div className="rigo-analysis-value">{data.pelvic_tilt} Side</div>
        <div className="rigo-analysis-description">Compensatory pelvic position</div>
      </div>

      {/* Brace Parameters */}
      <div
        className="rigo-analysis-card"
        style={{ marginTop: "16px", background: "rgba(59, 130, 246, 0.1)", borderColor: "#2563eb" }}
      >
        <div className="rigo-analysis-label" style={{ color: "#60a5fa" }}>
          Generated Brace Parameters
        </div>
        <div style={{ fontSize: "0.875rem", color: "#94a3b8", marginTop: "8px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "4px" }}>
            <span>Pressure Pad Position:</span>
            <strong style={{ color: "#f1f5f9" }}>{data.apex} Level</strong>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "4px" }}>
            <span>Pad Depth:</span>
            <strong style={{ color: "#f1f5f9" }}>{data.cobb_angle > 30 ? "Aggressive" : "Standard"}</strong>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <span>Expansion Window:</span>
            <strong style={{ color: "#f1f5f9" }}>{data.pelvic_tilt === "Left" ? "Right" : "Left"} Side</strong>
          </div>
        </div>
      </div>

      {/* View Toggle */}
      {modelUrl && (
        <div style={{ marginTop: "16px" }}>
          <button
            className={`rigo-btn ${showPadsOnly ? "rigo-btn-primary" : "rigo-btn-secondary"} rigo-btn-block`}
            onClick={handleTogglePadsOnly}
            disabled={isRegenerating}
            style={{ fontSize: "0.875rem" }}
          >
            {isRegenerating ? (
              <>
                <span className="rigo-spinner" style={{ width: "16px", height: "16px", marginRight: "8px" }}></span>
                Regenerating...
              </>
            ) : (
              <>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  {showPadsOnly ? (
                    <>
                      <rect x="3" y="3" width="18" height="18" rx="2" />
                      <path d="M9 9h6v6H9z" />
                    </>
                  ) : (
                    <>
                      <circle cx="12" cy="12" r="3" />
                      <path d="M12 5v2M12 17v2M5 12h2M17 12h2" />
                    </>
                  )}
                </svg>
                {showPadsOnly ? "Show Full Brace" : "Show Pads Only"}
              </>
            )}
          </button>
        </div>
      )}

      {/* Download Buttons */}
      <div style={{ display: "flex", flexDirection: "column", gap: "12px", marginTop: "16px" }}>
        <button
          className={`rigo-btn ${modelUrl ? "rigo-btn-primary" : "rigo-btn-secondary"} rigo-btn-block`}
          onClick={handleDownloadSTL}
        >
          <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="7 10 12 15 17 10" />
            <line x1="12" y1="15" x2="12" y2="3" />
          </svg>
          {modelUrl ? "Download STL (3D Print)" : "Download (Blender Required)"}
        </button>

        {modelUrl && (
          <button className="rigo-btn rigo-btn-secondary rigo-btn-block" onClick={handleDownloadGLB}>
            <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="7 10 12 15 17 10" />
              <line x1="12" y1="15" x2="12" y2="3" />
            </svg>
            Download GLB (Web Viewer)
          </button>
        )}
      </div>
    </div>
  );
}
