import * as THREE from 'three';
import { useMemo, useRef } from 'react';
import { Extrude } from '@react-three/drei';
import * as Constants from '../../../../../../types/world/worldConstants';
import { useToolMode } from '../../../../../../store/builder/store';
import { useBuilderStore } from '../../../../../../store/builder/useBuilderStore';

function CircleAisle({ aisle }: { readonly aisle: Aisle }) {
    const aisleRef = useRef<THREE.Group>(null);
    const { toolMode } = useToolMode();
    const { setSelectedAisle, hoveredPoint } = useBuilderStore();

    const circle = useMemo(() => {
        if (aisle.points.length < 2 || aisle.type.aisleType !== 'circle-aisle') return null;

        const center = new THREE.Vector3(...aisle.points[0].position);
        const widthCenter = new THREE.Vector3(...aisle.points[1].position);
        const width = aisle.type.aisleWidth || 0.1;

        const middleRadius = center.distanceTo(widthCenter);

        const innerRadius = Math.max(0, middleRadius - width / 2);
        const outerRadius = middleRadius + width / 2;

        const shape = new THREE.Shape();
        shape.absarc(center.x, center.z, outerRadius, 0, Math.PI * 2, false);

        if (innerRadius > 0) {
            const hole = new THREE.Path();
            hole.absarc(center.x, center.z, innerRadius, 0, Math.PI * 2, true);
            shape.holes.push(hole);
        }

        return {
            shape,
            rotationY: 0
        };
    }, [aisle]);

    const handleClick = () => {
        if (toolMode === 'move' && !hoveredPoint) {
            setSelectedAisle(aisleRef.current);
        }
    }

    if (!circle) return null;

    return (
        <group
            name='Circle-Aisle'
            uuid={aisle.aisleUuid}
            ref={aisleRef}
            position={[0, (aisle.points[0].layer - 1) * Constants.wallConfig.height + 0.01, 0]}
            rotation={[Math.PI / 2, 0, 0]}
            userData={aisle}
            onDoubleClick={handleClick}
            onPointerMissed={() => {
                setSelectedAisle(null);
            }}
        >
            <Extrude
                args={[circle.shape, {
                    depth: 0.01,
                    bevelEnabled: false,
                    steps: 1,
                    curveSegments: 64
                }]}
                receiveShadow
                castShadow
            >
                <meshStandardMaterial
                    color={aisle.type.aisleColor || '#ffffff'}
                    side={THREE.DoubleSide}
                />
            </Extrude>
        </group>
    );
}

export default CircleAisle;