import { FC, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';

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 HuFormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
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 { CAR_OPTIONS } from 'src/constants/banBajio';
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 Car: FC<LoanRequestsStep2Props> = ({
  loanType,
  getPaymentCapacity,
  salary,
  levelPosition,
}) => {
  const { t } = useLokaliseTranslation('banbajio');
  const { isMobile } = useMobile();
  const { hiringDate } = useAuth().user!;

  const form = useFormContext();

  const {
    amount: { amount },
    carState,
  } = form.watch();
  const secondRowDisabled = !carState;
  const isNewCar = carState === 1;

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

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

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

  const carAgeRules = useRules(
    { requiredWithMessage: true },
    {
      validate: (val: string) => {
        const carAgeNumber = Number(val);
        const currentYear = new Date().getFullYear();
        const minYear = isNewCar ? currentYear - 1 : currentYear - 4;
        const maxYear = isNewCar ? currentYear + 1 : currentYear;
        if (
          isNaN(carAgeNumber) ||
          carAgeNumber % 1 != 0 ||
          carAgeNumber < minYear ||
          carAgeNumber > maxYear
        ) {
          return t('INVALID_YEAR');
        }
        return true;
      },
    },
  );

  const carStateRules = useRules({ requiredWithMessage: true });

  const termsOptions = (isNewCar ? [24, 36, 48, 60] : [12, 18, 24, 36, 48]).map(
    value => ({
      value,
      label: value.toString(),
    }),
  );

  useEffect(() => {
    form.resetField('termMonths');
    form.resetField('carAge');
  }, [amount, carState]);

  return (
    <Stack>
      <HuTitle
        variant="S"
        title={t('REQUEST_LOAN_CAR')}
      />
      <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="carState"
            inputProps={{
              sx: { flex: 1 },
              label: t('CAR_CONDITION'),
              placeholder: t('general:select'),
              options: CAR_OPTIONS.map(option => ({
                value: option.value,
                label: t(option.label),
              })),
            }}
            rules={carStateRules}
          />
        </Stack>
        <Stack
          sx={{ flexDirection: isMobile ? 'column' : 'row', mt: 2, gap: 2 }}
        >
          <HuFormInputSelect
            name="termMonths"
            inputProps={{
              disabled: secondRowDisabled,
              sx: { flex: 1 },
              label: t('TERM_IN_MONTHS'),
              placeholder: t('general:select'),
              options: termsOptions,
              helperText: secondRowDisabled
                ? t('SELECT_CAR_CONDITION_FIRST')
                : undefined,
            }}
            rules={secondRowDisabled ? undefined : termsRules}
          />
          <HuFormInputClassic
            name="carAge"
            inputProps={{
              type: 'number',
              hasCounter: false,
              label: t('CAR_YEAR'),
              placeholder: t('WRITE_HERE'),
              sx: { flex: 1 },
              disabled: secondRowDisabled,
              helperText: secondRowDisabled
                ? t('SELECT_CAR_CONDITION_FIRST')
                : t(isNewCar ? 'NEW_CAR_YEARS' : 'USED_CAR_YEARS'),
            }}
            rules={secondRowDisabled ? undefined : carAgeRules}
          />
        </Stack>
      </HuCardContainer>

      {getPaymentCapacity()}
    </Stack>
  );
};

export default Car;
