import { useMemo } from 'react'
import { Color, DoubleSide, ShaderMaterial } from 'three';
import { Vector3 } from 'three';

function ZoneInstance({ zone }: { zone: Zone }) {
    const zoneLayer = zone.points[0].layer;

    const zoneMaterial = useMemo(() => {
        return new ShaderMaterial({
            side: DoubleSide,
            vertexShader: `
                    varying vec2 vUv;
                    void main(){
                        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
                        vUv = uv;
                    }
                `,
            fragmentShader: `
                    varying vec2 vUv;
                    uniform vec3 uOuterColor;
                    void main(){
                        float alpha = 1.0 - vUv.y;
                        gl_FragColor = vec4(uOuterColor, alpha);
                    }
                `,
            uniforms: {
                uOuterColor: { value: new Color(zone.zoneColor) },
            },
            transparent: true,
            depthWrite: false,
        })
    }, []);

    return (
        <>
            <mesh
                name={`Zone-${zone.zoneUuid}`}
                userData={zone}
            >
                {zone.points.map((point, index: number) => {
                    const nextPoint = zone.points[(index + 1) % zone.points.length];

                    const point1 = new Vector3(point.position[0], point.position[1], point.position[2]);
                    const point2 = new Vector3(nextPoint.position[0], nextPoint.position[1], nextPoint.position[2]);

                    const planeWidth = point1.distanceTo(point2);
                    const planeHeight = zone.zoneHeight;

                    const midpoint = new Vector3((point1.x + point2.x) / 2, zone.zoneHeight / 2 + (zoneLayer - 1) * zone.zoneHeight, (point1.z + point2.z) / 2);

                    const angle = Math.atan2(point2.z - point1.z, point2.x - point1.x);

                    return (
                        <mesh
                            key={index}
                            position={midpoint}
                            rotation={[0, -angle, 0]}
                        >
                            <planeGeometry args={[planeWidth, planeHeight]} />
                            <primitive
                                object={zoneMaterial.clone()}
                                attach="material"
                            />
                        </mesh>
                    );
                })}

            </ mesh>
        </>
    )
}

export default ZoneInstance