import { useEffect, useState } from 'react';

import { CallingState, useCallStateHooks } from '@stream-io/video-react-sdk';

import { useTheme } from '@material-hu/mui/styles';

import HuAlert from '@material-hu/components/design-system/Alert';

import { useLokaliseTranslation } from 'src/utils/i18n';

export const NetworkAlert = () => {
  const { t } = useLokaliseTranslation('livestream');
  const theme = useTheme();

  const [stateHistory, setStateHistory] = useState<CallingState[]>([]);
  const [showReconnectionMessage, setShowReconnectionMessage] = useState(false);

  const { useCallCallingState } = useCallStateHooks();
  const callingState = useCallCallingState();

  useEffect(() => {
    if (stateHistory[stateHistory.length - 1] !== callingState) {
      let newHistory = [...stateHistory, callingState];
      const stateCount = newHistory.filter(
        state => state === callingState,
      ).length;
      if (stateCount > 1) {
        const firstAppearenceIndex = newHistory.findIndex(
          state => state === callingState,
        );
        const duplicate = newHistory
          .slice(firstAppearenceIndex + 1)
          .find(state => state === callingState);
        if (duplicate) {
          newHistory.splice(firstAppearenceIndex, 1);
        }
      }

      if (
        newHistory.includes(CallingState.OFFLINE) &&
        callingState === CallingState.JOINED
      ) {
        setShowReconnectionMessage(true);
        newHistory = newHistory.filter(state => state !== CallingState.OFFLINE);
      }

      if (showReconnectionMessage && callingState !== CallingState.JOINED) {
        setShowReconnectionMessage(false);
      }

      setStateHistory(newHistory);
    }
  }, [callingState]);

  const alertStyles = {
    position: 'absolute',
    bottom: theme.spacing(2),
    left: theme.spacing(3),
    zIndex: 2,
  };

  return (
    <>
      {stateHistory[stateHistory.length - 1] === CallingState.OFFLINE && (
        <HuAlert
          severity="error"
          title={t('INTERRUPTED')}
          description={t('INTERRUPTED_DESCRIPTION')}
          sx={alertStyles}
        />
      )}
      {showReconnectionMessage &&
        stateHistory[stateHistory.length - 1] === CallingState.JOINED && (
          <HuAlert
            key="online"
            severity="success"
            title={t('RECONNECTED')}
            hasClose
            sx={alertStyles}
          />
        )}
    </>
  );
};
