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

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 { useSendCodeMutation } from 'src/hooks/queryHooks/login';
import useGeneralError from 'src/hooks/useGeneralError';
import useStateLocation from 'src/hooks/useStateLocation';
import {
  type OTP,
  type OTPChannels,
  OTPErrors,
  type OTPState,
} from 'src/types/login';
import { useLokaliseTranslation } from 'src/utils/i18n';

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 = useSendCodeMutation(
    {
      instanceId: state?.instance?.id,
      instanceName: state?.instance?.name,
      employeeInternalId: state?.employeeInternalId,
    },
    {
      onError: error => {
        if (error?.response?.data?.code === OTPErrors.MAX_TRIES) {
          onError(OTPErrors.MAX_TRIES);
          return;
        }

        showGeneralError(error, t('ERROR_GENERAL_RETRY'));
      },
    },
  );

  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.new.text.neutral.lighter,
          }}
        >
          <Trans
            i18nKey={t('NOT_YOUR_NUMBER_HELP_TEXT')}
            t={t as TFunction}
            components={{
              linkSupport: (
                <HuLink
                  href={OTP_SUPPORT_LINK}
                  target="_blank"
                  rel="noopener noreferrer"
                  sx={{
                    display: 'inline-block',
                  }}
                />
              ),
            }}
          />
        </Typography>
      </Stack>
    </HuAuth.OTPLayout>
  );
};

export default SendSMS;
