import * as THREE from 'three';
import { Sky } from "@react-three/drei";
import { useAzimuth, useElevation, useSunPosition } from "../../../store/store";
import { useEffect, useRef, useState } from "react";
import * as CONSTANTS from '../../../types/world/worldConstants';

export default function Sun() {
    const { elevation, setElevation } = useElevation();
    const { sunPosition, setSunPosition } = useSunPosition();
    const { azimuth, setAzimuth } = useAzimuth();
    const [turbidity, setTurbidity] = useState(CONSTANTS.skyConfig.defaultTurbidity);
    const sunPositionRef = useRef(new THREE.Vector3(0, 0, 0));
    const [_, forceUpdate] = useState(0);
    const maxTurbidity = CONSTANTS.skyConfig.maxTurbidity;
    const minTurbidity = CONSTANTS.skyConfig.minTurbidity;

    useEffect(() => {
        const phi = THREE.MathUtils.degToRad(90 - elevation);
        const theta = THREE.MathUtils.degToRad(azimuth);

        const computedTurbidity = minTurbidity + ((elevation - 2) / (90 - 2)) * (maxTurbidity - minTurbidity);
        setTurbidity(computedTurbidity);

        sunPositionRef.current.setFromSphericalCoords(1, phi, theta);
        setSunPosition(sunPositionRef.current);
        forceUpdate(prev => prev + 1);
    }, [elevation, azimuth]);

    return (
        <>
            {(azimuth !== undefined && elevation !== undefined) && (
                <>
                    <Sky
                        distance={CONSTANTS.skyConfig.skyDistance}
                        sunPosition={[
                            sunPositionRef.current.x,
                            sunPositionRef.current.y,
                            sunPositionRef.current.z,
                        ]}
                        turbidity={turbidity}
                        rayleigh={CONSTANTS.skyConfig.defaultRayleigh}
                        mieCoefficient={CONSTANTS.skyConfig.mieCoefficient}
                        mieDirectionalG={CONSTANTS.skyConfig.mieDirectionalG}
                    />
                </>
            )}
        </>
    );
}
