import { useLoader } from "@react-three/fiber";
import { TextureLoader } from "three";
import { DoubleSide } from "three";
import Chair from "./Chair.jsx";

export default function Desk({ position = [0, 0, 0], nameplateColor = "#52b6ff", onSelect }) {
  const appleLogoTexture = useLoader(TextureLoader, "/apple-logo.png");

  return (
    <group
      position={position}
      onPointerDown={(event) => {
        event.stopPropagation();
        onSelect?.();
      }}
    >
      <mesh position={[0, 0.72, -0.08]}>
        <boxGeometry args={[2.1, 1.5, 2.1]} />
        <meshBasicMaterial transparent opacity={0} />
      </mesh>
      <mesh castShadow receiveShadow position={[0, 0.78, 0]}>
        <boxGeometry args={[1.9, 0.16, 1.15]} />
        <meshStandardMaterial color="#b78256" roughness={0.86} />
      </mesh>
      {[
        [-0.78, 0.38, -0.43],
        [0.78, 0.38, -0.43],
        [-0.78, 0.38, 0.43],
        [0.78, 0.38, 0.43]
      ].map((leg, index) => (
        <mesh key={index} castShadow receiveShadow position={leg}>
          <boxGeometry args={[0.12, 0.76, 0.12]} />
          <meshStandardMaterial color="#8e603b" roughness={0.9} />
        </mesh>
      ))}

      <group position={[0, 0.92, 0]} rotation={[0, Math.PI, 0]}>
        <mesh castShadow receiveShadow position={[0, 0.02, 0.02]}>
          <boxGeometry args={[0.64, 0.04, 0.42]} />
          <meshStandardMaterial color="#c3c9d2" roughness={0.36} metalness={0.52} />
        </mesh>
        <group position={[0, 0.055, -0.19]} rotation={[-Math.PI / 2, 0, 0]}>
          <mesh castShadow receiveShadow position={[0, 0, 0.2]}>
            <boxGeometry args={[0.62, 0.03, 0.4]} />
            <meshStandardMaterial color="#c8ced6" roughness={0.28} metalness={0.58} />
          </mesh>
          <mesh position={[0, 0.022, 0.2]} rotation={[-Math.PI / 2, 0, Math.PI]}>
            <planeGeometry args={[0.18, 0.18]} />
            <meshBasicMaterial
              map={appleLogoTexture}
              transparent
              alphaTest={0.1}
              side={DoubleSide}
              toneMapped={false}
            />
          </mesh>
        </group>
      </group>

      <mesh castShadow receiveShadow position={[0.65, 0.9, 0.18]}>
        <boxGeometry args={[0.26, 0.1, 0.26]} />
        <meshStandardMaterial color={nameplateColor} roughness={0.55} />
      </mesh>
      <Chair position={[0, 0, -1.05]} />
    </group>
  );
}
