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

function Zone2DInstance({ zone }: { zone: Zone }) {
    const savedTheme: string | null = localStorage.getItem("theme");

    const shape = useMemo(() => {
        const shape = new Shape();
        const points = zone.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;
    }, [zone]);

    if (!shape) return null;

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

export default Zone2DInstance;