import { useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { FormProvider, useForm } from 'react-hook-form';

import { canShowBanBajio, loanRequestsOptions } from 'src/constants/banBajio';
import { useAuth } from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { useMobileLayout } from 'src/hooks/useMobileLayout';
import { useMobileToken } from 'src/hooks/useMobileToken';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormPDFs from './FormPDFs';
import LoanRequestsStep1 from './LoanRequestsStep1';
import LoanRequestsStep2 from './LoanRequestsStep2';
import LoanRequestsStep3 from './LoanRequestsStep3';

const LoanRequests = () => {
  const { instance } = useAuth();
  const { t } = useLokaliseTranslation('banbajio');
  const HugoThemeProvider = useHuGoTheme();

  useMobileToken();
  useMobileLayout();

  if (!canShowBanBajio(instance!.id)) {
    return null;
  }

  const [currentStep, setCurrentStep] = useState(0);

  const form = useForm({
    mode: 'onChange',
    defaultValues: {
      selectedLoan: loanRequestsOptions.reduce((acc, module) => {
        acc[module.loanType] = false;
        return acc;
      }, {} as any),
      loanType: null,
      amount: { currencyCode: 'MXN', amount: '' },
      termMonths: '',
      carState: null,
      carAge: '',
      loanInfo: '',
      sellerInfo: '',
    },
  });

  const handleGoToPreviousStep = () => setCurrentStep(currentStep - 1);
  const handleGoToNextStep = () => setCurrentStep(currentStep + 1);

  return (
    <HugoThemeProvider>
      <FormProvider {...form}>
        <Helmet>
          <title>{t('LOAN_REQUESTS')}</title>
        </Helmet>
        {currentStep === 0 && (
          <LoanRequestsStep1
            onGoToNextStep={handleGoToNextStep}
            onGoToPreviousStep={handleGoToPreviousStep}
          />
        )}
        {currentStep === 1 && (
          <LoanRequestsStep2
            onGoToNextStep={handleGoToNextStep}
            onGoToPreviousStep={handleGoToPreviousStep}
          />
        )}
        {currentStep > 1 && (
          <LoanRequestsStep3
            onGoToNextStep={handleGoToNextStep}
            onGoToPreviousStep={handleGoToPreviousStep}
            loadingNextStep={currentStep === 3}
          />
        )}
        {currentStep === 3 && <FormPDFs />}
      </FormProvider>
    </HugoThemeProvider>
  );
};

export default LoanRequests;
