import { useMemo } from "react";
import { DoubleSide, Vector2 } from "three";
import { Html } from "@react-three/drei";
import ExtrudePolygon from "../../../wrappers/geomentry/extrudePolygon";
import * as Constants from "../../../../../types/world/worldConstants";
import getCenteroid from "../../../functions/getCenteroid";
import getArea from "../../../functions/getArea";

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

    const points2D = useMemo(() => {
        return zone.points.map((p) => new Vector2(parseFloat(p.position[0].toFixed(2)), parseFloat(p.position[2].toFixed(2))));
    }, [zone]);

    const area = useMemo(() => getArea(points2D), [points2D]);

    const centroid: [number, number, number] = useMemo(() => {
        const center = getCenteroid(points2D);
        if (!center) return [0, Constants.floorConfig.height, 0];

        return [center.x, Constants.floorConfig.height, center.y] as [number, number, number];
    }, [points2D]);

    const formattedArea = `${area.toFixed(2)} m²`;

    return (
        <>
            <ExtrudePolygon points={zone.points} options={{ depth: 0, bevelEnabled: false }} position={[0, 0.05, 0]} castShadow receiveShadow name={`Zone-2D-${zone.zoneUuid}`} userData={zone}>
                <meshBasicMaterial color={savedTheme === "dark" ? Constants.lineConfig.zoneColor : Constants.lineConfig.zoneColor} side={DoubleSide} transparent opacity={0.4} depthWrite={false} />
            </ExtrudePolygon>

            <Html key={zone.zoneUuid} position={centroid} wrapperClass="distance-text-wrapper" className="distance-text" zIndexRange={[1, 0]} prepend center sprite>
                <div className="distance area">
                    {zone.zoneName} ({formattedArea})
                </div>
            </Html>
        </>
    );
}

export default Zone2DInstance;
