import { useEffect } from 'react';
import { useBlocker } from 'react-router';

import { useCall } from '@stream-io/video-react-sdk';
import { useModal } from '@material-hu/hooks/useModal';

import { StreamStatus } from 'src/types/stream';

import ConfirmDialog from '../components/ConfirmDialog';

const beforeUnloadHandler = (event: BeforeUnloadEvent) => {
  event.preventDefault();
};

export const useLeaveLive = (
  onLeave: () => void,
  streamStatus: StreamStatus,
) => {
  const call = useCall();
  const isLive = streamStatus === StreamStatus.Streaming;
  const hasEnded = streamStatus === StreamStatus.Finished;

  let blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      currentLocation.pathname !== nextLocation.pathname,
  );

  useEffect(() => {
    if (isLive) {
      window.addEventListener('beforeunload', beforeUnloadHandler);
    }

    return () => {
      window.removeEventListener('beforeunload', beforeUnloadHandler);
    };
  }, [isLive]);

  const { modal, showModal, closeModal } = useModal(
    ConfirmDialog,
    {
      fullWidth: true,
      maxWidth: 'sm',
    },
    {
      onClose: () => {
        closeModal();
        blocker.reset?.();
      },
      onConfirm: () => {
        onLeave();
        blocker.proceed?.();
      },
    },
  );

  useEffect(() => {
    if (blocker.state === 'blocked') {
      if (isLive) {
        showModal();
      } else if (hasEnded) {
        blocker.proceed?.();
      } else {
        call?.endCall();
        blocker.proceed?.();
      }
    }
  }, [blocker, call, hasEnded, isLive, showModal]);

  return { confirmLeaveModal: modal };
};

export default useLeaveLive;
