import React, { useEffect, type ReactNode } from 'react';
import { Canvas, type CanvasProps } from '@react-three/fiber';
import { isWebGLSupported } from '../lib/webgl-detect';
import { useCaptureStore } from '../store/captureStore';
import { useViewerStore } from '../store/viewerStore';
import WebglErrorBoundary from './WebglErrorBoundary';
import { Lock, Unlock } from 'lucide-react';
import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from '@/components/ui/tooltip';

export const ViewerModuleContext = React.createContext<string | undefined>(undefined);

interface SceneCanvasProps extends CanvasProps {
  fallback: ReactNode;
  moduleId?: string;
}

function CanvasInner({ fallback: _, shadows, ...canvasProps }: SceneCanvasProps) {
  const registerCanvas = useCaptureStore((s) => s.registerCanvas);
  const unregisterCanvas = useCaptureStore((s) => s.unregisterCanvas);

  useEffect(() => () => unregisterCanvas(), [unregisterCanvas]);

  // Suprimir avisos de depreciação conhecidos do Three.js (r185) que o R3F ainda aciona
  useEffect(() => {
    const originalWarn = console.warn;
    console.warn = (...args) => {
      if (typeof args[0] === 'string' && (args[0].includes('THREE.Clock') || args[0].includes('THREE.WebGLShadowMap'))) {
        return;
      }
      originalWarn(...args);
    };
    return () => {
      console.warn = originalWarn;
    };
  }, []);

  // O R3F v9 usa PCFSoftShadowMap por padrão, que está deprecado no Three r185.
  // Mudar para PCFShadowMap (1) via propriedade shadows.
  const shadowConfig = shadows === true ? { type: 1 as any } : shadows;

  return (
    <Canvas
      frameloop="demand"
      gl={{ preserveDrawingBuffer: true }}
      {...canvasProps}
      shadows={shadowConfig}
      onCreated={(state) => {
        registerCanvas(state.gl.domElement);
        canvasProps.onCreated?.(state);
      }}
    />
  );
}

export default function SceneCanvas({ fallback, style, className, moduleId, ...rest }: SceneCanvasProps) {
  const { locks, toggleLock } = useViewerStore();

  if (!isWebGLSupported()) {
    return (
      <div
        style={{ width: '100%', height: '100%', minHeight: '500px', borderRadius: 'var(--radius-lg)', overflow: 'hidden', ...style }}
        className={className}
      >
        {fallback}
      </div>
    );
  }

  // If no moduleId is provided, use a default key or treat as unlocked globally
  const isLocked = moduleId ? !!locks[moduleId] : false;

  const handleToggleLock = () => {
    if (moduleId) {
      toggleLock(moduleId);
    }
  };

  return (
    <ViewerModuleContext.Provider value={moduleId}>
      <div
        style={{ width: '100%', height: '100%', minHeight: '500px', borderRadius: 'var(--radius-lg)', overflow: 'hidden', position: 'relative', ...style }}
        className={`${className ?? ''} glass-panel`}
      >
        <WebglErrorBoundary fallback={fallback}>
          <CanvasInner {...rest} fallback={fallback} />
        </WebglErrorBoundary>
        
        {moduleId && (
          <div className="absolute bottom-4 right-4 z-20">
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <button
                    onClick={handleToggleLock}
                    className={`flex items-center justify-center w-10 h-10 rounded-full border shadow-sm backdrop-blur-md transition-colors ${
                      isLocked ? 'bg-destructive/80 hover:bg-destructive border-destructive/20' : 'bg-background/80 hover:bg-background border-border'
                    }`}
                    aria-label={isLocked ? 'Destravar visualização 3D' : 'Travar visualização 3D'}
                  >
                    {isLocked ? <Lock className="w-5 h-5 text-destructive-foreground" /> : <Unlock className="w-5 h-5 text-muted-foreground" />}
                  </button>
                </TooltipTrigger>
                <TooltipContent side="left">
                  <p>{isLocked ? 'Destravar rotação' : 'Travar rotação'}</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </div>
        )}
      </div>
    </ViewerModuleContext.Provider>
  );
}
