import { useRef, useState, Suspense } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { OrbitControls, Stage } from '@react-three/drei';
import { Card } from '../common/Card';
import { Button } from '../common/Button';
import { Maximize2, RotateCcw } from 'lucide-react';

// Placeholder component for the mesh
// In a real implementation, this would load the GLTF/OBJ file converted from Nastran
const Model = ({ path: _path }: { path?: string }) => {
  // For now, we'll render a simple box to demonstrate the viewer
  const meshRef = useRef<any>();
  
  useFrame((_state, delta) => {
    if (meshRef.current) {
      meshRef.current.rotation.y += delta * 0.2;
    }
  });

  return (
    <mesh ref={meshRef}>
      <boxGeometry args={[2, 2, 2]} />
      <meshStandardMaterial color="#60a5fa" wireframe />
    </mesh>
  );
};

interface MeshViewerProps {
  modelPath?: string;
  resultField?: string;
}

export const MeshViewer = ({ modelPath, resultField: _resultField }: MeshViewerProps) => {
  const [autoRotate, setAutoRotate] = useState(true);

  return (
    <Card title="3D Result Viewer" className="h-full flex flex-col">
      <div className="relative flex-1 min-h-[400px] bg-dark-900 rounded-lg overflow-hidden border border-dark-700">
        <Canvas shadows dpr={[1, 2]} camera={{ fov: 50 }}>
          <Suspense fallback={null}>
            <Stage environment="city" intensity={0.6}>
              <Model path={modelPath} />
            </Stage>
          </Suspense>
          <OrbitControls autoRotate={autoRotate} />
        </Canvas>
        
        {/* Controls Overlay */}
        <div className="absolute bottom-4 right-4 flex gap-2">
          <Button 
            size="sm" 
            variant="secondary" 
            onClick={() => setAutoRotate(!autoRotate)}
            icon={<RotateCcw className={`w-4 h-4 ${autoRotate ? 'animate-spin' : ''}`} />}
          >
            {autoRotate ? 'Stop Rotation' : 'Auto Rotate'}
          </Button>
          <Button 
            size="sm" 
            variant="secondary" 
            icon={<Maximize2 className="w-4 h-4" />}
          >
            Fullscreen
          </Button>
        </div>

        {/* Legend Overlay */}
        <div className="absolute top-4 left-4 bg-dark-800/80 p-3 rounded-lg backdrop-blur-sm border border-dark-600">
          <div className="text-xs font-medium text-dark-300 mb-2">Displacement (mm)</div>
          <div className="h-32 w-4 bg-gradient-to-t from-blue-500 via-green-500 to-red-500 rounded-full mx-auto" />
          <div className="flex justify-between text-[10px] text-dark-400 mt-1 w-12">
            <span>0.0</span>
            <span>5.2</span>
          </div>
        </div>
      </div>
    </Card>
  );
};