import { type FC, useEffect } from 'react';
import { useMutation } from 'react-query';
import { useSearchParams } from 'react-router-dom';

import Stack from '@material-hu/mui/Stack';

import { DialogHeader } from '@material-hu/components/design-system/Dialog';

import { logEvent } from 'src/config/amplitude';
import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useSocket } from 'src/contexts/SocketContext';
import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import IncomingCallModal from 'src/pages/dashboard/videoCall/IncomingCallModal';
import { parseIncomingCallParams } from 'src/pages/dashboard/videoCall/utils';
import { rejectCall } from 'src/services/streaming';
import { EventName } from 'src/types/amplitude';
import { CallType } from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getUrl } from 'src/utils/stream';

const IncomingCallPopupPage: FC = () => {
  const [searchParams] = useSearchParams();
  const socket = useSocket();
  const ThemeProvider = useHuGoTheme();
  const showGeneralError = useGeneralError();
  const { t } = useLokaliseTranslation('calls');

  const callProps = parseIncomingCallParams(searchParams);

  const { mutateAsync: rejectCallMutation } = useMutation(
    (variables: { callId: string }) => rejectCall(variables.callId),
    {
      onSuccess: () => {
        window.close();
      },
      onError: error => {
        showGeneralError(error, t('ERROR_REJECT_CALL'));
      },
    },
  );

  useEffect(() => {
    const closePopup = () => {
      window.close();
    };

    socket.listenEvent(EVENTS_SOCKETS.CALL_ENDED, closePopup);
    socket.listenEvent(EVENTS_SOCKETS.CALL_ACCEPTED, closePopup);
    socket.listenEvent(EVENTS_SOCKETS.CALL_REJECTED, closePopup);
    socket.listenEvent(EVENTS_SOCKETS.CALL_MISSED, closePopup);

    return () => {
      socket.closeEvent(EVENTS_SOCKETS.CALL_ENDED, closePopup);
      socket.closeEvent(EVENTS_SOCKETS.CALL_ACCEPTED, closePopup);
      socket.closeEvent(EVENTS_SOCKETS.CALL_REJECTED, closePopup);
      socket.closeEvent(EVENTS_SOCKETS.CALL_MISSED, closePopup);
    };
  }, [socket]);

  if (!callProps) {
    window.close();
    return null;
  }

  const handleAccept = () => {
    window.open(
      getUrl({
        id: callProps.id,
        providerCallId: callProps.providerCallId,
      }),
      callProps.id,
    );

    logEvent(EventName.CALLS_CALL_ANSWERED_ACCEPTED, {
      call_type: callProps.initializationConfig.cameraEnabled
        ? CallType.VIDEO
        : CallType.AUDIO,
      id: callProps.id,
      caller_id: callProps.creator.id,
    });

    window.close();
  };

  const handleReject = () => {
    rejectCallMutation({ callId: callProps.id });
  };

  return (
    <ThemeProvider>
      <Stack sx={{ height: '100vh' }}>
        <DialogHeader
          title={t('INCOMING_CALL')}
          onClose={handleReject}
        />
        <Stack
          sx={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: theme =>
              theme.palette.new.background.layout.default,
          }}
        >
          <IncomingCallModal
            creator={callProps.creator}
            joinedUserNames={callProps.joinedUserNames}
            isGroupCall={callProps.isGroupCall}
            initializationConfig={callProps.initializationConfig}
            onCancel={handleReject}
            onAccept={handleAccept}
          />
        </Stack>
      </Stack>
    </ThemeProvider>
  );
};

export default IncomingCallPopupPage;
