import { useEffect, useState, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { fetchCase, getBraceOutputs, getDownloadUrl, generateBrace } from "../api/braceflowApi";
import type { CaseRecord, BraceOutputsResponse } from "../api/braceflowApi";

// Helper function to determine curve severity from Cobb angle
function getCurveSeverity(angle: number): string {
  if (angle < 10) return "Normal";
  if (angle < 25) return "Mild";
  if (angle < 40) return "Moderate";
  if (angle < 50) return "Severe";
  return "Very Severe";
}

function getCurveSeverityClass(angle: number): string {
  if (angle < 10) return "severity-normal";
  if (angle < 25) return "severity-mild";
  if (angle < 40) return "severity-moderate";
  return "severity-severe";
}

// Helper function to get Rigo type description
function getRigoDescription(rigoType: string): string {
  const descriptions: Record<string, string> = {
    'A1': 'Three-curve pattern with lumbar modifier',
    'A2': 'Three-curve pattern with thoracolumbar modifier', 
    'A3': 'Three-curve pattern balanced',
    'B1': 'Four-curve pattern with lumbar modifier',
    'B2': 'Four-curve pattern with double thoracic',
    'C1': 'Non-3 non-4 with thoracolumbar curve',
    'C2': 'Non-3 non-4 with lumbar curve',
    'E1': 'Single thoracic curve',
    'E2': 'Single thoracolumbar curve',
  };
  return descriptions[rigoType] || `Rigo type ${rigoType}`;
}

// Helper function to format file size
function formatFileSize(bytes: number): string {
  if (!bytes || bytes === 0) return '';
  const units = ['B', 'KB', 'MB', 'GB'];
  let size = bytes;
  let unitIndex = 0;
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  return `${size.toFixed(1)} ${units[unitIndex]}`;
}

export default function CaseDetailPage() {
  const { caseId } = useParams<{ caseId: string }>();
  const nav = useNavigate();
  
  const [caseData, setCaseData] = useState<CaseRecord | null>(null);
  const [outputs, setOutputs] = useState<BraceOutputsResponse | null>(null);
  const [xrayUrl, setXrayUrl] = useState<string | null>(null);
  const [xrayError, setXrayError] = useState(false);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);
  const [generating, setGenerating] = useState(false);
  const [genError, setGenError] = useState<string | null>(null);

  const loadCaseData = useCallback(async () => {
    if (!caseId) return;
    
    setLoading(true);
    setErr(null);
    setXrayError(false);
    try {
      // Fetch case data first
      const caseResult = await fetchCase(caseId);
      setCaseData(caseResult);
      
      // Fetch outputs and X-ray URL in parallel (don't fail if they error)
      const [outputsResult, xrayResult] = await Promise.all([
        getBraceOutputs(caseId).catch(() => null),
        getDownloadUrl(caseId, "xray").catch(() => null)
      ]);
      
      setOutputs(outputsResult);
      setXrayUrl(xrayResult?.url || null);
    } catch (e: any) {
      setErr(e?.message || "Failed to load case");
    } finally {
      setLoading(false);
    }
  }, [caseId]);

  useEffect(() => {
    loadCaseData();
  }, [loadCaseData]);

  // Handle generate brace button
  const handleGenerateBrace = async () => {
    if (!caseId) return;
    setGenerating(true);
    setGenError(null);
    try {
      await generateBrace(caseId, { experiment: "experiment_3" });
      // Reload case data after generation
      await loadCaseData();
    } catch (e: any) {
      setGenError(e?.message || "Failed to generate brace");
    } finally {
      setGenerating(false);
    }
  };

  // Find the visualization PNG from outputs
  const vizUrl = outputs?.outputs?.find(o => 
    o.filename.endsWith('.png') && !o.filename.includes('ap')
  )?.url;
  
  // Check if brace has been generated
  const hasBrace = caseData?.status === "brace_generated" || 
                   caseData?.status === "completed" ||
                   caseData?.analysis_result?.cobb_angles;
  
  const isProcessing = caseData?.status === "processing_brace" || generating;

  if (loading) {
    return (
      <div className="bf-page">
        <div className="muted">Loading case...</div>
      </div>
    );
  }

  if (err || !caseData) {
    return (
      <div className="bf-page">
        <div className="error">{err || "Case not found"}</div>
        <button className="btn secondary" onClick={() => nav("/")}>Back to Cases</button>
      </div>
    );
  }

  return (
    <div className="bf-page bf-page--wide">
      {/* Header with case ID */}
      <div className="bf-case-header">
        <div className="bf-case-header-left">
          <button className="bf-back-btn" onClick={() => nav("/")}>
            ← Back
          </button>
          <h1 className="bf-case-title">{caseId}</h1>
          <span className={`bf-case-status bf-case-status--${caseData.status}`}>
            {caseData.status?.replace(/_/g, ' ')}
          </span>
        </div>
      </div>

      {/* X-ray Image Section */}
      <div className="bf-case-content">
        <div className="bf-case-xray-section">
          <h2 className="bf-section-title">Original X-ray</h2>
          <div className="bf-xray-container">
            {xrayUrl && !xrayError ? (
              <img 
                src={xrayUrl} 
                alt="X-ray" 
                className="bf-xray-image" 
                onError={() => setXrayError(true)}
              />
            ) : (
              <div className="bf-xray-placeholder">
                <span>{xrayError ? "Failed to load X-ray" : "X-ray not available yet"}</span>
              </div>
            )}
          </div>

          {/* Processing State */}
          {isProcessing && (
            <div className="bf-processing-indicator">
              <div className="bf-processing-spinner"></div>
              <span>Processing... Generating brace from X-ray analysis</span>
            </div>
          )}

          {/* Generate Button - show if X-ray exists but brace not generated */}
          {xrayUrl && !hasBrace && !isProcessing && (
            <div className="bf-generate-section">
              <button 
                className="btn primary bf-generate-btn" 
                onClick={handleGenerateBrace}
                disabled={generating}
              >
                {generating ? "Generating..." : "Generate Brace"}
              </button>
              {genError && <div className="error">{genError}</div>}
            </div>
          )}
        </div>

        {/* Visualization Section */}
        {vizUrl && (
          <div className="bf-case-viz-section">
            <h2 className="bf-section-title">Spine Analysis Visualization</h2>
            <div className="bf-viz-container">
              <img src={vizUrl} alt="Analysis visualization" className="bf-viz-image" />
            </div>
            
            {/* Detailed Analysis Under Visualization */}
            {caseData.analysis_result && (
              <div className="bf-detailed-analysis">
                {/* Cobb Angles with Severity */}
                {caseData.analysis_result.cobb_angles && (
                  <div className="bf-analysis-block">
                    <h3>Cobb Angle Measurements</h3>
                    <div className="bf-cobb-detailed">
                      {caseData.analysis_result.cobb_angles.PT !== undefined && (
                        <div className="bf-cobb-row">
                          <span className="bf-cobb-name">PT (Proximal Thoracic)</span>
                          <span className={`bf-cobb-value ${getCurveSeverityClass(caseData.analysis_result.cobb_angles.PT)}`}>
                            {caseData.analysis_result.cobb_angles.PT.toFixed(1)}°
                          </span>
                          <span className="bf-cobb-severity">{getCurveSeverity(caseData.analysis_result.cobb_angles.PT)}</span>
                        </div>
                      )}
                      {caseData.analysis_result.cobb_angles.MT !== undefined && (
                        <div className="bf-cobb-row">
                          <span className="bf-cobb-name">MT (Main Thoracic)</span>
                          <span className={`bf-cobb-value ${getCurveSeverityClass(caseData.analysis_result.cobb_angles.MT)}`}>
                            {caseData.analysis_result.cobb_angles.MT.toFixed(1)}°
                          </span>
                          <span className="bf-cobb-severity">{getCurveSeverity(caseData.analysis_result.cobb_angles.MT)}</span>
                        </div>
                      )}
                      {caseData.analysis_result.cobb_angles.TL !== undefined && (
                        <div className="bf-cobb-row">
                          <span className="bf-cobb-name">TL (Thoracolumbar/Lumbar)</span>
                          <span className={`bf-cobb-value ${getCurveSeverityClass(caseData.analysis_result.cobb_angles.TL)}`}>
                            {caseData.analysis_result.cobb_angles.TL.toFixed(1)}°
                          </span>
                          <span className="bf-cobb-severity">{getCurveSeverity(caseData.analysis_result.cobb_angles.TL)}</span>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Classification Summary */}
                <div className="bf-analysis-block">
                  <h3>Classification</h3>
                  <div className="bf-classification-grid">
                    {caseData.analysis_result.curve_type && (
                      <div className="bf-classification-item">
                        <span className="bf-classification-label">Curve Pattern</span>
                        <span className="bf-classification-value bf-curve-badge">
                          {caseData.analysis_result.curve_type}-Curve
                        </span>
                        <span className="bf-classification-desc">
                          {caseData.analysis_result.curve_type === 'S' ? 'Double curve (thoracic + lumbar)' : 
                           caseData.analysis_result.curve_type === 'C' ? 'Single curve pattern' : 
                           'Curve pattern identified'}
                        </span>
                      </div>
                    )}
                    {caseData.analysis_result.rigo_classification && (
                      <div className="bf-classification-item">
                        <span className="bf-classification-label">Rigo-Chêneau Type</span>
                        <span className="bf-classification-value bf-rigo-badge">
                          {caseData.analysis_result.rigo_classification.type}
                        </span>
                        <span className="bf-classification-desc">
                          {caseData.analysis_result.rigo_classification.description || getRigoDescription(caseData.analysis_result.rigo_classification.type)}
                        </span>
                      </div>
                    )}
                  </div>
                </div>

                {/* Brace Generation Details */}
                <div className="bf-analysis-block">
                  <h3>Brace Generation Details</h3>
                  <div className="bf-brace-details-grid">
                    {caseData.analysis_result.vertebrae_detected && (
                      <div className="bf-detail-item">
                        <span className="bf-detail-label">Vertebrae Detected</span>
                        <span className="bf-detail-value">{caseData.analysis_result.vertebrae_detected}</span>
                      </div>
                    )}
                    {caseData.analysis_result.mesh_info && (
                      <>
                        <div className="bf-detail-item">
                          <span className="bf-detail-label">Mesh Vertices</span>
                          <span className="bf-detail-value">{caseData.analysis_result.mesh_info.vertices?.toLocaleString()}</span>
                        </div>
                        <div className="bf-detail-item">
                          <span className="bf-detail-label">Mesh Faces</span>
                          <span className="bf-detail-value">{caseData.analysis_result.mesh_info.faces?.toLocaleString()}</span>
                        </div>
                      </>
                    )}
                    {caseData.analysis_result.processing_time_ms && (
                      <div className="bf-detail-item">
                        <span className="bf-detail-label">Processing Time</span>
                        <span className="bf-detail-value">{(caseData.analysis_result.processing_time_ms / 1000).toFixed(2)}s</span>
                      </div>
                    )}
                  </div>
                </div>

                {/* Deformation/Pressure Zones */}
                {caseData.analysis_result.deformation_report?.zones && caseData.analysis_result.deformation_report.zones.length > 0 && (
                  <div className="bf-analysis-block">
                    <h3>Brace Pressure Zones</h3>
                    <p className="bf-block-desc">
                      Based on the Cobb angles and Rigo classification, the following pressure modifications were applied to the brace:
                    </p>
                    <div className="bf-pressure-zones">
                      {caseData.analysis_result.deformation_report.zones.map((zone, idx) => (
                        <div key={idx} className={`bf-zone-item ${zone.deform_mm < 0 ? 'bf-zone-pressure' : 'bf-zone-relief'}`}>
                          <div className="bf-zone-header">
                            <span className="bf-zone-name">{zone.zone}</span>
                            <span className={`bf-zone-value ${zone.deform_mm < 0 ? 'bf-pressure' : 'bf-relief'}`}>
                              {zone.deform_mm > 0 ? '+' : ''}{zone.deform_mm.toFixed(1)} mm
                            </span>
                          </div>
                          <span className="bf-zone-reason">{zone.reason}</span>
                        </div>
                      ))}
                    </div>
                    {caseData.analysis_result.deformation_report.patch_grid && (
                      <p className="bf-patch-info">
                        Patch Grid: {caseData.analysis_result.deformation_report.patch_grid}
                      </p>
                    )}
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Downloads */}
        {outputs?.outputs && outputs.outputs.length > 0 && (
          <div className="bf-case-downloads">
            <h2 className="bf-section-title">Generated Brace Files</h2>
            <div className="bf-downloads-grid">
              {outputs.outputs
                .filter(o => o.type === 'stl' || o.type === 'obj')
                .map(o => (
                  <div key={o.filename} className="bf-download-card">
                    <div className="bf-download-card-icon">
                      {o.type === 'stl' ? '🧊' : '📦'}
                    </div>
                    <div className="bf-download-card-info">
                      <span className="bf-download-card-name">{o.filename}</span>
                      <span className="bf-download-card-size">{formatFileSize(o.size)}</span>
                    </div>
                    <div className="bf-download-card-actions">
                      <a 
                        href={o.url} 
                        className="bf-action-btn bf-action-download"
                        download={o.filename}
                        title="Download file"
                      >
                        Download
                      </a>
                    </div>
                  </div>
                ))}
            </div>
            <p className="bf-download-hint">STL files can be 3D printed or opened in any 3D modeling software.</p>
          </div>
        )}
      </div>
    </div>
  );
}
