import { useRef, useMemo } from "react";
import { MaterialModel } from "../../../materials/instances/material/materialModel";
import { Object3D, Box3, Vector3 } from "three";
import { useThree } from "@react-three/fiber";
import { useLoadingProgress } from "../../../../../store/builder/store";

const MaterialAnimator = ({
  storage,
}: Readonly<{ storage: StorageUnitStatus }>) => {
  const meshRef = useRef<any>(null!);
  const { scene } = useThree();
  const padding = 0.1;
  const { loadingProgress } = useLoadingProgress();

  const storageModel = useMemo(() => {
    return scene.getObjectByProperty("uuid", storage.modelUuid) as Object3D;
  }, [scene, storage.modelUuid, loadingProgress]);

  const materialPositions = useMemo(() => {
    if (!storageModel || storage.currentMaterials.length === 0) return [];

    const box = new Box3().setFromObject(storageModel);
    const size = new Vector3();
    box.getSize(size);

    const matCount = storage.currentMaterials.length;

    // Assumed size each material needs in world units
    const materialWidth = 0.45;
    const materialDepth = 0.45;
    const materialHeight = 0.3;

    const cols = Math.floor(size.x / materialWidth);
    const rows = Math.floor(size.z / materialDepth);
    const itemsPerLayer = cols * rows;

    const origin = new Vector3(
      box.min.x + materialWidth / 2,
      box.max.y + padding, // slightly above the surface
      box.min.z + materialDepth / 2
    );

    return Array.from({ length: matCount }, (_, i) => {
      const layer = Math.floor(i / itemsPerLayer);
      const layerIndex = i % itemsPerLayer;
      const row = Math.floor(layerIndex / cols);
      const col = layerIndex % cols;

      return new Vector3(
        origin.x + col * materialWidth,
        origin.y + layer * (materialHeight + padding),
        origin.z + row * materialDepth
      );
    });
  }, [storageModel, storage.currentMaterials]);

  return (
    <group {...{ position: [0, -padding, 0] }}>
      {storage.currentMaterials.map((mat, index) => (
        <MaterialModel
          key={`${index}-${mat.materialId}`}
          materialId={mat.materialId}
          matRef={meshRef}
          materialType={mat.materialType ?? "Default material"}
          position={materialPositions[index]}
        />
      ))}
    </group>
  );
};

export default MaterialAnimator;
