import { FC, useEffect, useState } from 'react';
import { FormProvider, useFormContext } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import { useModal } from '@material-hu/hooks/useModal';
import { IconInfoCircle } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import HuFormSelectionCard from '@material-hu/components/composed-components/SelectionCard/form';
import HuAlert from '@material-hu/components/design-system/Alert';
import HuDialog from '@material-hu/components/design-system/Dialog';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import { loanRequestsOptions } from 'src/constants/banBajio';
import { useAuth } from 'src/contexts/JWTContext';
import { getMonthsSinceHiring } from 'src/utils/banBajio';
import { useLokaliseTranslation } from 'src/utils/i18n';

import LoanRequestsLayout from './LoanRequestsLayout';
import { banBajioRoutes } from './routes';
import { useCarLibraryId } from './useCarLibraryId';
import useLibraryInfoDrawer from './useLibraryInfoDrawer';

type LoanRequestsStep1Props = {
  onGoToNextStep: () => void;
  onGoToPreviousStep: () => void;
};

const LoanRequestsStep1: FC<LoanRequestsStep1Props> = ({
  onGoToNextStep,
  onGoToPreviousStep,
}) => {
  const { user } = useAuth();
  const { t } = useLokaliseTranslation('banbajio');
  const navigate = useNavigate();
  const [selectedError, setSelectedError] = useState(false);
  const form = useFormContext();

  const selectedLoanType = Object.entries(form.watch('selectedLoan')).find(
    ([, value]) => value,
  )?.[0];
  const selectedLoan = loanRequestsOptions.find(
    module => module.loanType === selectedLoanType,
  );

  const userMonthsAntiquity = getMonthsSinceHiring(user!.hiringDate!) || 0;
  const wrongAntiquity =
    !!selectedLoan && userMonthsAntiquity < selectedLoan.antiquityThreshold;

  const handleClickNext = () => {
    if (!selectedLoan) {
      setSelectedError(true);
      return;
    }
    if (selectedLoan!.showWarning) {
      showWarningModal();
    } else {
      navigate(banBajioRoutes.mortgageLibrary());
    }
  };

  useEffect(() => {
    if (selectedLoan) {
      setSelectedError(false);
    }
  }, [selectedLoan]);

  const {
    modal: warningModal,
    showModal: showWarningModal,
    closeModal,
  } = useModal(
    HuDialog,
    {},
    {
      title: t(
        wrongAntiquity
          ? 'NOT_ALLOW_LOAN'
          : 'LOAN_REQUESTS_STEP_1_WARNING_TITLE',
      ),
      textBody: t(
        wrongAntiquity
          ? selectedLoan!.antiquityKey
          : 'LOAN_REQUESTS_STEP_1_WARNING_DESCRIPTION',
        {
          months: userMonthsAntiquity,
        },
      ),
      primaryButtonProps: {
        children: t(wrongAntiquity ? 'general:close' : 'AGREE_AND_CONTINUE'),
        onClick: () => {
          if (wrongAntiquity) {
            closeModal();
          } else {
            form.setValue('loanType', selectedLoan!);
            onGoToNextStep();
          }
        },
      },
    },
  );

  const { drawer, showDrawer } = useLibraryInfoDrawer();
  const { data: carLibraryId } = useCarLibraryId();

  return (
    <FormProvider {...form}>
      {drawer}
      <LoanRequestsLayout
        onGoToNextStep={handleClickNext}
        onGoToPreviousStep={onGoToPreviousStep}
        currentStep={0}
      >
        <Stack sx={{ width: '100%', gap: 2.25, mb: 1 }}>
          {loanRequestsOptions.map(module => (
            <HuFormSelectionCard
              key={module.loanType}
              isOnlyOption
              name={`selectedLoan.${module.loanType}`}
              sx={{ width: '100%' }}
            >
              <HuListItem
                avatar={{
                  Icon: module.icon,
                  color: module.color,
                  variant: 'square',
                }}
                text={{
                  title: t(module.title),
                  description: t('DESCRIPTION', { context: module.title }),
                }}
                action={
                  module.libraryId || carLibraryId
                    ? {
                        Icon: IconInfoCircle,
                        onClick: () => showDrawer({ module }),
                      }
                    : undefined
                }
                sx={{ width: '100%', '.MuiListItem-root': { p: 0 } }}
              />
            </HuFormSelectionCard>
          ))}
        </Stack>
        {selectedError && (
          <HuAlert
            severity="error"
            title={t('NOT_SELECTED_LOAN')}
            sx={{ mt: 5 }}
          />
        )}
      </LoanRequestsLayout>
      {warningModal}
    </FormProvider>
  );
};

export default LoanRequestsStep1;
