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

import { AxiosError } from 'axios';

import {
  IconCircleCheck,
  IconCircleX,
  IconExclamationCircle,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';
import { AvatarProps as HuAvatarProps } from '@material-hu/components/design-system/Avatar/types';
import Button from '@material-hu/components/design-system/Buttons/Button';
import HumandLogo from '@material-hu/components/design-system/HumandLogo';
import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { clearUser, logEvent, setUser } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { updateRequestByEmail } from 'src/services/vacations';
import { EventName } from 'src/types/amplitude';
import { ResponseError } from 'src/types/services';
import { VacationActionsSources } from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';

const UpdateRequestByMail = () => {
  const [searchParams] = useSearchParams();
  const { t } = useLokaliseTranslation('time_off');

  const otc = searchParams.get('otc')!;
  const state = searchParams.get('state')!;
  const policyTypeName = searchParams.get('policyTypeName');
  const policyTypeId = searchParams.get('policyTypeId');
  const issuerFullName = searchParams.get('issuerFullName');
  const requestId = searchParams.get('requestId');

  const { isAuthenticated } = useAuth();

  const [error, setError] = useState<{
    Icon: typeof IconCircleX;
    variant: HuAvatarProps['color'];
    errorTitleKey: string;
    descriptionTitleKey: string;
  }>({
    Icon: IconCircleX,
    variant: 'error',
    errorTitleKey: 'UPDATE_ERROR_REQUEST',
    descriptionTitleKey: 'DESCRIPTION_UPDATE_ERROR_REQUEST',
  });

  const updateRequestByMutation = useMutation(
    () => updateRequestByEmail(otc, state),
    {
      onSuccess: async response => {
        const { user, instance } = response.data;
        await setUser(user, instance);
        logEvent(EventName.TIME_OFF_APPROVAL_RESOLVED, {
          source: VacationActionsSources.MAIL,
          requestId,
          policyTypeId,
          state,
          resolutionReason: '',
        });
        if (!isAuthenticated) {
          clearUser();
        }
      },
      onError: (r: AxiosError<ResponseError>) => {
        if (
          ['VACATION_REQUEST_NOT_PENDING', 'OTC_ALREADY_USED'].includes(
            r.response!.data!.code,
          )
        ) {
          setError({
            Icon: IconExclamationCircle,
            variant: 'warning',
            errorTitleKey: 'UPDATE_ERROR_CANNOT_RESPOND',
            descriptionTitleKey: 'UPDATE_ERROR_CANNOT_RESPOND_DESCRIPTION',
          });
        }
      },
    },
  );

  useEffect(() => {
    updateRequestByMutation.mutate();
  }, []);

  const Icon = updateRequestByMutation.isError ? error.Icon : IconCircleCheck;

  return (
    <Stack
      sx={{
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%',
      }}
    >
      {updateRequestByMutation.isLoading && <HuCircularProgress centered />}
      {!updateRequestByMutation.isLoading &&
        !updateRequestByMutation.isIdle && (
          <Stack
            sx={{
              backgroundColor: theme =>
                theme.palette.new.background.layout.tertiary,
              width: '100%',
              height: '100%',
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <Stack
              sx={{
                width: '100%',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: theme =>
                  theme.palette.new.background.layout.default,
                py: 6,
              }}
            >
              <HumandLogo
                title="humand logo"
                style={{ width: 200 }}
              />
            </Stack>
            <HuAvatar
              Icon={Icon}
              size="large"
              color={
                updateRequestByMutation.isError ? error.variant : 'primary'
              }
              sx={{
                my: 3,
              }}
            />
            <Typography
              variant="globalXXL"
              fontWeight="fontWeightSemiBold"
              sx={{ textAlign: 'center' }}
            >
              {t(
                updateRequestByMutation.isError
                  ? error.errorTitleKey
                  : `UPDATE_${state}_REQUEST`,
              )}
            </Typography>
            <Typography
              variant="globalM"
              fontWeight="fontWeightRegular"
              sx={{ mt: 1.5 }}
            >
              {t(
                updateRequestByMutation.isError
                  ? error.descriptionTitleKey
                  : `DESCRIPTION_UPDATE_${state}_REQUEST`,
                { policyTypeName, issuerFullName },
              )}
            </Typography>
            <Typography
              variant="globalM"
              sx={{ mt: 5 }}
              fontWeight="fontWeightSemiBold"
            >
              {t('GO_TO_REQUEST_DETAIL')}
            </Typography>
            <Button
              variant="primary"
              component="a"
              disabled={!requestId}
              size="large"
              href={
                requestId
                  ? `vacations/manager?vacationId=${requestId}`
                  : 'login'
              }
              sx={{ mt: 2 }}
            >
              {t('GO_TO_HUMAND')}
            </Button>
          </Stack>
        )}
    </Stack>
  );
};

export const UpdateRequestByMailContainer = () => {
  const HugoThemeProvider = useHuGoTheme();
  return (
    <HugoThemeProvider>
      <UpdateRequestByMail />
    </HugoThemeProvider>
  );
};

export default UpdateRequestByMailContainer;
