/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react-hooks/exhaustive-deps */
import { useRoomContext } from "@livekit/components-react";
import { RoomEvent, Track } from "livekit-client";
import { useEffect, useState } from "react";
import MicroOnIcon from "./icons/MicroOnIcon";
import MicroOffIcon from "./icons/MicroOffIcon";

function ToggleMic({ socket, handleUpdate }: any) {
  const room = useRoomContext();
  const [muted, setMuted] = useState(false);

  function toggleMic(value: boolean) {
    const audioTrack = room.localParticipant.getTrack(Track.Source.Microphone);

    if (!audioTrack) return;

    if (value) {
      audioTrack.mute();
    } else {
      audioTrack.unmute();
    }

    setMuted(!audioTrack.isMuted);
  }

  useEffect(() => {
    if (!socket) return;

    socket.on("update", (socketId: string, data: { [key: string]: any }) => {
      if (
        socket.id === socketId &&
        Object.prototype.hasOwnProperty.call(data, "muted")
      ) {
        toggleMic(data.muted);
      }
    });
  }, [socket]);

  useEffect(() => {
    room.on(RoomEvent.TrackMuted, (_, participant) => {
      console.log(participant);
    });

    room.on(RoomEvent.TrackUnmuted, (_, participant) => {
      console.log(participant);
    });
  }, []);

  return (
    <button
      onClick={() =>
        handleUpdate(room.localParticipant.identity, {
          muted: !room.localParticipant.getTrack(Track.Source.Microphone)
            ?.isMuted,
        })
      }
      className="relative group outline-none bg-[#131313] rounded-full shadow-lg shadow-[#131313] p-2 opacity-90"
    >
      {!muted ? <MicroOnIcon /> : <MicroOffIcon />}
    </button>
  );
}

export default ToggleMic;
