import * as THREE from "three";
import { useMemo } from "react";
import { DragControls, Line as DreiLine } from "@react-three/drei";
import * as Constants from "../../../types/world/worldConstants";

import { useLineEventHandler } from "./eventHandler/useLineEventHandler";

interface LineProps {
    points: [Point, Point];
}

function Line({ points }: Readonly<LineProps>) {
    const path = useMemo(() => {
        const [start, end] = points.map((p) => new THREE.Vector3(...p.position));
        return new THREE.LineCurve3(start, end);
    }, [points]);
    const positions = useMemo(() => points.map((p) => new THREE.Vector3(...p.position)), [points]);
    const colors = getColor(points[0]);

    function getColor(point: Point) {
        if (point.pointType === "Aisle") {
            return {
                defaultLineColor: Constants.lineConfig.aisleColor,
                defaultDeleteColor: Constants.lineConfig.deleteColor,
            };
        } else if (point.pointType === "Floor") {
            return {
                defaultLineColor: Constants.lineConfig.floorColor,
                defaultDeleteColor: Constants.lineConfig.deleteColor,
            };
        } else if (point.pointType === "Wall") {
            return {
                defaultLineColor: Constants.lineConfig.wallColor,
                defaultDeleteColor: Constants.lineConfig.deleteColor,
            };
        } else if (point.pointType === "Zone") {
            return {
                defaultLineColor: Constants.lineConfig.zoneColor,
                defaultDeleteColor: Constants.lineConfig.deleteColor,
            };
        } else {
            return {
                defaultLineColor: Constants.lineConfig.defaultColor,
                defaultDeleteColor: Constants.lineConfig.deleteColor,
            };
        }
    }

    const { isDeletable, handleDrag, handleDragStart, handleDragEnd, handleLineClick, handlePointerOver, handlePointerOut } = useLineEventHandler({ points });

    return (
        <DragControls axisLock="y" autoTransform={false} onDragStart={handleDragStart} onDrag={handleDrag} onDragEnd={handleDragEnd}>
            <DreiLine
                name={`${points[0].pointType}-Line`}
                key={`${points[0].pointUuid}-${points[1].pointUuid}`}
                uuid={`${points[0].pointUuid}-${points[1].pointUuid}`}
                userData={{ points, path }}
                points={positions}
                lineWidth={7.5}
                color={isDeletable ? colors.defaultDeleteColor : colors.defaultLineColor}
                onClick={handleLineClick}
                onPointerOver={handlePointerOver}
                onPointerOut={handlePointerOut}
            />
        </DragControls>
    );
}

export default Line;
