import { TFunction, Trans } from 'react-i18next';
import { useMutation } from 'react-query';

import { IconDeviceMobile } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import * as HuAuth from '@material-hu/components/composed-components/auth';
import HuAvatar from '@material-hu/components/design-system/Avatar';
import Button from '@material-hu/components/design-system/Buttons/Button';
import HuLink from '@material-hu/components/design-system/Link';

import { OTP_SUPPORT_LINK, OTPChannelsLabelAndIcon } from 'src/constants/login';
import useGeneralError from 'src/hooks/useGeneralError';
import useStateLocation from 'src/hooks/useStateLocation';
import { loginKeys } from 'src/pages/authentication/queries';
import { sendOTP } from 'src/services/authService';
import { OTPState, OTPErrors, OTP, OTPChannels } from 'src/types/login';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

export type SendSMSProps = Pick<OTP, 'receiver'> & {
  channels: OTP['channel'][];
  onSuccess?: () => void;
  onError?: (error: OTPErrors) => void;
  setSelectedChannel: (channel: OTPChannels) => void;
  selectedChannel: OTPChannels | null;
};

const SendSMS = (props: SendSMSProps) => {
  const {
    receiver,
    channels,
    onSuccess = () => null,
    onError = () => null,
    setSelectedChannel = () => null,
    selectedChannel,
  } = props;

  const { t } = useLokaliseTranslation('authentication');
  const showGeneralError = useGeneralError();
  const state = useStateLocation<OTPState>();

  const sendMutation = useMutation(
    loginKeys.otp.send(),
    (channel: OTPChannels) =>
      sendOTP({
        instanceId: state?.instance?.id,
        employeeInternalId: state?.employeeInternalId,
        channel,
      }),
    {
      onMutate: variables => {
        logEvent(LogEvents.USER_RECEIVE_CODE, {
          instanceId: state?.instance?.id,
          instanceName: state?.instance?.name,
          username: state?.employeeInternalId,
          channel: variables,
        });
      },
      onError: (error: any) => {
        if (error?.response?.data?.code === OTPErrors.MAX_TRIES) {
          onError(OTPErrors.MAX_TRIES);
          return;
        }

        showGeneralError(error, t('general:error'));
      },
      onSuccess: () => {
        onSuccess();
      },
    },
  );

  const handleSend = (channel: OTPChannels) => {
    setSelectedChannel(channel);
    sendMutation.mutate(channel, {
      onSuccess,
    });
  };

  const firstChannel = channels?.[0];
  const secondChannel = channels?.[1];

  const IconFirstChannel = OTPChannelsLabelAndIcon[firstChannel].icon;
  const IconSecondChannel = OTPChannelsLabelAndIcon[secondChannel]?.icon;

  return (
    <HuAuth.OTPLayout
      instanceCardProps={{
        name: state?.instance?.name,
        logo: state?.instance?.logo,
      }}
      title={t('otp_send_message.new_body')}
    >
      <Stack sx={{ gap: 4 }}>
        <Stack sx={{ gap: 1 }}>
          <Typography variant="globalM">
            {t('otp_send_message.body_2')}
          </Typography>
          <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
            <HuAvatar Icon={IconDeviceMobile} />
            <Typography
              variant="globalL"
              fontWeight="fontWeightSemiBold"
              component="span"
            >
              {receiver}
            </Typography>
          </Stack>
        </Stack>
        <Stack sx={{ gap: 2 }}>
          <Button
            variant="primary"
            size="large"
            onClick={() => handleSend(firstChannel)}
            disabled={sendMutation.isLoading}
            loading={selectedChannel === firstChannel && sendMutation.isLoading}
            fullWidth
            endIcon={!sendMutation.isLoading ? <IconFirstChannel /> : null}
          >
            {t('otp_send_message.button', {
              channel: OTPChannelsLabelAndIcon[firstChannel].label,
            })}
          </Button>
          {secondChannel && (
            <Button
              size="large"
              onClick={() => handleSend(secondChannel)}
              disabled={sendMutation.isLoading}
              loading={
                selectedChannel === secondChannel && sendMutation.isLoading
              }
              fullWidth
              endIcon={sendMutation.isLoading ? null : <IconSecondChannel />}
            >
              {t('otp_send_message.button', {
                channel: OTPChannelsLabelAndIcon[secondChannel].label,
              })}
            </Button>
          )}
        </Stack>
        <Typography
          variant="globalS"
          sx={{
            color: theme => theme.palette.textColors?.neutralTextLighter,
          }}
        >
          <Trans
            i18nKey={t('not_your_number_help_text')}
            t={t as TFunction}
            components={{
              linkSupport: (
                <HuLink
                  href={OTP_SUPPORT_LINK}
                  target="_blank"
                  sx={{
                    display: 'inline-block',
                  }}
                />
              ),
            }}
          />
        </Typography>
      </Stack>
    </HuAuth.OTPLayout>
  );
};

export default SendSMS;
