import React, { useMemo } from "react";
import * as THREE from "three";
import { GLTF } from "three-stdlib";
import { SpawnedObject } from "./types";

interface ProcessObjectProps {
  objectId: string;
  obj: SpawnedObject;
  renderAs?: "box" | "custom";
  gltf?: GLTF;
}

const ProcessObject: React.FC<ProcessObjectProps> = ({
  objectId,
  obj,
  renderAs = "custom",
  gltf,
}) => {
  const renderedObject = useMemo(() => {
    if (renderAs === "box") {
      return (
        <mesh
          key={objectId}
          ref={obj.ref as React.RefObject<THREE.Mesh>}
          material={obj.material}
          position={obj.position}
        >
          <boxGeometry args={[1, 1, 1]} />
        </mesh>
      );
    }

    if (gltf?.scene) {
      const clonedScene = gltf.scene.clone();
      clonedScene.traverse((child) => {
        if (child instanceof THREE.Mesh) {
          child.material = obj.material;
        }
      });

      return (
        <group
          key={objectId}
          ref={obj.ref as React.RefObject<THREE.Group>}
          position={obj.position}
        >
          <primitive object={clonedScene} />
        </group>
      );
    }

    return null;
  }, [objectId, obj, renderAs, gltf]);

  return renderedObject;
};

export default ProcessObject;
