import { Vector3 } from "three";
import ZoneCornerReference from "./zoneCornerReference";
import ExtrudePolygon from "../../../wrappers/geomentry/extrudePolygon";
import PlaneMaterial from "../../../wrappers/materials/planeMaterial";
import PolygonMaterial from "../../../wrappers/materials/polygonMaterial";

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

    return (
        <group name={`Zone-${zone.zoneUuid}`} userData={zone}>
            <ExtrudePolygon options={{ depth: 0, bevelEnabled: false }} points={zone.points}>
                <PolygonMaterial
                    transparent
                    depthWrite={false}
                    depthTest={true}
                    polygonOffset
                    polygonOffsetFactor={-10}
                    polygonOffsetUnits={-10}
                    points={zone.points}
                    color={zone.zoneColor}
                    variant="edge"
                />
            </ExtrudePolygon>

            {zone.points.map((point, index: number) => {
                const nextPoint = zone.points[(index + 1) % zone.points.length];
                const prevPoint = zone.points[(index - 1 + zone.points.length) % zone.points.length];

                const point1 = new Vector3(...point.position);
                const point2 = new Vector3(...nextPoint.position);

                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 (
                    <group key={index}>
                        <mesh position={midpoint} rotation={[0, -angle, 0]}>
                            <planeGeometry args={[planeWidth, planeHeight]} />
                            <PlaneMaterial transparent depthWrite={false} depthTest={true} color={zone.zoneColor} variant="plane1" />
                        </mesh>

                        <ZoneCornerReference showTop={false} showBottom={false} point={point} prevPoint={prevPoint} nextPoint={nextPoint} zone={zone} cornerThickness={0.25} />
                    </group>
                );
            })}
        </group>
    );
}

export default ZoneInstance;
