import { useMemo } from "react";
import { DoubleSide, Shape, Vector2 } from "three";
import { Extrude, Html } from "@react-three/drei";
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 shape = useMemo(() => {
        const shape = new Shape();
        shape.moveTo(points2D[0].x, points2D[0].y);
        for (let i = 1; i < points2D.length; i++) {
            shape.lineTo(points2D[i].x, points2D[i].y);
        }
        shape.lineTo(points2D[0].x, points2D[0].y);
        return shape;
    }, [points2D]);

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

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

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

    if (!shape) return null;

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

    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" ? Constants.lineConfig.zoneColor : Constants.lineConfig.zoneColor} side={DoubleSide} transparent opacity={0.4} depthWrite={false} />
                </Extrude>
            </mesh>

            <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;
