import { useMutation } from 'react-query';
import { useLocation } from 'react-router-dom';

import i18next from 'i18next';

import { IconCheck, IconWorld } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuMenu from '@material-hu/components/design-system/Menu';
import HuMenuItem from '@material-hu/components/design-system/Menu/components/MenuItem';
import HuTitle from '@material-hu/components/design-system/Title';

import { Language } from 'src/constants/languages';
import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { changeLanguageUser } from 'src/services/users';
import { getLanguageOptions, setDocumentLanguage } from 'src/utils/languages';

import { useTranslation } from '../i18n';

type LanguageMenuProps = {
  anchorEl: HTMLElement | null;
  onClose: () => void;
};

const LanguageMenu = ({ anchorEl, onClose }: LanguageMenuProps) => {
  const showGeneralError = useGeneralError();
  const location = useLocation();
  const { t } = useTranslation();
  const { user, changeLanguage: changeUserLanguage } = useAuth();

  const updateLanguage = (language: Language) => {
    changeUserLanguage(language);

    setDocumentLanguage(language);
    i18next.changeLanguage(language);
  };

  const changeLanguageMutation = useMutation(
    (language: Language) => {
      updateLanguage(language);
      return changeLanguageUser(user.id, language);
    },
    {
      onSuccess: () => {
        if (location.pathname === '/org-chart') {
          window.location.reload();
        }
      },
      onError: err => {
        const rollbackLanguage = user?.language as Language;
        updateLanguage(rollbackLanguage);
        showGeneralError(err, t('CHANGE_LANGUAGE_ERROR'));
      },
    },
  );

  return (
    <HuMenu
      open={!!anchorEl}
      anchorEl={anchorEl}
      onClose={onClose}
      header={
        <Stack
          sx={{ flexDirection: 'row', gap: 1, alignItems: 'center', p: 2 }}
        >
          <HuAvatar Icon={IconWorld} />
          <HuTitle
            title={t('LANGUAGE')}
            variant="S"
          />
        </Stack>
      }
      sx={{ minWidth: '200px' }}
      position="right"
    >
      {getLanguageOptions().map(language => {
        const isCurrentLanguage = user?.language === language.value;
        return (
          <HuMenuItem
            onClick={() => changeLanguageMutation.mutate(language.value)}
            key={language.value}
            sx={{ justifyContent: 'space-between', gap: 2 }}
          >
            <HuTitle
              title={t(`${language.label}`)}
              variant="S"
            />
            {isCurrentLanguage && <IconCheck />}
          </HuMenuItem>
        );
      })}
    </HuMenu>
  );
};

export default LanguageMenu;
