/**
 * Stage 4: Brace Generation
 * Shows generated brace with 3D viewer and marker editing
 * Displays both Regular and Vase brace types side-by-side
 * Includes inline editors for real-time brace transformation
 */
import { useState, useRef, useCallback } from 'react';
import type { GenerateBraceResponse, DeformationZone } from '../../api/braceflowApi';
import { getModifiedBraceUploadUrl, uploadBlobToS3 } from '../../api/braceflowApi';
import BraceTransformViewer from '../three/BraceTransformViewer';
import type { BraceTransformViewerRef } from '../three/BraceTransformViewer';
import BraceInlineEditor, { 
  type BraceTransformParams, 
  DEFAULT_TRANSFORM_PARAMS 
} from './BraceInlineEditor';

type Props = {
  caseId: string;
  braceData: GenerateBraceResponse | null;
  isLoading: boolean;
  onGenerate: () => Promise<void>;
  onUpdateMarkers: (markers: Record<string, unknown>) => Promise<void>;
};

export default function BraceGenerationStage({
  caseId,
  braceData,
  isLoading,
  onGenerate,
  onUpdateMarkers,
}: Props) {
  const [showEditor, setShowEditor] = useState(false);
  const [showInlineEditors, setShowInlineEditors] = useState(true);
  const regularViewerRef = useRef<BraceTransformViewerRef>(null);
  const vaseViewerRef = useRef<BraceTransformViewerRef>(null);
  
  // Transform params state for each brace type
  const [regularParams, setRegularParams] = useState<BraceTransformParams>(() => ({
    ...DEFAULT_TRANSFORM_PARAMS,
  }));
  const [vaseParams, setVaseParams] = useState<BraceTransformParams>(() => ({
    ...DEFAULT_TRANSFORM_PARAMS,
  }));
  
  // Track if braces have been modified
  const [regularModified, setRegularModified] = useState(false);
  const [vaseModified, setVaseModified] = useState(false);

  // Handle transform params changes
  const handleRegularParamsChange = useCallback((params: BraceTransformParams) => {
    setRegularParams(params);
    setRegularModified(true);
  }, []);

  const handleVaseParamsChange = useCallback((params: BraceTransformParams) => {
    setVaseParams(params);
    setVaseModified(true);
  }, []);

  // Track save status
  const [saveStatus, setSaveStatus] = useState<string | null>(null);

  // Handle save/upload for modified braces
  const handleSaveRegular = useCallback(async (params: BraceTransformParams) => {
    if (!regularViewerRef.current) return;
    
    setSaveStatus('Exporting regular brace...');
    
    try {
      let savedCount = 0;
      
      // Export STL
      const stlBlob = await regularViewerRef.current.exportSTL();
      if (stlBlob) {
        setSaveStatus('Uploading regular STL...');
        const { url: uploadUrl, contentType } = await getModifiedBraceUploadUrl(caseId, 'regular', 'stl');
        await uploadBlobToS3(uploadUrl, stlBlob, contentType || 'application/octet-stream');
        console.log('Regular STL uploaded to case storage');
        savedCount++;
      }
      
      // Export GLB
      const glbBlob = await regularViewerRef.current.exportGLB();
      if (glbBlob) {
        setSaveStatus('Uploading regular GLB...');
        const { url: uploadUrl, contentType } = await getModifiedBraceUploadUrl(caseId, 'regular', 'glb');
        await uploadBlobToS3(uploadUrl, glbBlob, contentType || 'model/gltf-binary');
        console.log('Regular GLB uploaded to case storage');
        savedCount++;
      }
      
      setSaveStatus(`Regular brace saved! (${savedCount} files)`);
      setRegularModified(false);
      setTimeout(() => setSaveStatus(null), 3000);
    } catch (err) {
      console.error('Failed to save regular brace:', err);
      setSaveStatus(`Error: ${err instanceof Error ? err.message : 'Failed to save'}`);
      setTimeout(() => setSaveStatus(null), 5000);
    }
  }, [caseId]);

  const handleSaveVase = useCallback(async (params: BraceTransformParams) => {
    if (!vaseViewerRef.current) return;
    
    setSaveStatus('Exporting vase brace...');
    
    try {
      let savedCount = 0;
      
      // Export STL
      const stlBlob = await vaseViewerRef.current.exportSTL();
      if (stlBlob) {
        setSaveStatus('Uploading vase STL...');
        const { url: uploadUrl, contentType } = await getModifiedBraceUploadUrl(caseId, 'vase', 'stl');
        await uploadBlobToS3(uploadUrl, stlBlob, contentType || 'application/octet-stream');
        console.log('Vase STL uploaded to case storage');
        savedCount++;
      }
      
      // Export GLB
      const glbBlob = await vaseViewerRef.current.exportGLB();
      if (glbBlob) {
        setSaveStatus('Uploading vase GLB...');
        const { url: uploadUrl, contentType } = await getModifiedBraceUploadUrl(caseId, 'vase', 'glb');
        await uploadBlobToS3(uploadUrl, glbBlob, contentType || 'model/gltf-binary');
        console.log('Vase GLB uploaded to case storage');
        savedCount++;
      }
      
      setSaveStatus(`Vase brace saved! (${savedCount} files)`);
      setVaseModified(false);
      setTimeout(() => setSaveStatus(null), 3000);
    } catch (err) {
      console.error('Failed to save vase brace:', err);
      setSaveStatus(`Error: ${err instanceof Error ? err.message : 'Failed to save'}`);
      setTimeout(() => setSaveStatus(null), 5000);
    }
  }, [caseId]);

  // Handle reset
  const handleResetRegular = useCallback(() => {
    setRegularParams({
      ...DEFAULT_TRANSFORM_PARAMS,
      cobbDeg: braceData?.cobb_angles?.MT || braceData?.cobb_angles?.TL || DEFAULT_TRANSFORM_PARAMS.cobbDeg,
    });
    setRegularModified(false);
  }, [braceData?.cobb_angles]);

  const handleResetVase = useCallback(() => {
    setVaseParams({
      ...DEFAULT_TRANSFORM_PARAMS,
      cobbDeg: braceData?.cobb_angles?.MT || braceData?.cobb_angles?.TL || DEFAULT_TRANSFORM_PARAMS.cobbDeg,
    });
    setVaseModified(false);
  }, [braceData?.cobb_angles]);

  // Get output URLs for regular brace
  const outputs = braceData?.outputs || {};
  const stlUrl = outputs.stl?.url || (outputs as any).stl;
  const glbUrl = outputs.glb?.url || (outputs as any).glb;
  const vizUrl = outputs.visualization?.url || (outputs as any).visualization;
  const jsonUrl = outputs.landmarks?.url || (outputs as any).landmarks;

  // Get output URLs for vase brace (if available)
  const braces = (braceData as any)?.braces || {};
  const regularBrace = braces.regular || { outputs: { stl: stlUrl, glb: glbUrl } };
  const vaseBrace = braces.vase || {};

  // Helper function to format file size
  const formatFileSize = (bytes?: number): string => {
    if (!bytes) 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]}`;
  };

  if (!braceData && !isLoading) {
    return (
      <div className="pipeline-stage brace-stage">
        <div className="stage-header">
          <h2>Stage 4: Brace Generation</h2>
          <div className="stage-status">
            <span className="status-badge status-pending">Pending</span>
          </div>
        </div>
        <div className="stage-content">
          <div className="brace-empty">
            <p>Ready to generate custom brace based on approved landmarks and analysis.</p>
            <button className="btn primary btn-large" onClick={onGenerate}>
              Generate Brace
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="pipeline-stage brace-stage">
        <div className="stage-header">
          <h2>Stage 4: Brace Generation</h2>
          <div className="stage-status">
            <span className="status-badge status-processing">Generating...</span>
          </div>
        </div>
        <div className="stage-content">
          <div className="brace-loading">
            <div className="spinner large"></div>
            <p>Generating custom braces...</p>
            <p className="loading-hint">
              Generating both Regular and Vase brace designs for comparison.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="pipeline-stage brace-stage">
      <div className="stage-header">
        <h2>Stage 4: Brace Generation</h2>
        <div className="stage-status">
          <span className="status-badge status-complete">Complete</span>
        </div>
      </div>

      {/* Summary Panels - Right under header */}
      <div className="brace-summary-row">
        {/* Generation Summary */}
        <div className="brace-panel summary-panel">
          <h3>Generation Summary</h3>
          <div className="summary-grid horizontal">
            {braceData?.rigo_classification && (
              <div className="summary-item">
                <span className="summary-label">Rigo Type</span>
                <span className="summary-value badge">
                  {braceData.rigo_classification.type}
                </span>
              </div>
            )}
            {braceData?.curve_type && (
              <div className="summary-item">
                <span className="summary-label">Curve</span>
                <span className="summary-value">{braceData.curve_type}-Curve</span>
              </div>
            )}
            {braceData?.processing_time_ms && (
              <div className="summary-item">
                <span className="summary-label">Time</span>
                <span className="summary-value">
                  {(braceData.processing_time_ms / 1000).toFixed(1)}s
                </span>
              </div>
            )}
          </div>
        </div>

        {/* Cobb Angles Used */}
        {braceData?.cobb_angles && (
          <div className="brace-panel cobb-panel">
            <h3>Cobb Angles Used</h3>
            <div className="cobb-mini-grid horizontal">
              <div className="cobb-mini">
                <span className="cobb-label">PT</span>
                <span className="cobb-value">{braceData.cobb_angles.PT?.toFixed(1)}°</span>
              </div>
              <div className="cobb-mini">
                <span className="cobb-label">MT</span>
                <span className="cobb-value">{braceData.cobb_angles.MT?.toFixed(1)}°</span>
              </div>
              <div className="cobb-mini">
                <span className="cobb-label">TL</span>
                <span className="cobb-value">{braceData.cobb_angles.TL?.toFixed(1)}°</span>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Toggle Editor Button + Save Status */}
      <div className="editor-toggle-row">
        {saveStatus && (
          <span className={`save-status ${saveStatus.includes('Error') ? 'error' : saveStatus.includes('saved') ? 'success' : ''}`}>
            {saveStatus}
          </span>
        )}
        <button 
          className={`btn-toggle-editor ${showInlineEditors ? 'active' : ''}`}
          onClick={() => setShowInlineEditors(!showInlineEditors)}
        >
          {showInlineEditors ? 'Hide Editors' : 'Show Editors'}
        </button>
      </div>

      {/* Dual Brace Viewers with Inline Editors */}
      <div className={`dual-brace-viewers ${showInlineEditors ? 'with-editors' : ''}`}>
        {/* Regular Brace Viewer + Editor */}
        <div className="brace-viewer-with-editor">
          <div className="brace-viewer-container">
            <div className="viewer-header">
              <h3>Regular Brace</h3>
              <span className="viewer-subtitle">Fitted design for precise correction</span>
              {regularModified && <span className="modified-indicator">Modified</span>}
            </div>
            <div className="brace-viewer brace-viewer-3d">
              <BraceTransformViewer 
                ref={regularViewerRef}
                stlUrl={regularBrace.outputs?.stl || stlUrl}
                glbUrl={regularBrace.outputs?.glb || glbUrl}
                transformParams={regularParams}
                autoRotate={!showInlineEditors}
                rotationSpeed={0.005}
                showMarkers={true}
                showGrid={showInlineEditors}
              />
            </div>
            {regularBrace.meshStats && (
              <div className="viewer-stats">
                <span>{regularBrace.meshStats.vertices?.toLocaleString()} vertices</span>
                <span>{regularBrace.meshStats.faces?.toLocaleString()} faces</span>
              </div>
            )}
          </div>
          
          {/* Inline Editor for Regular Brace */}
          {showInlineEditors && (
            <BraceInlineEditor
              braceType="regular"
              initialParams={regularParams}
              cobbAngles={braceData?.cobb_angles}
              onParamsChange={handleRegularParamsChange}
              onSave={handleSaveRegular}
              onReset={handleResetRegular}
              isModified={regularModified}
              className="viewer-inline-editor"
            />
          )}
        </div>

        {/* Vase Brace Viewer + Editor */}
        <div className="brace-viewer-with-editor">
          <div className="brace-viewer-container">
            <div className="viewer-header">
              <h3>Vase Brace</h3>
              <span className="viewer-subtitle">Smooth contoured design</span>
              {vaseModified && <span className="modified-indicator">Modified</span>}
            </div>
            <div className="brace-viewer brace-viewer-3d">
              {vaseBrace.outputs?.stl || vaseBrace.outputs?.glb ? (
                <BraceTransformViewer 
                  ref={vaseViewerRef}
                  stlUrl={vaseBrace.outputs?.stl}
                  glbUrl={vaseBrace.outputs?.glb}
                  transformParams={vaseParams}
                  autoRotate={!showInlineEditors}
                  rotationSpeed={0.005}
                  showMarkers={true}
                  showGrid={showInlineEditors}
                />
              ) : (
                <div className="viewer-placeholder">
                  <div className="placeholder-icon">🏺</div>
                  <p>Vase brace not generated</p>
                  <p className="hint">Click "Generate Both" to create vase design</p>
                </div>
              )}
            </div>
            {vaseBrace.meshStats && (
              <div className="viewer-stats">
                <span>{vaseBrace.meshStats.vertices?.toLocaleString()} vertices</span>
                <span>{vaseBrace.meshStats.faces?.toLocaleString()} faces</span>
              </div>
            )}
          </div>
          
          {/* Inline Editor for Vase Brace */}
          {showInlineEditors && (vaseBrace.outputs?.stl || vaseBrace.outputs?.glb) && (
            <BraceInlineEditor
              braceType="vase"
              initialParams={vaseParams}
              cobbAngles={braceData?.cobb_angles}
              onParamsChange={handleVaseParamsChange}
              onSave={handleSaveVase}
              onReset={handleResetVase}
              isModified={vaseModified}
              className="viewer-inline-editor"
            />
          )}
        </div>
      </div>

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

      {/* Download Files - Bottom Section */}
      <div className="downloads-section">
        <h3>Download Files</h3>
        <div className="downloads-columns">
          {/* Regular Brace Downloads */}
          <div className="download-column">
            <h4>Regular Brace</h4>
            <div className="downloads-list">
              {(regularBrace.outputs?.stl || stlUrl) && (
                <a
                  href={regularBrace.outputs?.stl || stlUrl}
                  className="download-item"
                  download={`brace_${caseId}_regular.stl`}
                >
                  <span className="download-icon">📦</span>
                  <span className="download-info">
                    <span className="download-name">regular.stl</span>
                    <span className="download-desc">For 3D printing</span>
                  </span>
                  <span className="download-action">↓</span>
                </a>
              )}
              {(regularBrace.outputs?.glb || glbUrl) && (
                <a
                  href={regularBrace.outputs?.glb || glbUrl}
                  className="download-item"
                  download={`brace_${caseId}_regular.glb`}
                >
                  <span className="download-icon">🎮</span>
                  <span className="download-info">
                    <span className="download-name">regular.glb</span>
                    <span className="download-desc">For web/AR</span>
                  </span>
                  <span className="download-action">↓</span>
                </a>
              )}
              {(regularBrace.outputs?.json || jsonUrl) && (
                <a
                  href={regularBrace.outputs?.json || jsonUrl}
                  className="download-item"
                  download={`brace_${caseId}_regular_markers.json`}
                >
                  <span className="download-icon">📄</span>
                  <span className="download-info">
                    <span className="download-name">markers.json</span>
                    <span className="download-desc">With markers</span>
                  </span>
                  <span className="download-action">↓</span>
                </a>
              )}
            </div>
          </div>

          {/* Vase Brace Downloads */}
          <div className="download-column">
            <h4>Vase Brace</h4>
            <div className="downloads-list">
              {vaseBrace.outputs?.stl ? (
                <>
                  <a
                    href={vaseBrace.outputs.stl}
                    className="download-item"
                    download={`brace_${caseId}_vase.stl`}
                  >
                    <span className="download-icon">📦</span>
                    <span className="download-info">
                      <span className="download-name">vase.stl</span>
                      <span className="download-desc">For 3D printing</span>
                    </span>
                    <span className="download-action">↓</span>
                  </a>
                  {vaseBrace.outputs?.glb && (
                    <a
                      href={vaseBrace.outputs.glb}
                      className="download-item"
                      download={`brace_${caseId}_vase.glb`}
                    >
                      <span className="download-icon">🎮</span>
                      <span className="download-info">
                        <span className="download-name">vase.glb</span>
                        <span className="download-desc">For web/AR</span>
                      </span>
                      <span className="download-action">↓</span>
                    </a>
                  )}
                  {vaseBrace.outputs?.json && (
                    <a
                      href={vaseBrace.outputs.json}
                      className="download-item"
                      download={`brace_${caseId}_vase_markers.json`}
                    >
                      <span className="download-icon">📄</span>
                      <span className="download-info">
                        <span className="download-name">markers.json</span>
                        <span className="download-desc">With markers</span>
                      </span>
                      <span className="download-action">↓</span>
                    </a>
                  )}
                </>
              ) : (
                <div className="download-placeholder">
                  <span>Not generated</span>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Actions */}
      <div className="stage-actions">
        <button
          className="btn secondary"
          onClick={() => setShowEditor(!showEditor)}
        >
          {showEditor ? 'Hide Editor' : 'Edit Brace Markers'}
        </button>
        <button className="btn primary" onClick={onGenerate}>
          Regenerate Brace
        </button>
      </div>

      {/* Marker Editor Modal (placeholder) */}
      {showEditor && (
        <div className="marker-editor-overlay">
          <div className="marker-editor-modal">
            <div className="modal-header">
              <h3>Brace Marker Editor</h3>
              <button className="close-btn" onClick={() => setShowEditor(false)}>
                ×
              </button>
            </div>
            <div className="modal-content">
              <p>
                The 3D marker editor integration is coming soon. This will allow you to:
              </p>
              <ul>
                <li>Drag and reposition pressure pad markers</li>
                <li>Adjust deformation depths</li>
                <li>Preview changes in real-time</li>
                <li>Regenerate the brace with modified parameters</li>
              </ul>
              <p className="hint">
                For now, you can download the JSON file to manually edit marker positions.
              </p>
            </div>
            <div className="modal-actions">
              <button className="btn secondary" onClick={() => setShowEditor(false)}>
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
