import { useState } from 'react';
import { Helmet } from 'react-helmet-async';

import Stack from '@material-hu/mui/Stack';

import * as HuAuth from '@material-hu/components/composed-components/auth';

import webBanner from 'src/assets/images/login-banner-web.webp';
import { useGetOTP } from 'src/hooks/queryHooks/login';
import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useStateLocation from 'src/hooks/useStateLocation';
import { type OTPChannels, OTPErrors, type OTPState } from 'src/types/login';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  CheckCode,
  Loading,
  MaxTries,
  PhoneNotUpdated,
  SendSMS,
} from './components/otp';

const LoginOTP = () => {
  const [step, setStep] = useState<number>(0);
  const [error, setError] = useState<OTPErrors | null>(null);
  const [selectedChannel, setSelectedChannel] = useState<OTPChannels | null>(
    null,
  );

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

  const { phoneNumber, channels, isLoading } = useGetOTP(
    {
      instanceId: state?.instance?.id,
      employeeInternalId: state?.employeeInternalId,
    },
    {
      onError: err => {
        if (
          [OTPErrors.PHONE_NOT_FOUND, OTPErrors.INVALID_PHONE].includes(
            err?.response?.data?.code,
          )
        ) {
          handleError(err?.response?.data?.code);
          return;
        }

        showGeneralError(err, t('ERROR_GENERAL_RETRY'));
      },
      onSuccess: successData => {
        if (successData?.data?.length <= 0) {
          handleError(OTPErrors.PHONE_NOT_FOUND);
        }
      },
    },
  );

  const handleNext = () => setStep(step + 1);

  const handleError = (err: OTPErrors) => setError(err);

  const handleRetry = () => {
    setStep(0);
    setError(null);
  };

  const steps = [
    <SendSMS
      key="send-sms"
      receiver={phoneNumber || ''}
      channels={channels!}
      onSuccess={handleNext}
      onError={handleError}
      setSelectedChannel={setSelectedChannel}
      selectedChannel={selectedChannel}
    />,
    <CheckCode
      key="check-code"
      receiver={phoneNumber || ''}
      channels={channels!}
      selectedChannel={selectedChannel!}
      onError={handleError}
      onSuccess={newSelectedChannel => setSelectedChannel(newSelectedChannel)}
    />,
  ];

  const errors = {
    [OTPErrors.PHONE_NOT_FOUND]: <PhoneNotUpdated />,
    [OTPErrors.INVALID_PHONE]: <PhoneNotUpdated />,
    [OTPErrors.MAX_TRIES]: <MaxTries onRetry={handleRetry} />,
  };

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('LOGIN'))}</title>
      </Helmet>
      <HugoThemeProvider>
        {!error && (
          <HuAuth.LoginLayout
            showBackdrop={false}
            banner={{
              src: webBanner,
              styles: {
                maxWidth: '45%',
                minWidth: 300,
                alignContent: 'center',
              },
            }}
          >
            <Stack
              sx={{
                width: '100%',
                height: '100%',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              {isLoading && <Loading />}
              {!isLoading && !error && steps[step]}
            </Stack>
          </HuAuth.LoginLayout>
        )}
        {!!error && errors[error as keyof typeof errors]}
      </HugoThemeProvider>
    </>
  );
};

export default LoginOTP;
