
import React, { useRef, useMemo } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { OrbitControls, Grid, PerspectiveCamera, Text, Box, Environment, RoundedBox } from '@react-three/drei';
import * as THREE from 'three';
import { RobotTarget, IOPoint } from '../types';

interface Machine3DProps {
  target: RobotTarget;
  ioState: IOPoint[];
  doorStates: {
    front: boolean;
    right: boolean;
    left: boolean;
    back: boolean;
  };
}

// -- Parts Components --

const TowerLamp = ({ ioState }: { ioState: IOPoint[] }) => {
  // Outputs 0,1,2 mapped to Red, Yellow, Green
  const redOn = ioState.find(io => io.id === 0 && io.type === 'output')?.state;
  const yellowOn = ioState.find(io => io.id === 1 && io.type === 'output')?.state;
  const greenOn = ioState.find(io => io.id === 2 && io.type === 'output')?.state;

  const redMat = useRef<THREE.MeshStandardMaterial>(null);
  const yelMat = useRef<THREE.MeshStandardMaterial>(null);
  const grnMat = useRef<THREE.MeshStandardMaterial>(null);

  useFrame((state) => {
    const time = state.clock.elapsedTime;
    const pulse = (Math.sin(time * 6) * 0.5 + 0.5); 
    const intensity = 0.5 + (pulse * 3.0);

    if (redMat.current) {
      redMat.current.emissiveIntensity = redOn ? intensity : 0;
      redMat.current.opacity = redOn ? 1.0 : 0.3;
      redMat.current.color.setHex(redOn ? 0xff0000 : 0x550000); 
    }
    if (yelMat.current) {
      yelMat.current.emissiveIntensity = yellowOn ? intensity : 0;
      yelMat.current.opacity = yellowOn ? 1.0 : 0.3;
      yelMat.current.color.setHex(yellowOn ? 0xffff00 : 0x555500);
    }
    if (grnMat.current) {
      grnMat.current.emissiveIntensity = greenOn ? intensity : 0;
      grnMat.current.opacity = greenOn ? 1.0 : 0.3;
      grnMat.current.color.setHex(greenOn ? 0x00ff00 : 0x005500);
    }
  });

  return (
    <group position={[1.8, 2.5, -1.8]}>
      {/* Pole */}
      <mesh position={[0, 0, 0]}>
        <cylinderGeometry args={[0.05, 0.05, 0.5]} />
        <meshStandardMaterial color="#333" roughness={0.5} />
      </mesh>
      {/* Green */}
      <mesh position={[0, 0.3, 0]}>
        <cylinderGeometry args={[0.08, 0.08, 0.15]} />
        <meshStandardMaterial 
          ref={grnMat}
          color="#00ff00" 
          emissive="#00ff00" 
          transparent 
          toneMapped={false} 
        />
      </mesh>
      {/* Yellow */}
      <mesh position={[0, 0.46, 0]}>
        <cylinderGeometry args={[0.08, 0.08, 0.15]} />
        <meshStandardMaterial 
          ref={yelMat}
          color="#ffff00" 
          emissive="#ffff00" 
          transparent 
          toneMapped={false}
        />
      </mesh>
      {/* Red */}
      <mesh position={[0, 0.62, 0]}>
        <cylinderGeometry args={[0.08, 0.08, 0.15]} />
        <meshStandardMaterial 
          ref={redMat}
          color="#ff0000" 
          emissive="#ff0000" 
          transparent 
          toneMapped={false}
        />
      </mesh>
    </group>
  );
};

// -- DIPPING STATION COMPONENTS --

const LiquidBath = ({ 
  position, 
  label, 
  liquidColor, 
}: { 
  position: [number, number, number], 
  label: string, 
  liquidColor: string, 
}) => {
  const width = 1.0;
  const depth = 0.8;
  const height = 0.3;
  const wallThick = 0.03;

  const SteelMaterial = (
    <meshStandardMaterial color="#e2e8f0" metalness={0.95} roughness={0.2} />
  );

  return (
    <group position={position}>
      <group position={[0, height / 2, 0]}>
        <mesh position={[0, -height/2 + wallThick/2, 0]}>
           <boxGeometry args={[width, wallThick, depth]} />
           {SteelMaterial}
        </mesh>
        <mesh position={[0, 0, depth/2 - wallThick/2]}>
           <boxGeometry args={[width, height, wallThick]} />
           {SteelMaterial}
        </mesh>
        <mesh position={[0, 0, -depth/2 + wallThick/2]}>
           <boxGeometry args={[width, height, wallThick]} />
           {SteelMaterial}
        </mesh>
        <mesh position={[-width/2 + wallThick/2, 0, 0]}>
           <boxGeometry args={[wallThick, height, depth - wallThick*2]} />
           {SteelMaterial}
        </mesh>
        <mesh position={[width/2 - wallThick/2, 0, 0]}>
           <boxGeometry args={[wallThick, height, depth - wallThick*2]} />
           {SteelMaterial}
        </mesh>
        <mesh position={[0, height/2 - 0.05, 0]} rotation={[-Math.PI / 2, 0, 0]}>
          <planeGeometry args={[width - wallThick*2, depth - wallThick*2]} />
          <meshPhysicalMaterial 
            color={liquidColor}
            transparent
            opacity={0.85}
            roughness={0.05}
            metalness={0.2}
            transmission={0.4}
            thickness={1}
            clearcoat={1}
          />
        </mesh>
      </group>
      <Text 
        position={[0, 0.6, 0.55]} 
        fontSize={0.12} 
        color="white" 
        anchorX="center" 
        anchorY="middle"
        rotation={[-Math.PI/4, 0, 0]}
      >
        {label}
      </Text>
    </group>
  );
};

const HakkoFX305 = ({ position }: { position: [number, number, number] }) => {
  return (
    <group position={position}>
       {/* Main Blue Chassis */}
       <mesh position={[0, 0.25, 0]}>
          <boxGeometry args={[1.3, 0.55, 1.0]} /> 
          <meshStandardMaterial color="#2563eb" metalness={0.1} roughness={0.4} /> 
       </mesh>
       
       <mesh position={[-0.66, 0.25, 0]}>
          <boxGeometry args={[0.02, 0.3, 0.6]} />
          <meshStandardMaterial color="#1e3a8a" />
       </mesh>
       <mesh position={[0.66, 0.25, 0]}>
          <boxGeometry args={[0.02, 0.3, 0.6]} />
          <meshStandardMaterial color="#1e3a8a" />
       </mesh>

       <mesh position={[0, 0.25, 0.51]}>
          <planeGeometry args={[1.25, 0.5]} />
          <meshStandardMaterial color="#cbd5e1" metalness={0.6} roughness={0.3} />
       </mesh>

       <Text 
          position={[0, 0.42, 0.52]} 
          fontSize={0.08} 
          color="#2563eb" 
          anchorX="center" 
          anchorY="middle"
          fontWeight="bold"
        >
          HAKKO
        </Text>
        <Text 
          position={[0.5, 0.42, 0.52]} 
          fontSize={0.04} 
          color="#64748b" 
          anchorX="right" 
          anchorY="middle"
        >
          FX-305
        </Text>

       <mesh position={[0.15, 0.25, 0.52]}>
          <planeGeometry args={[0.35, 0.15]} />
          <meshStandardMaterial color="#0f172a" roughness={0.2} />
       </mesh>
       
       <group position={[-0.45, 0.25, 0.52]} rotation={[Math.PI/2, 0, 0]}>
          <mesh>
            <cylinderGeometry args={[0.08, 0.08, 0.02, 32]} />
            <meshStandardMaterial color="#1e293b" />
          </mesh>
          <mesh position={[0, 0.02, 0]} rotation={[0, 0, Math.PI/2]}>
             <boxGeometry args={[0.02, 0.08, 0.01]} />
             <meshStandardMaterial color="#475569" />
          </mesh>
       </group>

       <group position={[0.15, 0.12, 0.52]}>
          {[-0.12, 0, 0.12, 0.24].map((x, i) => (
             <mesh key={i} position={[x, 0, 0]} rotation={[Math.PI/2, 0, 0]}>
                <cylinderGeometry args={[0.035, 0.035, 0.02, 16]} />
                <meshStandardMaterial color="#facc15" />
             </mesh>
          ))}
       </group>

       <mesh position={[0, 0.55, 0]}>
          <boxGeometry args={[0.9, 0.05, 0.7]} />
          <meshStandardMaterial color="#94a3b8" metalness={0.8} roughness={0.3} />
       </mesh>

       <group position={[0, 0.58, 0]}>
          <mesh position={[0, 0, -0.3]}>
             <boxGeometry args={[0.8, 0.05, 0.05]} />
             <meshStandardMaterial color="#64748b" metalness={0.7} />
          </mesh>
          <mesh position={[0, 0, 0.3]}>
             <boxGeometry args={[0.8, 0.05, 0.05]} />
             <meshStandardMaterial color="#64748b" metalness={0.7} />
          </mesh>
          <mesh position={[-0.4, 0, 0]}>
             <boxGeometry args={[0.05, 0.05, 0.65]} />
             <meshStandardMaterial color="#64748b" metalness={0.7} />
          </mesh>
          <mesh position={[0.4, 0, 0]}>
             <boxGeometry args={[0.05, 0.05, 0.65]} />
             <meshStandardMaterial color="#64748b" metalness={0.7} />
          </mesh>
       </group>

       <mesh position={[0, 0.57, 0]} rotation={[-Math.PI / 2, 0, 0]}>
         <planeGeometry args={[0.75, 0.6]} />
         <meshPhysicalMaterial 
           color="#e2e8f0" 
           emissive="#cbd5e1"
           emissiveIntensity={0.1}
           roughness={0.02}
           metalness={1.0}
           clearcoat={1}
           reflectivity={1}
         />
       </mesh>

       <Text 
          position={[0, 0.9, 0.6]} 
          fontSize={0.15} 
          color="#fbbf24" 
          anchorX="center" 
          anchorY="middle"
          rotation={[-Math.PI/4, 0, 0]}
        >
          2. HAKKO SOLDER
        </Text>
    </group>
  );
};

const DippingStations = () => {
  return (
    <group>
      <mesh position={[0, 0.2, 0]}>
        <boxGeometry args={[4.5, 0.4, 1.5]} />
        <meshStandardMaterial color="#334155" roughness={0.5} metalness={0.5} />
      </mesh>
      <LiquidBath position={[-1.5, 0.4, 0]} label="1. FLUX" liquidColor="#fef08a" />
      <HakkoFX305 position={[0, 0.4, 0]} />
      <LiquidBath position={[1.5, 0.4, 0]} label="3. CLEAN" liquidColor="#bae6fd" />
    </group>
  );
};

const Door = ({ 
  position, 
  rotation = [0,0,0], 
  size, 
  isOpen 
}: { 
  position: [number, number, number], 
  rotation?: [number, number, number],
  size: [number, number], 
  isOpen: boolean 
}) => {
  const meshRef = useRef<THREE.Mesh>(null);

  useFrame((state, delta) => {
    if (!meshRef.current) return;
    const targetY = isOpen ? position[1] + 2 : position[1];
    meshRef.current.position.y = THREE.MathUtils.lerp(meshRef.current.position.y, targetY, delta * 5);
  });

  return (
    <mesh ref={meshRef} position={position} rotation={rotation as any}>
      <planeGeometry args={[size[0], size[1]]} />
      <meshPhysicalMaterial 
        color="#a5f3fc" 
        transparent 
        opacity={0.2} 
        roughness={0} 
        metalness={0.9} 
        side={THREE.DoubleSide} 
        depthWrite={false} 
      />
      <mesh position={[size[0]/2 - 0.1, 0, 0.02]}>
         <boxGeometry args={[0.05, size[1], 0.05]} />
         <meshStandardMaterial color="#cbd5e1" />
      </mesh>
      <mesh position={[-size[0]/2 + 0.1, 0, 0.02]}>
         <boxGeometry args={[0.05, size[1], 0.05]} />
         <meshStandardMaterial color="#cbd5e1" />
      </mesh>
    </mesh>
  );
};

const MachineFrame = ({ doorStates }: { doorStates: { front: boolean, right: boolean, left: boolean, back: boolean } }) => {
  return (
    <group>
      <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -0.05, 0]}>
        <planeGeometry args={[6, 6]} />
        <meshStandardMaterial color="#0f172a" roughness={0.8} metalness={0.2} />
      </mesh>
      <Grid infiniteGrid fadeDistance={15} sectionColor="#475569" cellColor="#1e293b" />
      
      {[[-2, -2], [2, -2], [2, 2], [-2, 2]].map(([x, z], i) => (
        <mesh key={i} position={[x, 1.5, z]}>
          <boxGeometry args={[0.15, 3, 0.15]} />
          <meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
        </mesh>
      ))}

      <group position={[0, 3, 0]}>
        <mesh position={[0, 0, -2]}>
            <boxGeometry args={[4.15, 0.15, 0.15]} />
            <meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
        </mesh>
        <mesh position={[0, 0, 2]}>
            <boxGeometry args={[4.15, 0.15, 0.15]} />
            <meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
        </mesh>
        <mesh position={[-2, 0, 0]}>
            <boxGeometry args={[0.15, 0.15, 4.15]} />
            <meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
        </mesh>
        <mesh position={[2, 0, 0]}>
            <boxGeometry args={[0.15, 0.15, 4.15]} />
            <meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
        </mesh>
      </group>

      <Door position={[0, 1.5, 2]} size={[4, 3]} isOpen={doorStates.front} />
      <Door position={[0, 1.5, -2]} size={[4, 3]} isOpen={doorStates.back} />
      <Door position={[-2, 1.5, 0]} rotation={[0, Math.PI/2, 0]} size={[4, 3]} isOpen={doorStates.left} />
      <Door position={[2, 1.5, 0]} rotation={[0, Math.PI/2, 0]} size={[4, 3]} isOpen={doorStates.right} />
      <DippingStations />
    </group>
  );
};

// --- MISUMI STYLE INDUSTRIAL ACTUATOR COMPONENT ---

const IndustrialActuatorRail = ({ length, label, hasMotor = true }: { length: number, label?: string, hasMotor?: boolean }) => {
  const width = 0.14; // Actuator Width
  const height = 0.08; // Actuator Height (Profile)

  return (
    <group>
      {/* 1. Main Aluminum Body (White/Light Grey Matte) */}
      <RoundedBox args={[width, height, length]} radius={0.01} smoothness={4}>
         <meshStandardMaterial color="#f8fafc" roughness={0.8} metalness={0.1} />
      </RoundedBox>

      {/* 2. Top Stainless Steel Cover Strip */}
      <mesh position={[0, height/2 + 0.001, 0]}>
         <boxGeometry args={[width * 0.7, 0.002, length]} />
         <meshStandardMaterial color="#cbd5e1" metalness={0.9} roughness={0.2} />
      </mesh>
      
      {/* 3. Black Gap/Slit for Slider */}
      <mesh position={[0, height/2, 0]}>
         <boxGeometry args={[width * 0.8, 0.01, length * 0.98]} />
         <meshStandardMaterial color="#0f172a" roughness={0.9} />
      </mesh>

      {/* 4. End Caps (Plastic White) */}
      <group position={[0, 0, length/2 + 0.02]}>
         <RoundedBox args={[width + 0.01, height + 0.01, 0.04]} radius={0.02} smoothness={4}>
            <meshStandardMaterial color="#e2e8f0" />
         </RoundedBox>
      </group>
      <group position={[0, 0, -length/2 - 0.02]}>
         <RoundedBox args={[width + 0.01, height + 0.01, 0.04]} radius={0.02} smoothness={4}>
            <meshStandardMaterial color="#e2e8f0" />
         </RoundedBox>
      </group>

      {/* 5. Servo Motor Unit (Black & Silver) */}
      {hasMotor && (
        <group position={[0, 0, -length/2 - 0.15]}>
           {/* Flange */}
           <mesh position={[0, 0, 0.08]}>
              <boxGeometry args={[0.12, 0.12, 0.05]} />
              <meshStandardMaterial color="#475569" metalness={0.8} />
           </mesh>
           {/* Motor Body */}
           <mesh position={[0, 0, 0]} rotation={[Math.PI/2, 0, 0]}>
              <cylinderGeometry args={[0.05, 0.05, 0.2, 32]} />
              <meshStandardMaterial color="#1e293b" metalness={0.6} roughness={0.4} />
           </mesh>
           {/* Encoder Cap */}
           <mesh position={[0, 0, -0.11]} rotation={[Math.PI/2, 0, 0]}>
              <cylinderGeometry args={[0.045, 0.045, 0.05, 32]} />
              <meshStandardMaterial color="#000000" />
           </mesh>
           {/* Cable Gland */}
           <mesh position={[0, 0.04, -0.05]}>
              <boxGeometry args={[0.03, 0.03, 0.03]} />
              <meshStandardMaterial color="#333" />
           </mesh>
        </group>
      )}

      {/* 6. Label/Branding */}
      {label && (
        <Text 
           position={[width/2 + 0.01, 0, length/2 - 0.2]} 
           rotation={[0, Math.PI/2, 0]}
           fontSize={0.06}
           color="#334155"
           fontWeight="bold"
           anchorX="right"
        >
           {label}
        </Text>
      )}
    </group>
  );
}

// The Moving Block on top of the actuator
const IndustrialSlider = ({ width = 0.16, length = 0.18, height = 0.03 }) => {
  return (
    <group position={[0, 0.06, 0]}>
      <RoundedBox args={[width, height, length]} radius={0.005} smoothness={2}>
         <meshStandardMaterial color="#f1f5f9" metalness={0.4} roughness={0.5} />
      </RoundedBox>
      {/* Mounting Holes (Visual) */}
      {[-1, 1].map(x => [-1, 1].map(z => (
         <mesh key={`${x}-${z}`} position={[x * 0.06, height/2 + 0.001, z * 0.07]} rotation={[Math.PI/2, 0, 0]}>
            <circleGeometry args={[0.008, 16]} />
            <meshStandardMaterial color="#94a3b8" />
         </mesh>
      )))}
    </group>
  )
}

// -- MAIN ROBOT ASSEMBLY --

const Robot = ({ target }: { target: RobotTarget }) => {
  const bridgeGroup = useRef<THREE.Group>(null); 
  const carriageGroup = useRef<THREE.Group>(null);
  const zAxisGroup = useRef<THREE.Group>(null);

  useFrame((state, delta) => {
    if (bridgeGroup.current) {
      // Y-Axis Movement
      bridgeGroup.current.position.z = THREE.MathUtils.lerp(bridgeGroup.current.position.z, target.y, delta * 3);
    }
    if (carriageGroup.current) {
      // X-Axis Movement
      carriageGroup.current.position.x = THREE.MathUtils.lerp(carriageGroup.current.position.x, target.x, delta * 3);
    }
    if (zAxisGroup.current) {
      // Z-Axis Movement
      zAxisGroup.current.position.y = THREE.MathUtils.lerp(zAxisGroup.current.position.y, target.z, delta * 3);
    }
  });

  return (
    <group position={[0, 2.0, 0]}> 
      
      {/* --- Y-AXIS (Left & Right Fixed Actuators) --- */}
      <group>
        <group position={[-1.8, 0, 0]}>
          <IndustrialActuatorRail length={3.8} label="MISUMI-Y1" />
        </group>
        <group position={[1.8, 0, 0]}>
           <IndustrialActuatorRail length={3.8} label="MISUMI-Y2" />
        </group>
      </group>

      {/* --- MOVING BRIDGE (Y-AXIS CARRIAGE + X-AXIS ACTUATOR) --- */}
      <group ref={bridgeGroup}>
        
        {/* Y-Sliders (Connecting Bridge to Y-Rails) */}
        <group position={[-1.8, 0, 0]}> <IndustrialSlider /> </group>
        <group position={[1.8, 0, 0]}> <IndustrialSlider /> </group>
        
        {/* Bridge Beam Structure */}
        <mesh position={[0, 0.08, 0]}>
          <boxGeometry args={[4.2, 0.05, 0.25]} />
          <meshStandardMaterial color="#cbd5e1" metalness={0.6} roughness={0.4} /> 
        </mesh>

        {/* X-AXIS ACTUATOR (Mounted on top of Bridge) */}
        <group position={[0, 0.14, 0]} rotation={[0, Math.PI/2, 0]}>
           <IndustrialActuatorRail length={3.4} label="MISUMI-X" hasMotor />
        </group>

        {/* --- MOVING CARRIAGE (X-AXIS SLIDER + Z-AXIS) --- */}
        <group ref={carriageGroup}>
          
          {/* X-Slider */}
          <group position={[0, 0.14, 0]} rotation={[0, Math.PI/2, 0]}>
             <IndustrialSlider />
          </group>

          {/* --- Z-AXIS ACTUATOR (Vertical) --- */}
          <group position={[0, 0.2, 0.12]}> 
             {/* Z-Actuator Body (Fixed to X-Slider) */}
             <group position={[0, 0.4, 0]} rotation={[Math.PI/2, 0, 0]}>
                <IndustrialActuatorRail length={0.8} label="MISUMI-Z" hasMotor={false} />
                {/* Z-Motor on Top */}
                <group position={[0, 0, 0.4 + 0.15]} rotation={[0, Math.PI, 0]}>
                    <mesh position={[0, 0, -0.05]} rotation={[Math.PI/2, 0, 0]}>
                       <boxGeometry args={[0.1, 0.1, 0.12]} />
                       <meshStandardMaterial color="#0f172a" />
                    </mesh>
                </group>
             </group>

             {/* MOVING Z-HEAD (The Slider of Z-Axis) */}
             <group ref={zAxisGroup}>
                <group position={[0, 0, 0.08]}>
                   {/* Connection Plate */}
                   <mesh position={[0, 0, -0.04]}>
                      <boxGeometry args={[0.12, 0.15, 0.02]} />
                      <meshStandardMaterial color="#64748b" />
                   </mesh>

                   {/* PICKER MECHANISM */}
                   <group position={[0, -0.2, 0]}>
                        <mesh position={[0, 0, 0]}>
                          <boxGeometry args={[0.3, 0.05, 0.1]} />
                          <meshStandardMaterial color="#334155" />
                        </mesh>
                        {/* Fingers */}
                        <mesh position={[-0.12, -0.15, 0]}>
                           <boxGeometry args={[0.02, 0.3, 0.05]} />
                           <meshStandardMaterial color="#94a3b8" metalness={0.8} />
                        </mesh>
                        <mesh position={[0.12, -0.15, 0]}>
                           <boxGeometry args={[0.02, 0.3, 0.05]} />
                           <meshStandardMaterial color="#94a3b8" metalness={0.8} />
                        </mesh>

                        {/* PCB STRIP */}
                        <group position={[0, -0.35, 0]}>
                           <mesh>
                              <boxGeometry args={[0.28, 0.6, 0.02]} />
                              <meshStandardMaterial color="#166534" roughness={0.3} />
                           </mesh>
                           <mesh position={[0, -0.28, 0.011]}>
                              <planeGeometry args={[0.24, 0.04]} />
                              <meshStandardMaterial color="#fbbf24" metalness={1.0} roughness={0.1} />
                           </mesh>
                           <mesh position={[0, 0, 0.011]}>
                              <planeGeometry args={[0.15, 0.15]} />
                              <meshStandardMaterial color="#0f172a" />
                           </mesh>
                        </group>
                   </group>
                </group>
             </group>
          </group>
        </group>
      </group>
    </group>
  );
};

export const Machine3D: React.FC<Machine3DProps> = ({ target, ioState, doorStates }) => {
  return (
    <Canvas shadows className="w-full h-full bg-slate-900">
      <PerspectiveCamera makeDefault position={[5, 5, 6]} fov={45} />
      <OrbitControls 
        maxPolarAngle={Math.PI / 2 - 0.05} 
        minDistance={3}
        maxDistance={12}
      />
      <Environment preset="city" />
      
      <ambientLight intensity={0.4} />
      <pointLight position={[10, 10, 10]} intensity={1} castShadow />
      <pointLight position={[-10, 5, -10]} intensity={0.5} />
      
      <pointLight position={[0, 2, 0]} intensity={0.2} color="#bae6fd" distance={5} />

      <MachineFrame doorStates={doorStates} />
      <TowerLamp ioState={ioState} />
      <Robot target={target} />
    </Canvas>
  );
};
