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

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

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuFormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import HuTitle from '@material-hu/components/design-system/Title';
import { canShowBanBajio } from 'src/constants/banBajio';
import { useAuth } from 'src/contexts/JWTContext';
import { useMobile } from 'src/contexts/MobileContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { useMobileLayout } from 'src/hooks/useMobileLayout';
import { useMobileToken } from 'src/hooks/useMobileToken';
import AdvancePayment from 'src/pages/dashboard/banBajio/AdvancePayment';
import { banBajioRoutes } from 'src/pages/dashboard/banBajio/routes';
import {
  formatCurrentDate,
  formatDateFromString,
  useGenerateBanbajioPDFDownload,
  validateAdvancePaymentAmount,
} from 'src/utils/banBajio';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';
import FocusNavbar from 'src/components/FocusNavbar';

import BanBajioGrid from './components/BanBajioGrid';
import { useDynamicFields } from './useDynamicFields';

const FormAdvancePayment: FC = () => {
  const { user, instance } = useAuth();
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('banbajio');
  const { isMobile } = useMobile();
  const HugoThemeProvider = useHuGoTheme();

  const [isLoading, setIsLoading] = useState(false);
  const advancePaymentRef = useRef<HTMLDivElement>(null);
  const generatePDF = useGenerateBanbajioPDFDownload();

  useMobileToken();
  useMobileLayout();

  const { data: profileData } = useDynamicFields();

  const form = useForm({
    mode: 'onChange',
    defaultValues: {
      name: getFullName(user),
      payroll: '',
      hiringDate: formatDateFromString(user!.hiringDate!),
      advancePaymentDate: formatCurrentDate(new Date()),
      amount: '',
    },
  });

  if (!profileData) return null;

  const { watch } = form;

  const handleOnClick = form.handleSubmit(async () => {
    setIsLoading(true);
    await generatePDF(advancePaymentRef.current!, t('FORTNIGHT_ADVANCED_PDF'));
    navigate(banBajioRoutes.home() + (isMobile ? '-mobile/1' : ''));
  });

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

  const userInformation = [
    {
      label: 'FULL_NAME',
      value: getFullName(user),
    },
    {
      label: 'PAYROLL_NUMBER',
      value: profileData!.payroll,
    },
    {
      label: 'HIRING_DATE',
      value: formatDateFromString(user!.hiringDate!),
    },
    {
      label: 'ADVANCE_PAYMENT_DATE',
      value: formatDateFromString(user!.hiringDate!),
    },
  ];

  return (
    <HugoThemeProvider>
      <FormProvider {...form}>
        <Helmet>
          <title>{t('ADVANCE_PAYMENT_FORTNIGHT')}</title>
        </Helmet>
        <FocusNavbar
          navbarProps={{
            title: t('ADVANCE'),
            onClick: () =>
              navigate(banBajioRoutes.home() + (isMobile ? '-mobile/1' : '')),
          }}
          bottomBarContent={
            <Container maxWidth="md">
              <Stack sx={{ alignItems: 'flex-end' }}>
                <Button
                  variant="primary"
                  onClick={handleOnClick}
                  loading={isLoading}
                >
                  {t('SEND_REQUEST')}
                </Button>
              </Stack>
            </Container>
          }
          content={
            <Container maxWidth="md">
              <div
                style={{
                  position: 'absolute',
                  top: '-9999px',
                  left: '-9999px',
                }}
              >
                <AdvancePayment
                  ref={advancePaymentRef}
                  isFiba={profileData!.isFiba}
                  payroll={profileData!.payroll}
                  amount={watch('amount')}
                  bankAccount={profileData!.bankAccount}
                  bossName={profileData!.boss}
                  bossPosition={profileData!.bossPosition}
                />
              </div>
              <HuTitle
                title={t('ADVANCE_PAYMENT_FORTNIGHT')}
                description={t('DESCRIPTION_ADVANCE_PAYMENT')}
                variant="L"
                sx={{ mt: 8 }}
              />
              <FormProvider {...form}>
                <HuTitle
                  title={t('LOAN_DETAILS')}
                  variant="S"
                  sx={{ mt: 3, mb: 0.5 }}
                />
                <HuCardContainer sx={{ width: '100%', mb: 3 }}>
                  <HuFormInputClassic
                    name="amount"
                    inputProps={{
                      type: 'number',
                      label: t('ADVANCE_PAYMENT_AMOUNT_FIELD'),
                      helperText: t('ENTER_AMOUNT_BETWEEN', {
                        amount1: 1,
                        amount2: Math.min(
                          profileData!.netFortnight,
                          profileData!.salary * 0.25,
                        ),
                      }),
                      startAdornment: '$',
                    }}
                    rules={{
                      validate: value =>
                        validateAdvancePaymentAmount(
                          value,
                          profileData!.salary,
                          profileData!.netFortnight,
                          t,
                        ),
                      required: t('REQUIRED_FIELD'),
                    }}
                  />
                </HuCardContainer>
                <HuCardContainer sx={{ width: '100%' }}>
                  <BanBajioGrid data={userInformation} />
                </HuCardContainer>
              </FormProvider>
            </Container>
          }
        />
      </FormProvider>
    </HugoThemeProvider>
  );
};

export default FormAdvancePayment;
