import { Suspense, useState, useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { OrbitControls, Environment, ContactShadows, useGLTF, Center, Grid } from "@react-three/drei";
import * as THREE from "three";

// Placeholder brace model when no model is loaded
function PlaceholderBrace({ opacity = 1 }: { opacity?: number }) {
  const meshRef = useRef<THREE.Group>(null);

  useFrame((state) => {
    if (meshRef.current) {
      meshRef.current.rotation.y = Math.sin(state.clock.elapsedTime * 0.3) * 0.1;
    }
  });

  return (
    <group ref={meshRef}>
      {/* Main brace body - simplified torso shape */}
      <mesh position={[0, 0, 0]}>
        <cylinderGeometry args={[0.8, 1, 2.5, 32, 1, true]} />
        <meshStandardMaterial
          color="#4a90d9"
          transparent
          opacity={opacity * 0.8}
          side={THREE.DoubleSide}
          metalness={0.1}
          roughness={0.6}
        />
      </mesh>

      {/* Right pressure pad (thoracic) */}
      <mesh position={[0.85, 0.3, 0]} rotation={[0, 0, Math.PI / 6]}>
        <boxGeometry args={[0.15, 0.8, 0.6]} />
        <meshStandardMaterial color="#2563eb" transparent opacity={opacity} metalness={0.2} roughness={0.4} />
      </mesh>

      {/* Left expansion window cutout visual */}
      <mesh position={[-0.75, 0.3, 0.2]}>
        <boxGeometry args={[0.1, 0.6, 0.5]} />
        <meshStandardMaterial color="#0f172a" transparent opacity={opacity * 0.9} />
      </mesh>

      {/* Lumbar support */}
      <mesh position={[0, -0.8, 0.5]} rotation={[0.3, 0, 0]}>
        <boxGeometry args={[0.8, 0.4, 0.2]} />
        <meshStandardMaterial color="#3b82f6" transparent opacity={opacity} metalness={0.2} roughness={0.4} />
      </mesh>
    </group>
  );
}

// Load actual GLB model
function BraceModel({ url, opacity = 1 }: { url: string; opacity?: number }) {
  const { scene } = useGLTF(url);
  const meshRef = useRef<THREE.Object3D>(null);

  // Apply materials to all meshes
  scene.traverse((child) => {
    if ((child as THREE.Mesh).isMesh) {
      (child as THREE.Mesh).material = new THREE.MeshStandardMaterial({
        color: "#4a90d9",
        transparent: true,
        opacity: opacity * 0.8,
        metalness: 0.1,
        roughness: 0.6,
        side: THREE.DoubleSide,
      });
    }
  });

  return (
    <Center>
      <primitive ref={meshRef} object={scene} scale={1} />
    </Center>
  );
}

// Loading indicator
function LoadingIndicator() {
  const meshRef = useRef<THREE.Mesh>(null);

  useFrame((state) => {
    if (meshRef.current) {
      meshRef.current.rotation.y = state.clock.elapsedTime * 2;
    }
  });

  return (
    <mesh ref={meshRef}>
      <torusGeometry args={[0.5, 0.1, 16, 32]} />
      <meshStandardMaterial color="#3b82f6" emissive="#3b82f6" emissiveIntensity={0.5} />
    </mesh>
  );
}

interface BraceViewerProps {
  modelUrl: string | null;
  isLoading: boolean;
}

export default function BraceViewer({ modelUrl, isLoading }: BraceViewerProps) {
  const [transparency, setTransparency] = useState(false);
  const [showGrid, setShowGrid] = useState(true);

  const opacity = transparency ? 0.4 : 1;

  return (
    <>
      <Canvas
        className="rigo-viewer-canvas"
        camera={{ position: [3, 2, 3], fov: 45 }}
        gl={{ antialias: true, alpha: true }}
        style={{ width: "100%", height: "100%", minHeight: "400px" }}
      >
        <color attach="background" args={["#111827"]} />

        {/* Lighting */}
        <ambientLight intensity={0.4} />
        <directionalLight position={[5, 5, 5]} intensity={1} castShadow shadow-mapSize={[2048, 2048]} />
        <directionalLight position={[-5, 3, -5]} intensity={0.3} />
        <pointLight position={[0, 3, 0]} intensity={0.5} color="#60a5fa" />

        {/* Environment for reflections */}
        <Environment preset="city" />

        {/* Grid */}
        {showGrid && (
          <Grid
            args={[10, 10]}
            cellSize={0.5}
            cellThickness={0.5}
            cellColor="#334155"
            sectionSize={2}
            sectionThickness={1}
            sectionColor="#475569"
            fadeDistance={10}
            fadeStrength={1}
            position={[0, -1.5, 0]}
          />
        )}

        {/* Contact shadows */}
        <ContactShadows position={[0, -1.5, 0]} opacity={0.4} scale={5} blur={2.5} />

        {/* Model */}
        <Suspense fallback={<LoadingIndicator />}>
          {isLoading ? (
            <LoadingIndicator />
          ) : modelUrl ? (
            <BraceModel url={modelUrl} opacity={opacity} />
          ) : (
            <PlaceholderBrace opacity={opacity} />
          )}
        </Suspense>

        {/* Controls */}
        <OrbitControls
          makeDefault
          enableDamping
          dampingFactor={0.05}
          minDistance={2}
          maxDistance={10}
          minPolarAngle={Math.PI / 6}
          maxPolarAngle={Math.PI / 1.5}
        />
      </Canvas>

      {/* Viewer Controls */}
      <div className="rigo-viewer-controls">
        <button
          className={`rigo-viewer-control-btn ${transparency ? "active" : ""}`}
          onClick={() => setTransparency(!transparency)}
          title="Toggle Transparency"
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="12" cy="12" r="10" strokeDasharray="4 2" />
            <circle cx="12" cy="12" r="4" />
          </svg>
        </button>
        <button
          className={`rigo-viewer-control-btn ${showGrid ? "active" : ""}`}
          onClick={() => setShowGrid(!showGrid)}
          title="Toggle Grid"
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
            <line x1="3" y1="9" x2="21" y2="9" />
            <line x1="3" y1="15" x2="21" y2="15" />
            <line x1="9" y1="3" x2="9" y2="21" />
            <line x1="15" y1="3" x2="15" y2="21" />
          </svg>
        </button>
      </div>
    </>
  );
}
