import React, { ForwardedRef, forwardRef, useMemo } from 'react';
import { Mesh, MeshPhysicalMaterial, Object3D, PerspectiveCamera } from 'three';
import { useGLTF } from '@react-three/drei';
import * as SkeletonUtils from 'three/examples/jsm/utils/SkeletonUtils';
import { useThree } from '@react-three/fiber';
import { fitCameraToObject } from './fitCameraToObject';
import { BufferGeometry } from 'three/src/core/BufferGeometry';

export const Model = forwardRef(({ url }: { url: string }, ref: ForwardedRef<Object3D>) => {
  const { camera } = useThree();
  const { scene } = useGLTF(url);

  const model = useMemo(() => {
    const model = (SkeletonUtils as any).clone(scene);
    model.traverse((el: Mesh<BufferGeometry, MeshPhysicalMaterial>) => {
      if (el.type === 'Mesh') {
        el.material.reflectivity = 0.0;
        el.material.fog = false;
        el.material.color.setHex(0xffffff);
      }
    });

    fitCameraToObject(camera as PerspectiveCamera, scene);
    scene.updateWorldMatrix(true, true);

    return model;
  }, [scene, camera]);

  return <primitive key={url} object={model} ref={ref} />;
});
