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

function Floor2DInstance({ floor }: { readonly floor: Floor }) {
    const savedTheme: string | null = localStorage.getItem("theme");

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

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

    const centroid: [number, number, number] = useMemo(() => {
        const center = getCenteroidPoint(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 castShadow receiveShadow name={`Floor-2D-${floor.floorUuid}`} position={[0, 0.05, 0]} points={floor.points} options={{ depth: 0, bevelEnabled: false }} userData={floor}>
                <meshBasicMaterial color={savedTheme === "dark" ? Constants.lineConfig.floorColor : Constants.lineConfig.floorColor} side={DoubleSide} transparent opacity={0.4} depthWrite={false} />
            </ExtrudePolygon>

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

export default Floor2DInstance;
