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

import HuAccordion from '@material-hu/components/design-system/Accordion';
import HuAlert from '@material-hu/components/design-system/Alert';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuPills from '@material-hu/components/design-system/Pills';
import HuSpinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import { INTEREST_RATE } from 'src/constants/banBajio';
import { LOAN, PriceType } from 'src/types/banBajio';
import {
  calculatePaymentCapacity,
  formatPriceValue,
  getAmortization,
  getInitialInterest,
} from 'src/utils/banBajio';
import { useLokaliseTranslation } from 'src/utils/i18n';

import BanBajioGrid from './components/BanBajioGrid';
import Car from './components/step2/Car';
import ShortTerm from './components/step2/ShortTerm';
import LoanRequestsLayout from './LoanRequestsLayout';
import { useDynamicFields } from './useDynamicFields';

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

const LoanRequestsStep2: FC<LoanRequestsStep2Props> = ({
  onGoToNextStep,
  onGoToPreviousStep,
}) => {
  const { t } = useLokaliseTranslation('banbajio');
  const loanType = useFormContext().watch('loanType');
  const [remainingPaymentC, setRemainingPaymentC] = useState(0);

  const { data } = useDynamicFields();

  const form = useFormContext();
  const {
    amount: { amount },
    termMonths,
  } = form.watch();

  if (!data) return <HuSpinner />;

  const salary = data.salary;
  const shortTermDiscount = data.shortTermDiscount;
  const carDiscount = data.carDiscount;
  const furnitureDiscount = data.furnitureDiscount;
  const mortgageDiscount = data.mortgageDiscount;
  const amortization = getAmortization(amount, termMonths);
  const initialInterest = getInitialInterest(amount);

  const getPaymentCapacity = () => {
    const isComplete = amount && termMonths;
    const initialMonthlyPayment =
      amortization && initialInterest && amortization + initialInterest;

    const loanDetails = [
      {
        label: 'AMOUNT',
        value: amount ? formatPriceValue(amount, PriceType.PRICE) : '—',
        type: 'PRICE',
      },
      {
        label: 'AMORTIZATION',
        value: isComplete
          ? formatPriceValue(amortization, PriceType.PRICE)
          : '—',
        type: 'PRICE',
      },
      {
        label: 'TERM',
        value: termMonths ? t('MONTHS_AMOUNT', { termMonths }) : '—',
      },
      {
        label: 'INITIAL_INTEREST',
        value: isComplete
          ? formatPriceValue(initialInterest, PriceType.PRICE)
          : '—',
        type: 'PRICE',
      },
      {
        label: 'INITIAL_INTEREST_RATE',
        value: `${INTEREST_RATE}%`,
      },
      {
        label: 'INITIAL_MONTHLY_PAYMENT',
        value: isComplete
          ? formatPriceValue(initialMonthlyPayment, PriceType.PRICE)
          : '—',
        type: 'PRICE',
      },
    ];

    const { salaryPercentage, shortTermD, carD, furnitureD, remainingPayment } =
      calculatePaymentCapacity(
        mortgageDiscount,
        salary,
        loanType.loanType,
        initialMonthlyPayment || 0,
        shortTermDiscount,
        carDiscount,
        furnitureDiscount,
      );

    const paymentCapacity = [
      {
        label:
          mortgageDiscount > 0
            ? 'MONTHLY_SALARY_PERCENTAGE_WITH_MORTGAGE'
            : 'MONTHLY_SALARY_PERCENTAGE',
        value: formatPriceValue(salaryPercentage, PriceType.PRICE),
      },
      {
        label: 'SHORT_TERM_MONTHLY_PAYMENT',
        value: formatPriceValue(shortTermD, PriceType.PRICE_NEGATIVE),
      },
      {
        label: 'FURNITURE_MONTHLY_PAYMENT',
        value: formatPriceValue(furnitureD, PriceType.PRICE_NEGATIVE),
      },
      {
        label: 'MORTGAGE_MONTHLY_PAYMENT',
        value: formatPriceValue(mortgageDiscount, PriceType.PRICE_NEGATIVE),
      },
      {
        label: 'CAR_MONTHLY_PAYMENT',
        value: formatPriceValue(carD, PriceType.PRICE_NEGATIVE),
        type: 'PRICE_NEGATIVE',
      },
      {
        label: 'REMAINING_PAYMENT_CAPACITY',
        value: (
          <HuPills
            type={remainingPayment > 0 ? 'success' : 'error'}
            size="small"
            hasIcon={false}
            label={
              (remainingPayment < 0 ? '-' : '') +
              formatPriceValue(
                remainingPayment > 0 ? remainingPayment : -remainingPayment,
                PriceType.PRICE,
              )
            }
          />
        ),
        hasColor: true,
      },
    ];

    if (remainingPaymentC !== remainingPayment) {
      setRemainingPaymentC(remainingPayment);
    }

    return (
      <>
        {remainingPaymentC <= 0 && (
          <HuAlert
            title={t('REMAINING_PAYMENT_INSUFFICIENT')}
            severity="error"
            sx={{ mb: 1 }}
          />
        )}
        <HuCardContainer sx={{ width: '100%', mb: 3 }}>
          <BanBajioGrid data={loanDetails} />
        </HuCardContainer>
        <HuCardContainer sx={{ width: '100%', mb: 1 }}>
          <HuAccordion
            title={t('PAYMENT_CAPACITY')}
            elevation={0}
            defaultExpanded
            hasPadding={false}
            customDetail={<BanBajioGrid data={paymentCapacity} />}
          />
        </HuCardContainer>
      </>
    );
  };

  return (
    <LoanRequestsLayout
      disabledNextStep={remainingPaymentC <= 0}
      onGoToNextStep={async () => {
        if (!(await form.trigger()) || remainingPaymentC <= 0) {
          return;
        }
        onGoToNextStep();
      }}
      onGoToPreviousStep={onGoToPreviousStep}
      currentStep={1}
    >
      {[LOAN.SHORT_TERM, LOAN.FURNITURE].includes(loanType.loanType) && (
        <ShortTerm
          getPaymentCapacity={getPaymentCapacity}
          loanType={loanType.loanType}
          salary={salary}
          levelPosition={data.levelPosition}
        />
      )}
      {loanType.loanType === LOAN.CAR && (
        <Car
          getPaymentCapacity={getPaymentCapacity}
          salary={salary}
          loanType={loanType.loanType}
          levelPosition={data.levelPosition}
        />
      )}
    </LoanRequestsLayout>
  );
};

export default LoanRequestsStep2;
