import { useGLTF } from '@react-three/drei'
import { useMemo } from 'react';
import * as THREE from 'three';

import defaultMaterial from '../../../../../assets/gltf-glb/materials/default.glb';
import material1 from '../../../../../assets/gltf-glb/materials/material1.glb';
import material2 from '../../../../../assets/gltf-glb/materials/material2.glb';
import material3 from '../../../../../assets/gltf-glb/materials/material3.glb';

const modelPaths: Record<string, string> = {
    'Default material': defaultMaterial,
    'Material 1': material1,
    'Material 2': material2,
    'Material 3': material3,
};

type ModelType = keyof typeof modelPaths;

interface ModelProps extends React.ComponentProps<'group'> {
    materialId: string;
    materialType: ModelType;
    matRef: React.Ref<THREE.Group<THREE.Object3DEventMap>>
}

export function MaterialModel({ materialId, materialType, matRef, ...props }: Readonly<ModelProps>) {
    const path = modelPaths[materialType] || modelPaths['Default material'];
    const gltf = useGLTF(path);
    const cloned = useMemo(() => gltf?.scene.clone(), [gltf]);

    if (!cloned) return null;

    return (
        <group uuid={materialId} ref={matRef} {...props} dispose={null}>
            <primitive
                object={cloned}
                scale={[0.4, 0.4, 0.4]}
            />
        </group>
    );
}

Object.values(modelPaths).forEach((path) => {
    useGLTF.preload(path);
});