/**
 * Stage 2: Spine Analysis
 * Shows Cobb angles, Rigo classification, and curve analysis
 */
import type { LandmarksResult, RecalculationResult } from '../../api/braceflowApi';

type Props = {
  landmarksData: LandmarksResult | null;
  analysisData: RecalculationResult | null;
  isLoading: boolean;
  onRecalculate: () => Promise<void>;
  onContinue: () => void;
};

// Helper functions
function getSeverityClass(severity: string): string {
  switch (severity?.toLowerCase()) {
    case 'normal':
      return 'severity-normal';
    case 'mild':
      return 'severity-mild';
    case 'moderate':
      return 'severity-moderate';
    case 'severe':
    case 'very severe':
      return 'severity-severe';
    default:
      return '';
  }
}

function getRigoDescription(type: string): string {
  const descriptions: Record<string, string> = {
    A1: 'Three-curve pattern with lumbar modifier - Main thoracic curve with compensatory lumbar',
    A2: 'Three-curve pattern with thoracolumbar modifier - Thoracolumbar prominence',
    A3: 'Three-curve pattern balanced - Balanced thoracic and lumbar curves',
    B1: 'Four-curve pattern with lumbar modifier - Double thoracic with lumbar',
    B2: 'Four-curve pattern with double thoracic - Primary double thoracic',
    C1: 'Non-3 non-4 with thoracolumbar curve - Single thoracolumbar focus',
    C2: 'Non-3 non-4 with lumbar curve - Single lumbar focus',
    E1: 'Single thoracic curve - Primary thoracic scoliosis',
    E2: 'Single thoracolumbar curve - Primary thoracolumbar scoliosis',
  };
  return descriptions[type] || `Rigo-Chêneau classification type ${type}`;
}

function getTreatmentRecommendation(maxCobb: number): {
  recommendation: string;
  urgency: string;
} {
  if (maxCobb < 10) {
    return {
      recommendation: 'Observation only - no treatment required',
      urgency: 'routine',
    };
  } else if (maxCobb < 25) {
    return {
      recommendation: 'Physical therapy and observation recommended',
      urgency: 'standard',
    };
  } else if (maxCobb < 40) {
    return {
      recommendation: 'Brace treatment indicated - custom brace recommended',
      urgency: 'priority',
    };
  } else if (maxCobb < 50) {
    return {
      recommendation: 'Aggressive bracing required - consider surgical consultation',
      urgency: 'high',
    };
  } else {
    return {
      recommendation: 'Surgical consultation recommended',
      urgency: 'urgent',
    };
  }
}

export default function SpineAnalysisStage({
  landmarksData,
  analysisData,
  isLoading,
  onRecalculate,
  onContinue,
}: Props) {
  // Use recalculated data if available, otherwise use initial detection data
  const cobbAngles = analysisData?.cobb_angles || landmarksData?.cobb_angles;
  const rigoClass = analysisData?.rigo_classification || landmarksData?.rigo_classification;
  const curveType = analysisData?.curve_type || landmarksData?.curve_type;

  if (!landmarksData) {
    return (
      <div className="pipeline-stage analysis-stage">
        <div className="stage-header">
          <h2>Stage 2: Spine Analysis</h2>
          <div className="stage-status">
            <span className="status-badge status-pending">Pending</span>
          </div>
        </div>
        <div className="stage-content">
          <div className="stage-empty">
            <p>Complete Stage 1 (Landmark Detection) first.</p>
          </div>
        </div>
      </div>
    );
  }

  const maxCobb = cobbAngles ? Math.max(cobbAngles.PT, cobbAngles.MT, cobbAngles.TL) : 0;
  const treatment = getTreatmentRecommendation(maxCobb);

  return (
    <div className="pipeline-stage analysis-stage">
      <div className="stage-header">
        <h2>Stage 2: Spine Analysis</h2>
        <div className="stage-status">
          {isLoading ? (
            <span className="status-badge status-processing">Recalculating...</span>
          ) : (
            <span className="status-badge status-complete">Analyzed</span>
          )}
        </div>
      </div>

      <div className="stage-content">
        {/* Cobb Angles Panel */}
        <div className="analysis-panel cobb-panel">
          <h3>Cobb Angle Measurements</h3>
          {cobbAngles && (
            <div className="cobb-grid">
              <div className={`cobb-card ${getSeverityClass(cobbAngles.PT_severity)}`}>
                <div className="cobb-region">PT</div>
                <div className="cobb-label">Proximal Thoracic</div>
                <div className="cobb-value">{cobbAngles.PT.toFixed(1)}°</div>
                <div className="cobb-severity">{cobbAngles.PT_severity}</div>
              </div>
              <div className={`cobb-card ${getSeverityClass(cobbAngles.MT_severity)}`}>
                <div className="cobb-region">MT</div>
                <div className="cobb-label">Main Thoracic</div>
                <div className="cobb-value">{cobbAngles.MT.toFixed(1)}°</div>
                <div className="cobb-severity">{cobbAngles.MT_severity}</div>
              </div>
              <div className={`cobb-card ${getSeverityClass(cobbAngles.TL_severity)}`}>
                <div className="cobb-region">TL</div>
                <div className="cobb-label">Thoracolumbar/Lumbar</div>
                <div className="cobb-value">{cobbAngles.TL.toFixed(1)}°</div>
                <div className="cobb-severity">{cobbAngles.TL_severity}</div>
              </div>
            </div>
          )}
        </div>

        {/* Classification Panel */}
        <div className="analysis-panel classification-panel">
          <h3>Classification</h3>
          <div className="classification-grid">
            {rigoClass && (
              <div className="classification-card rigo-card">
                <div className="classification-type">Rigo-Chêneau</div>
                <div className="classification-badge">{rigoClass.type}</div>
                <div className="classification-desc">
                  {rigoClass.description || getRigoDescription(rigoClass.type)}
                </div>
              </div>
            )}
            {curveType && (
              <div className="classification-card curve-card">
                <div className="classification-type">Curve Pattern</div>
                <div className="classification-badge">{curveType}-Curve</div>
                <div className="classification-desc">
                  {curveType === 'S'
                    ? 'Double curve pattern with thoracic and lumbar components'
                    : curveType === 'C'
                    ? 'Single curve pattern'
                    : 'Curve pattern identified'}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Treatment Recommendation */}
        <div className={`analysis-panel treatment-panel treatment-${treatment.urgency}`}>
          <h3>Clinical Recommendation</h3>
          <div className="treatment-content">
            <div className="treatment-summary">
              <span className="max-cobb">
                Maximum Cobb Angle: <strong>{maxCobb.toFixed(1)}°</strong>
              </span>
              <span className={`urgency-badge urgency-${treatment.urgency}`}>
                {treatment.urgency}
              </span>
            </div>
            <p className="treatment-recommendation">{treatment.recommendation}</p>
          </div>
        </div>

        {/* Analysis Metadata */}
        <div className="analysis-panel metadata-panel">
          <h3>Analysis Details</h3>
          <div className="metadata-grid">
            <div className="metadata-item">
              <span className="metadata-label">Vertebrae Analyzed</span>
              <span className="metadata-value">
                {analysisData?.vertebrae_used || landmarksData?.vertebrae_structure.detected_count}
              </span>
            </div>
            <div className="metadata-item">
              <span className="metadata-label">Processing Time</span>
              <span className="metadata-value">
                {((analysisData?.processing_time_ms || landmarksData?.processing_time_ms || 0) / 1000).toFixed(2)}s
              </span>
            </div>
            {analysisData && (
              <div className="metadata-item">
                <span className="metadata-label">Source</span>
                <span className="metadata-value">Recalculated</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Actions */}
      <div className="stage-actions">
        <button
          className="btn secondary"
          onClick={onRecalculate}
          disabled={isLoading}
        >
          {isLoading ? 'Recalculating...' : 'Recalculate'}
        </button>
        <button className="btn primary" onClick={onContinue}>
          Continue to Brace Generation
        </button>
      </div>
    </div>
  );
}
