"use client";
import { DialogTransition } from "@/core/components/DialogTransition";
import { useCall } from "@/lib/contexts/call";
import { useSocket } from "@/lib/contexts/socket";
import { Dialog } from "@mui/material";
import { useEffect } from "react";
import CallTabs from "./CallTabs";

const CallWidgetDialog = () => {
  const { openCallDialog, setOpenCallDialog, calls, newCall } = useCall();
  const { socket } = useSocket();

  useEffect(() => {
    const call = (_data, act) => {
      const data = JSON.parse(_data);
      newCall({
        id: data.call_id,
        phone_number: data.phone_number,
      });
      act();
    };
    socket.on("call", call);

    return () => {
      socket.off("call", call);
    };
  });

  useEffect(() => {
    if (calls.length === 0) {
      setOpenCallDialog(false);
      return;
    }
    setOpenCallDialog(true);
  }, [calls.length]);

  return (
    <Dialog
      fullScreen
      open={openCallDialog}
      slots={{ transition: DialogTransition }}
    >
      <CallTabs />
    </Dialog>
  );
};

export default CallWidgetDialog;
