/**
 * BraceInlineEditor - Inline slider controls for brace transformation
 * Based on EXPERIMENT_6's brace-transform-playground-v2
 * 
 * Provides real-time deformation controls that can be embedded
 * directly within the BraceGenerationStage component.
 */
import { useState, useCallback, useEffect } from 'react';

export type BraceTransformParams = {
  // Analysis parameters
  cobbDeg: number;
  apexNorm: number;           // 0..1 along brace height
  lumbarApexNorm: number;     // 0..1
  rotationScore: number;      // 0..3
  trunkShiftMm: number;
  
  // Calibration
  expectedBraceHeightMm: number;
  strengthMult: number;
  
  // Direction strategy
  pushMode: 'normal' | 'radial' | 'lateral';
  
  // Pelvis/anchors
  hipAnchorStrengthMm: number;
  
  // Debug
  mirrorX: boolean;
};

export const DEFAULT_TRANSFORM_PARAMS: BraceTransformParams = {
  cobbDeg: 25,
  apexNorm: 0.62,
  lumbarApexNorm: 0.40,
  rotationScore: 0,
  trunkShiftMm: 0,
  expectedBraceHeightMm: 400,
  strengthMult: 1.0,
  pushMode: 'radial',
  hipAnchorStrengthMm: 4,
  mirrorX: false,
};

type SliderConfig = {
  key: keyof BraceTransformParams;
  label: string;
  min: number;
  max: number;
  step: number;
  unit?: string;
};

const SLIDER_CONFIGS: SliderConfig[] = [
  { key: 'cobbDeg', label: 'Cobb Angle', min: 0, max: 80, step: 1, unit: '°' },
  { key: 'apexNorm', label: 'Thoracic Apex Height', min: 0, max: 1, step: 0.01 },
  { key: 'lumbarApexNorm', label: 'Lumbar Apex Height', min: 0, max: 1, step: 0.01 },
  { key: 'rotationScore', label: 'Rotation', min: 0, max: 3, step: 0.1 },
  { key: 'trunkShiftMm', label: 'Trunk Shift', min: -40, max: 40, step: 1, unit: 'mm' },
  { key: 'strengthMult', label: 'Strength', min: 0.2, max: 2.0, step: 0.05, unit: 'x' },
  { key: 'hipAnchorStrengthMm', label: 'Hip Anchor', min: 0, max: 12, step: 1, unit: 'mm' },
];

const ADVANCED_SLIDER_CONFIGS: SliderConfig[] = [
  { key: 'expectedBraceHeightMm', label: 'Expected Height', min: 250, max: 650, step: 10, unit: 'mm' },
];

type Props = {
  braceType: 'regular' | 'vase';
  initialParams?: Partial<BraceTransformParams>;
  cobbAngles?: { PT?: number; MT?: number; TL?: number };
  onParamsChange: (params: BraceTransformParams) => void;
  onSave: (params: BraceTransformParams) => void;
  onReset: () => void;
  isModified?: boolean;
  className?: string;
};

export default function BraceInlineEditor({
  braceType,
  initialParams,
  cobbAngles,
  onParamsChange,
  onSave,
  onReset,
  isModified = false,
  className = '',
}: Props) {
  const [params, setParams] = useState<BraceTransformParams>(() => ({
    ...DEFAULT_TRANSFORM_PARAMS,
    ...initialParams,
    // Auto-set Cobb angle from analysis if available
    cobbDeg: cobbAngles?.MT || cobbAngles?.TL || DEFAULT_TRANSFORM_PARAMS.cobbDeg,
  }));
  
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  // Update params when initial params change
  useEffect(() => {
    if (initialParams) {
      setParams(prev => ({
        ...prev,
        ...initialParams,
      }));
    }
  }, [initialParams]);

  // Notify parent of changes
  const handleParamChange = useCallback((key: keyof BraceTransformParams, value: number | string | boolean) => {
    setParams(prev => {
      const updated = { ...prev, [key]: value };
      onParamsChange(updated);
      return updated;
    });
  }, [onParamsChange]);

  // Handle save
  const handleSave = useCallback(async () => {
    setIsSaving(true);
    try {
      await onSave(params);
    } finally {
      setIsSaving(false);
    }
  }, [params, onSave]);

  // Handle reset
  const handleReset = useCallback(() => {
    const resetParams = {
      ...DEFAULT_TRANSFORM_PARAMS,
      ...initialParams,
      cobbDeg: cobbAngles?.MT || cobbAngles?.TL || DEFAULT_TRANSFORM_PARAMS.cobbDeg,
    };
    setParams(resetParams);
    onReset();
  }, [initialParams, cobbAngles, onReset]);

  const formatValue = (value: number, step: number, unit?: string): string => {
    const formatted = step < 1 ? value.toFixed(2) : value.toString();
    return unit ? `${formatted}${unit}` : formatted;
  };

  return (
    <div className={`brace-inline-editor ${className}`}>
      <div className="editor-header">
        <h4>{braceType === 'regular' ? 'Regular' : 'Vase'} Brace Editor</h4>
        {isModified && <span className="modified-badge">Modified</span>}
      </div>

      <div className="editor-sliders">
        {SLIDER_CONFIGS.map(config => (
          <div key={config.key} className="slider-row">
            <div className="slider-label">
              <span>{config.label}</span>
              <span className="slider-value">
                {formatValue(params[config.key] as number, config.step, config.unit)}
              </span>
            </div>
            <input
              type="range"
              min={config.min}
              max={config.max}
              step={config.step}
              value={params[config.key] as number}
              onChange={(e) => handleParamChange(config.key, Number(e.target.value))}
              className="slider-input"
            />
          </div>
        ))}
      </div>

      {/* Push Mode Toggle */}
      <div className="editor-mode-toggle">
        <span className="toggle-label">Push Mode:</span>
        <div className="toggle-buttons">
          {(['normal', 'radial', 'lateral'] as const).map(mode => (
            <button
              key={mode}
              className={`toggle-btn ${params.pushMode === mode ? 'active' : ''}`}
              onClick={() => handleParamChange('pushMode', mode)}
            >
              {mode.charAt(0).toUpperCase() + mode.slice(1)}
            </button>
          ))}
        </div>
      </div>

      {/* Mirror Toggle */}
      <div className="editor-checkbox">
        <label>
          <input
            type="checkbox"
            checked={params.mirrorX}
            onChange={(e) => handleParamChange('mirrorX', e.target.checked)}
          />
          <span>Mirror X (flip left/right)</span>
        </label>
      </div>

      {/* Advanced Toggle */}
      <button 
        className="advanced-toggle"
        onClick={() => setShowAdvanced(!showAdvanced)}
      >
        {showAdvanced ? '▼ Hide Advanced' : '▶ Show Advanced'}
      </button>

      {showAdvanced && (
        <div className="editor-sliders advanced">
          {ADVANCED_SLIDER_CONFIGS.map(config => (
            <div key={config.key} className="slider-row">
              <div className="slider-label">
                <span>{config.label}</span>
                <span className="slider-value">
                  {formatValue(params[config.key] as number, config.step, config.unit)}
                </span>
              </div>
              <input
                type="range"
                min={config.min}
                max={config.max}
                step={config.step}
                value={params[config.key] as number}
                onChange={(e) => handleParamChange(config.key, Number(e.target.value))}
                className="slider-input"
              />
            </div>
          ))}
        </div>
      )}

      {/* Action Buttons */}
      <div className="editor-actions">
        <button 
          className="btn-editor reset"
          onClick={handleReset}
          title="Reset to default values"
        >
          Reset
        </button>
        <button 
          className="btn-editor save"
          onClick={handleSave}
          disabled={isSaving}
          title="Save modified brace to case storage"
        >
          {isSaving ? 'Saving...' : 'Save'}
        </button>
      </div>
    </div>
  );
}
