/**
 * Stage 5: Brace Editor
 * 3D visualization and deformation controls for the generated brace
 * 
 * Based on EXPERIMENT_6's brace-transform-playground-v2
 */
import { useState, useCallback } from 'react';
import BraceViewer from '../three/BraceViewer';
import type { GenerateBraceResponse } from '../../api/braceflowApi';

type MarkerInfo = {
  name: string;
  position: [number, number, number];
  color: string;
};

type DeformationParams = {
  thoracicPadDepth: number;
  lumbarPadDepth: number;
  trunkShift: number;
  rotationCorrection: number;
};

type Props = {
  caseId: string;
  braceData: GenerateBraceResponse | null;
  onRegenerate: (params: DeformationParams) => Promise<void>;
  onExportSTL: () => void;
};

const DEFAULT_PARAMS: DeformationParams = {
  thoracicPadDepth: 15,
  lumbarPadDepth: 10,
  trunkShift: 0,
  rotationCorrection: 0,
};

export default function BraceEditorStage({
  caseId,
  braceData,
  onRegenerate,
  onExportSTL,
}: Props) {
  const [params, setParams] = useState<DeformationParams>(DEFAULT_PARAMS);
  const [markers, setMarkers] = useState<MarkerInfo[]>([]);
  const [isRegenerating, setIsRegenerating] = useState(false);
  const [showMarkers, setShowMarkers] = useState(true);

  // Get GLB URL from brace data
  const glbUrl = braceData?.outputs?.glb?.url || braceData?.outputs?.shell_glb?.url || null;
  const stlUrl = braceData?.outputs?.stl?.url || braceData?.outputs?.shell_stl?.url || null;

  // Handle parameter change
  const handleParamChange = useCallback((key: keyof DeformationParams, value: number) => {
    setParams(prev => ({ ...prev, [key]: value }));
  }, []);

  // Handle regenerate
  const handleRegenerate = useCallback(async () => {
    setIsRegenerating(true);
    try {
      await onRegenerate(params);
    } finally {
      setIsRegenerating(false);
    }
  }, [params, onRegenerate]);

  // Handle markers loaded
  const handleMarkersLoaded = useCallback((loadedMarkers: MarkerInfo[]) => {
    setMarkers(loadedMarkers);
  }, []);

  // Reset parameters
  const handleReset = useCallback(() => {
    setParams(DEFAULT_PARAMS);
  }, []);

  if (!braceData) {
    return (
      <div className="pipeline-stage brace-editor-stage">
        <div className="stage-header">
          <h2>Stage 5: Brace Editor</h2>
          <div className="stage-status">
            <span className="status-badge status-pending">Waiting for Brace</span>
          </div>
        </div>
        <div className="stage-content">
          <div className="editor-empty">
            <p>Generate a brace first to use the 3D editor.</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="pipeline-stage brace-editor-stage">
      <div className="stage-header">
        <h2>Stage 5: Brace Editor</h2>
        <div className="stage-status">
          <span className="status-badge status-complete">Ready</span>
        </div>
      </div>

      <div className="stage-content">
        {/* 3D Viewer */}
        <div className="brace-editor-main">
          <BraceViewer
            glbUrl={glbUrl}
            width={700}
            height={550}
            showMarkers={showMarkers}
            onMarkersLoaded={handleMarkersLoaded}
            deformationParams={{
              thoracicPadDepth: params.thoracicPadDepth,
              lumbarPadDepth: params.lumbarPadDepth,
              trunkShift: params.trunkShift,
            }}
          />
          
          {/* View Controls */}
          <div className="viewer-controls">
            <label className="checkbox-label">
              <input
                type="checkbox"
                checked={showMarkers}
                onChange={(e) => setShowMarkers(e.target.checked)}
              />
              Show Markers
            </label>
          </div>
        </div>

        {/* Controls Sidebar */}
        <div className="brace-editor-sidebar">
          {/* Deformation Controls */}
          <div className="deformation-controls">
            <h3>Deformation Parameters</h3>
            
            <div className="control-group">
              <label>Thoracic Pad Depth (mm)</label>
              <div className="control-slider">
                <input
                  type="range"
                  min="0"
                  max="30"
                  step="1"
                  value={params.thoracicPadDepth}
                  onChange={(e) => handleParamChange('thoracicPadDepth', Number(e.target.value))}
                />
                <span className="value">{params.thoracicPadDepth}</span>
              </div>
            </div>
            
            <div className="control-group">
              <label>Lumbar Pad Depth (mm)</label>
              <div className="control-slider">
                <input
                  type="range"
                  min="0"
                  max="25"
                  step="1"
                  value={params.lumbarPadDepth}
                  onChange={(e) => handleParamChange('lumbarPadDepth', Number(e.target.value))}
                />
                <span className="value">{params.lumbarPadDepth}</span>
              </div>
            </div>
            
            <div className="control-group">
              <label>Trunk Shift (mm)</label>
              <div className="control-slider">
                <input
                  type="range"
                  min="-20"
                  max="20"
                  step="1"
                  value={params.trunkShift}
                  onChange={(e) => handleParamChange('trunkShift', Number(e.target.value))}
                />
                <span className="value">{params.trunkShift}</span>
              </div>
            </div>
            
            <div className="control-group">
              <label>Rotation Correction (°)</label>
              <div className="control-slider">
                <input
                  type="range"
                  min="-15"
                  max="15"
                  step="1"
                  value={params.rotationCorrection}
                  onChange={(e) => handleParamChange('rotationCorrection', Number(e.target.value))}
                />
                <span className="value">{params.rotationCorrection}</span>
              </div>
            </div>
            
            <div className="control-actions">
              <button className="btn secondary small" onClick={handleReset}>
                Reset
              </button>
              <button 
                className="btn primary small" 
                onClick={handleRegenerate}
                disabled={isRegenerating}
              >
                {isRegenerating ? 'Regenerating...' : 'Apply Changes'}
              </button>
            </div>
          </div>

          {/* Markers Panel */}
          {markers.length > 0 && (
            <div className="markers-panel">
              <h3>Markers ({markers.length})</h3>
              <div className="markers-list">
                {markers.map((marker, idx) => (
                  <div key={idx} className="marker-item">
                    <span 
                      className="marker-color" 
                      style={{ backgroundColor: marker.color }}
                    />
                    <span className="marker-name">{marker.name.replace('LM_', '')}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Export Panel */}
          <div className="export-panel">
            <h3>Export</h3>
            <div className="export-buttons">
              {stlUrl && (
                <a href={stlUrl} download={`brace_${caseId}.stl`} className="btn secondary">
                  Download STL
                </a>
              )}
              {glbUrl && (
                <a href={glbUrl} download={`brace_${caseId}.glb`} className="btn secondary">
                  Download GLB
                </a>
              )}
            </div>
          </div>

          {/* Info Panel */}
          <div className="info-panel">
            <h3>About the Editor</h3>
            <p>
              Adjust the deformation parameters to customize the brace fit. 
              Changes are previewed in real-time.
            </p>
            <ul className="tips-list">
              <li><strong>Thoracic Pad:</strong> Pressure on thoracic curve convexity</li>
              <li><strong>Lumbar Pad:</strong> Counter-pressure on lumbar region</li>
              <li><strong>Trunk Shift:</strong> Lateral correction force</li>
              <li><strong>Rotation:</strong> De-rotation effect</li>
            </ul>
            <p className="hint">
              Use mouse to orbit, scroll to zoom, right-click to pan.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
