/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { useEffect, useRef, useState } from "react";
import useIsAudioActive from "use-is-audio-active";
import IUser from "../types/IUser";
import SoundOffIcon from "./icons/SoundOffIcon";
import SoundOnIcon from "./icons/SoundOnIcon";

interface Props {
  mediaStream: MediaStream | null;
  muted: boolean;
  user?: IUser;
}

function Video({ mediaStream, muted, user }: Props) {
  const remoteVideoRef = useRef<HTMLVideoElement>(null);
  const isSpeaking = useIsAudioActive({ source: mediaStream });
  const [_muted, setMuted] = useState(muted);
  const [isLoading, setIsLoading] = useState(true);

  function toggleSound() {
    if (!remoteVideoRef.current) return;
    // remoteVideoRef.current.muted = !remoteVideoRef.current.muted;
    setMuted((prev) => !prev);
  }

  useEffect(() => {
    if (!remoteVideoRef.current) return;

    remoteVideoRef.current.srcObject = mediaStream;
    remoteVideoRef.current.onloadedmetadata = () => {
      remoteVideoRef.current?.play();
    };

    remoteVideoRef.current.onplay = () => {
      setIsLoading(false);
    };

    console.log("mediaStream", mediaStream?.getTracks());
  }, [mediaStream]);

  useEffect(() => {
    console.log("remoteVideoRef.current", remoteVideoRef);
  }, [remoteVideoRef.current]);

  return (
    <div className="relative">
      <video
        ref={remoteVideoRef}
        className={`aspect-video lg:w-[216px] w-[160px] lg:h-[162px] h-[120px] rounded-lg object-cover bg-gray-500 ring-2 ${
          !_muted && isSpeaking ? "ring-green-500" : "ring-transparent"
        }`}
        playsInline
        autoPlay
        muted={_muted}
      ></video>
      <div className="absolute bottom-0 flex items-center justify-between w-full p-2">
        <p className="text-sm text-white">{user?.name}</p>
        <button className="text-white" onClick={toggleSound}>
          {_muted ? <SoundOffIcon /> : <SoundOnIcon />}
        </button>
      </div>
      {isLoading && (
        <div className="absolute top-0 left-0 flex items-center justify-center w-full h-full">
          <img
            src="/icons/Loader.png"
            alt=""
            className="w-6 h-6 animate-spin"
          />
        </div>
      )}
    </div>
  );
}

export default Video;
