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 getCenteroidPoint from "../../../functions/getCenteroid";
import getArea from "../../../functions/getArea";

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 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 = getCenteroidPoint(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={`Floor-2D-${floor.floorUuid}`} rotation={[Math.PI / 2, 0, 0]} position={[0, 0, 0]} userData={floor}>
                <Extrude name={`Floor-${floor.floorUuid}`} args={[shape, { depth: Constants.floorConfig.height }]} userData={floor}>
                    <meshBasicMaterial
                        color={savedTheme === "dark" ? Constants.lineConfig.floorColor : Constants.lineConfig.floorColor}
                        side={DoubleSide}
                        transparent
                        opacity={0.4}
                        depthWrite={false}
                    />
                </Extrude>
            </mesh>

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