import {useEffect, useState} from "react";
import {Button} from "@/components/ui/button";

import {fetchValue, sendValue} from "@/app/lib/x32CommunicationManager";

const MuteButton = ({id, label, path, pollingInterval}) => {


    const [isMuted, setIsMuted] = useState(false);

    useEffect(() => {

        const updateCurrentMuteValue = async () => {
            fetchValue(path).then((value) => {
                    if (value !== isMuted) {
                        setIsMuted(value);
                    }
                }
            );
        }
        // Initial fetch and polling
        updateCurrentMuteValue();

        // add random interval to avoid all clients polling at the same time
        const randomInterval = Math.random() * pollingInterval;
        setTimeout(() => null, randomInterval);

        const interval = setInterval(() => {
            updateCurrentMuteValue();
        }, pollingInterval);

        return () => clearInterval(interval); // Cleanup interval
    }, [path, pollingInterval]);


    const toggleMute = () => {
        const newIsMuted = !isMuted;

        // disable or enable the input for each channel
        sendValue(
            path,
            newIsMuted ? 1 : 0,
        );

        setIsMuted(newIsMuted);
    }

    return (
        <Button key={`${id}-${path}-mute`}
                className={`w-24 ${isMuted ? 'bg-green-500' : 'bg-red-500'}`}
                onClick={toggleMute}>
            {label}
        </Button>
    )
}

export default MuteButton;