import { Dialog, DialogPanel, DialogTitle } from "@headlessui/react";
import { useNavigate } from "react-router-dom";
import TextTranslate from "../../../utils/TextTranslate";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import { updateViewState } from "../../../store/Slices/ViewManagerSlice";
import { useEffect, useRef } from "react";
import { socketInstance } from "../../../socket/socket";
import { resetCallData } from "../../../store/Slices/CallDataSlice";

export default function AcceptVideoCall() {
  const navigate = useNavigate();
  const ViewManager = useAppSelector((state) => state.ViewManager);
  const CallData = useAppSelector((state) => state.CallData);
  const dispatch = useAppDispatch();
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const socket = socketInstance();
  const peerData = useAppSelector((state) => state.PeerJsSlice);

  const callSound = () => {
    if (!audioRef.current) {
      audioRef.current = new Audio("/audio/call-sound.wav");
    }
    audioRef.current.loop = true;
    audioRef.current.play().catch((error) => {
      console.error("Error playing sound:", error);
    });
  };

  const stopSound = () => {
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
      audioRef.current = null;
    }
  };

  useEffect(() => {
    if (ViewManager.show_missed_call_modal) {
      stopSound();
    }
  }, [ViewManager.show_missed_call_modal]);

  function acceptCall() {
    navigate("video-call");
    dispatch(updateViewState({ show_accept_call_modal: false }));
    stopSound();
  }

  async function declineCall() {
    dispatch(updateViewState({ show_accept_call_modal: false }));
    stopSound();
    if (CallData.chat.chat_type !== "group") {
      socket.emit("decline_call", {
        chat_id: peerData.chat_id,
        peer_id: peerData.peer_id,
        call_id: peerData.call_id,
      });
    }
  }

  function closeMissedCallModal() {
    stopSound();
    dispatch(
      updateViewState({
        show_missed_call_modal: false,
        show_accept_call_modal: false,
      }),
    );
    dispatch(resetCallData({}));
  }

  useEffect(() => {
    if (ViewManager.show_accept_call_modal) {
      callSound();
    }
  }, [ViewManager.show_accept_call_modal]);

  if (!CallData?.chat?.chat_type) {
    return null;
  }

  const isMissedCall = ViewManager.show_missed_call_modal;

  return (
    <>
      <Dialog
        open={ViewManager.show_accept_call_modal || isMissedCall}
        as="div"
        className="relative z-10"
        onClose={() => {}}
      >
        <div className="fixed inset-0 z-10 backdrop-blur-sm">
          <div className="flex min-h-full items-center justify-center p-4">
            <DialogPanel
              transition
              className="data-[closed]:transform-[scale(95%)] w-full max-w-lg rounded-2xl bg-modalBg p-6 text-center shadow-[rgba(17,_17,_26,_0.3)_0px_0px_16px] backdrop-blur-md transition-all duration-300 ease-in-out data-[closed]:opacity-0"
            >
              <img
                className="mx-auto my-4 h-14 w-14 rounded-full object-cover"
                src={
                  CallData.chat.chat_type === "group"
                    ? CallData.chat.group_icon
                    : CallData.user.profile_pic
                }
                alt=""
              />
              <DialogTitle as="h3" className="text-xl font-medium">
                <TextTranslate
                  text={
                    isMissedCall
                      ? `You missed a call from ${
                          CallData.chat.chat_type === "group"
                            ? CallData.chat.group_name
                            : CallData.user.full_name
                        }`
                      : `A Request from ${
                          CallData.chat.chat_type === "group"
                            ? CallData.chat.group_name
                            : CallData.user.full_name
                        } to accept a call`
                  }
                />
              </DialogTitle>
              <p className="mt-2 text-sm opacity-70">
                <TextTranslate
                  text={
                    isMissedCall
                      ? "Please try calling back later."
                      : "Accept the call to get started discussion"
                  }
                />
              </p>

              <div className="mt-10 flex gap-3">
                {isMissedCall ? (
                  <button
                    onClick={closeMissedCallModal}
                    className="relative h-11 w-full overflow-hidden rounded-lg bg-[#E0E0E0] px-4 py-2 text-base font-medium text-black outline-none lg:px-9 lg:text-lg"
                  >
                    <span className="">Close</span>
                  </button>
                ) : (
                  <>
                    <button
                      onClick={acceptCall}
                      className="relative h-11 w-full overflow-hidden rounded-lg bg-[#76CC76] px-4 py-2 text-base font-medium text-black outline-none lg:px-9 lg:text-lg"
                    >
                      <span className="">Accept</span>
                    </button>
                    <button
                      onClick={declineCall}
                      className="relative h-11 w-full overflow-hidden rounded-lg bg-[#EA5F5F] px-4 py-2 text-base font-medium text-black outline-none lg:px-9 lg:text-lg"
                    >
                      <span className="">Reject</span>
                    </button>
                  </>
                )}
              </div>
            </DialogPanel>
          </div>
        </div>
      </Dialog>
    </>
  );
}
