import { FC } from 'react';

import enLocale from 'date-fns/locale/en-US';
import Stack from '@material-hu/mui/Stack';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuFormInputMoney from '@material-hu/components/design-system/Inputs/Money/form';
import { defaultTransform } from '@material-hu/components/design-system/Inputs/Money/utils';
import HuFormInputSelect from '@material-hu/components/design-system/Inputs/Select/form';
import HuTitle from '@material-hu/components/design-system/Title';
import { useAuth } from 'src/contexts/JWTContext';
import { useMobile } from 'src/contexts/MobileContext';
import useRules from 'src/hooks/useRules';
import { LOAN } from 'src/types/banBajio';
import { validateAmount } from 'src/utils/banBajio';
import { useLokaliseTranslation } from 'src/utils/i18n';

type LoanRequestsStep2Props = {
  loanType: LOAN;
  getPaymentCapacity: () => React.ReactNode;
  salary: number | null;
  levelPosition: number;
};

const ShortTerm: FC<LoanRequestsStep2Props> = ({
  loanType,
  getPaymentCapacity,
  salary,
  levelPosition,
}) => {
  const { t } = useLokaliseTranslation('banbajio');
  const { isMobile } = useMobile();
  const { hiringDate } = useAuth().user!;

  const termsRules = useRules({
    requiredWithMessage: true,
  });

  const amountRules = useRules(
    { requiredWithMessage: true },
    {
      validate: (val: any) => {
        const isValid = validateAmount(
          val.amount,
          loanType,
          hiringDate!,
          salary!,
          levelPosition,
        );

        return isValid === true || t(isValid);
      },
    },
  );

  const isShortTerm = loanType === LOAN.SHORT_TERM;
  const termOptions = isShortTerm ? [3, 6, 9, 12, 24] : [12, 18, 24, 36, 48];

  return (
    <Stack>
      <HuTitle
        variant="S"
        title={t(isShortTerm ? 'SHORT_TERM_LOAN' : 'REQUEST_LOAN_FURNITURE')}
      />
      <HuCardContainer sx={{ width: '100%', mb: 1 }}>
        <Stack sx={{ flexDirection: isMobile ? 'column' : 'row', gap: 2 }}>
          <Stack sx={{ flex: 1 }}>
            <HuFormInputMoney
              name="amount"
              inputProps={{
                label: t('AMOUNT'),
                selectCoin: false,
                transform: defaultTransform(enLocale),
              }}
              rules={amountRules}
            />
          </Stack>
          <HuFormInputSelect
            name="termMonths"
            inputProps={{
              sx: { flex: 1 },
              label: t('TERM_IN_MONTHS'),
              placeholder: t('general:select'),
              options: termOptions.map(value => ({
                value,
                label: value.toString(),
              })),
            }}
            rules={termsRules}
          />
        </Stack>
      </HuCardContainer>
      {getPaymentCapacity()}
    </Stack>
  );
};

export default ShortTerm;
