import React, { useEffect, useMemo } from 'react';
import { Vector3 } from 'three';
import { Html } from '@react-three/drei';
import { useSceneContext } from '../../../scene/sceneContext';
import { useToggleView } from '../../../../store/builder/store';
import Line from '../../line/line';
import Point from '../../point/point';
import ZoneInstance from './Instance/zoneInstance';
import Zone2DInstance from './Instance/zone2DInstance';

function ZoneInstances() {
    const { zoneStore } = useSceneContext();
    const { zones } = zoneStore();
    const { toggleView } = useToggleView();

    useEffect(() => {
        // console.log('zones: ', zones);
    }, [zones])

    const allPoints = useMemo(() => {
        const points: Point[] = [];
        const seenUuids = new Set<string>();

        zones.forEach(zone => {
            zone.points.forEach(point => {
                if (!seenUuids.has(point.pointUuid)) {
                    seenUuids.add(point.pointUuid);
                    points.push(point);
                }
            });
        });

        return points;
    }, [zones]);

    const allLines = useMemo(() => {
        const lines: { start: Point; end: Point; key: string }[] = [];
        const seenUuids = new Set<string>();

        zones.forEach((zone) => {
            const points = zone.points;
            if (points.length < 2) return;

            for (let i = 0; i < points.length; i++) {
                const current = points[i];
                const next = points[(i + 1) % points.length];
                const lineKey = `${current.pointUuid}-${next.pointUuid}`;
                if (current.pointUuid !== next.pointUuid && !seenUuids.has(lineKey)) {
                    seenUuids.add(lineKey);
                    lines.push({
                        start: current,
                        end: next,
                        key: lineKey
                    });
                }
            }
        });

        return lines;
    }, [zones]);

    return (
        <>

            {!toggleView && zones.length > 0 && (
                <mesh name='Zones-Group'>
                    {zones.map((zone) => (
                        <ZoneInstance key={zone.zoneUuid} zone={zone} />
                    ))}
                </mesh>
            )}

            {toggleView && zones.length > 0 && (
                <mesh name='Zones-2D-Group'>
                    {zones.map((zone) => (
                        <Zone2DInstance key={zone.zoneUuid} zone={zone} />
                    ))}
                </mesh>
            )}

            {toggleView && (
                <>
                    <group name='Zone-Points-Group'>
                        {allPoints.map((point) => (
                            <Point key={point.pointUuid} point={point} />
                        ))}
                    </group>

                    <group name='Zone-Lines-Group'>

                        {allLines.map(({ start, end, key }) => (
                            <Line key={key} points={[start, end]} />
                        ))}

                        {allLines.map((line) => {
                            const { start, end, key } = line;
                            const textPosition = new Vector3().addVectors(new Vector3(...start.position), new Vector3(...end.position)).divideScalar(2);
                            const distance = new Vector3(...start.position).distanceTo(new Vector3(...end.position));

                            return (
                                <React.Fragment key={key}>
                                    {toggleView &&
                                        <Html
                                            key={`${start.pointUuid}_${end.pointUuid}`}
                                            userData={line}
                                            position={[textPosition.x, 1, textPosition.z]}
                                            wrapperClass="distance-text-wrapper"
                                            className="distance-text"
                                            zIndexRange={[1, 0]}
                                            prepend
                                            sprite
                                        >
                                            <div
                                                key={key}
                                                className={`distance ${key}`}
                                            >
                                                {distance.toFixed(2)} m
                                            </div>
                                        </Html>
                                    }
                                </React.Fragment>
                            )
                        })}

                    </group>
                </>
            )}
        </>
    )
}

export default ZoneInstances