import gsap from "gsap"
import { forwardRef, useEffect, useImperativeHandle, useRef } from "react"
import { sendOsc } from "../util/osc";

const FADE_TIME=3;

export const Light=forwardRef((props, ref)=>{

    const refVal=useRef({val: 0});
    const refInput=useRef();
    const refContainer=useRef();

    function fade(from, to){
        
        const time= parseFloat(refInput.current.value) || FADE_TIME;
        gsap.fromTo(refVal.current,{val: from}, { 
            val: to, 
            duration: time,
            onUpdate: () => {
                // console.log(refVal.current.val);
                sendOsc('/light', refVal.current.val.toString());
                refContainer.current.style.background= `rgba(0, 255, 0, ${refVal.current.val})`; // Update background color based on value
            },
        });
    }
    useImperativeHandle(ref, () => ({
        fadeIn: ()=>{
            console.log('fadeIn');
            fade(0, 1);
        },
        fadeOut: ()=>{
            console.log('fadeOut');
            fade(1, 0);
        }
    }));
    useEffect(()=>{

        refInput.current.value=FADE_TIME;

    },[]);

    return (
        <div ref={refContainer} className="flex flex-row gap-4 !w-auto p-1 border">
            <span className="flex flex-col justify-between">
                <label className="text-center">Light</label>
                <input ref={refInput} type="text" className="border w-[5vw]" defaultValue={5}/>                
            </span>
            <span className="flex flex-col justify-between">
                <button onClick={()=>fade(0,1)}>fadeIn</button>
                <button onClick={()=>fade(1,0)}>fadeOut</button>
            </span>
        </div>
    )
});