import { useMemo } from 'react';
import { DoubleSide, Shape, Vector2 } from 'three';
import { Extrude } from '@react-three/drei';
import * as Constants from '../../../../../types/world/worldConstants';

function Floor2DInstance({ floor }: { floor: Floor }) {
    const savedTheme: string | null = localStorage.getItem("theme");

    const shape = useMemo(() => {
        const shape = new Shape();
        const points = floor.points.map(p => new Vector2(p.position[0], p.position[2]));
        if (points.length < 3) return null;
        shape.moveTo(points[0].x, points[0].y);
        for (let i = 1; i < points.length; i++) {
            shape.lineTo(points[i].x, points[i].y);
        }
        return shape;
    }, [floor]);

    if (!shape) return null;

    return (
        <mesh
            castShadow
            receiveShadow
            name={`Floor-2D-${floor.floorUuid}`}
            rotation={[Math.PI / 2, 0, 0]}
            position={[0, 0, 0]}
            userData={floor}
        >
            <Extrude
                name={`Floor-${floor.floorUuid}`}
                args={[shape, {
                    depth: Constants.floorConfig.height,
                }]}
                userData={floor}
            >
                <meshBasicMaterial
                    color={savedTheme === "dark" ? "#d2baff" : "#6f42c1"}
                    side={DoubleSide}
                    transparent
                    opacity={0.4}
                    depthWrite={false}
                />
            </Extrude>
        </mesh>
    );
}

export default Floor2DInstance;