import { useEffect, useRef, useState } from 'react'
import { useThree, useFrame } from '@react-three/fiber'
import type CameraControlsImpl from 'camera-controls'

export default function AutoRotate() {
    const { gl, controls } = useThree()
    const [isIdle, setIsIdle] = useState(false)
    const idleTimeout = useRef<NodeJS.Timeout | null>(null)
    const lastInteractionTime = useRef(Date.now())

    const cameraControls = controls as CameraControlsImpl | null

    const resetIdleTimer = () => {
        lastInteractionTime.current = Date.now()
        if (isIdle) setIsIdle(false)
        if (idleTimeout.current) clearTimeout(idleTimeout.current)
        idleTimeout.current = setTimeout(() => {
            setIsIdle(true)
        }, 30_000)
    }

    useEffect(() => {
        const dom = gl.domElement
        const listener = () => resetIdleTimer()

        dom.addEventListener('pointerdown', listener)
        dom.addEventListener('wheel', listener)
        window.addEventListener('keydown', listener)

        resetIdleTimer()

        return () => {
            dom.removeEventListener('pointerdown', listener)
            dom.removeEventListener('wheel', listener)
            window.removeEventListener('keydown', listener)
        }
    }, [gl])

    useFrame((_, delta) => {
        if (isIdle && cameraControls) {
            cameraControls.rotate(delta * 0.1, 0, true)
            cameraControls.update(delta)
        }
    })

    return null
}
