/* eslint-disable no-nested-ternary */
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import { ToWords } from 'to-words';

import buroApproval from 'src/assets/pdf/buroApproval.pdf';
import banbaCreditRequestLetter from 'src/assets/pdf/Solicitud de creditos Banbajio.pdf';
import fibaCreditRequestLetter from 'src/assets/pdf/Solicitud de creditos FIBA.pdf';
import { INTEREST_RATE } from 'src/constants/banBajio';
import { useMobile } from 'src/contexts/MobileContext';
import { LOAN, PriceType, type WebViewPdfData } from 'src/types/banBajio';
import { type ReactNativeWebViewType } from 'src/types/login';
import { type MeUser } from 'src/types/user';

import { getFullName } from './userUtils';

export const getUserProfileData = (data: any, user: MeUser) => {
  if (!data) return null;

  return data.map((elem: any) => ({
    id: elem.id,
    name: elem.name,
    value: user.profileData![elem.id] || null,
  }));
};

export const getProfileDataValue = (data: any, name: string) => {
  const profileData = data?.find((elem: any) => elem.name === name);
  return profileData ? profileData.value : null;
};

export const getMonthsSinceHiring = (hiringDate: string) => {
  if (!hiringDate) return null;

  const hiringDateObj = new Date(hiringDate);
  const currentDate = new Date();
  const yearsDifference =
    currentDate.getFullYear() - hiringDateObj.getFullYear();
  const monthsDifference = currentDate.getMonth() - hiringDateObj.getMonth();
  return yearsDifference * 12 + monthsDifference;
};

export const validateAmount = (
  value: string,
  loanType: LOAN,
  hiringDate: string,
  salary: number,
  levelPosition?: number,
  carState?: number,
) => {
  const intValue = parseInt(value, 10);
  if (!Number(intValue)) {
    return 'INTEGER_VALIDATION';
  }
  if (
    loanType === LOAN.SHORT_TERM &&
    getMonthsSinceHiring(hiringDate)! < 12 &&
    intValue > salary
  ) {
    return 'MONTH_VALIDATION_SALARY';
  }
  if (
    loanType === LOAN.SHORT_TERM &&
    getMonthsSinceHiring(hiringDate)! > 12 &&
    intValue > salary * 4
  ) {
    return 'MONTHS_4_VALIDATION_SALARY';
  }
  if (loanType === LOAN.FURNITURE && intValue > salary * 6) {
    return 'MONTHS_6_VALIDATION_SALARY';
  }
  if (loanType === LOAN.CAR && intValue > salary * 10) {
    return 'MONTHS_10_VALIDATION_SALARY';
  }
  if (
    loanType === LOAN.CAR &&
    levelPosition === 4 &&
    carState === 1 &&
    intValue > 1000000
  ) {
    return 'VALIDATION_AMOUNT_1';
  }
  if (
    loanType === LOAN.CAR &&
    levelPosition === 4 &&
    carState === 2 &&
    intValue > 900000
  ) {
    return 'VALIDATION_AMOUNT_2';
  }
  if (
    loanType === LOAN.CAR &&
    levelPosition === 3 &&
    carState === 1 &&
    intValue > 800000
  ) {
    return 'VALIDATION_AMOUNT_3';
  }
  if (
    loanType === LOAN.CAR &&
    levelPosition === 3 &&
    carState === 2 &&
    intValue > 700000
  ) {
    return 'VALIDATION_AMOUNT_4';
  }
  if (
    loanType === LOAN.CAR &&
    levelPosition === 2 &&
    carState === 1 &&
    intValue > 600000
  ) {
    return 'VALIDATION_AMOUNT_5';
  }
  if (
    loanType === LOAN.CAR &&
    levelPosition === 2 &&
    carState === 2 &&
    intValue > 500000
  ) {
    return 'VALIDATION_AMOUNT_6';
  }
  if (
    loanType === LOAN.CAR &&
    levelPosition === 1 &&
    carState === 1 &&
    intValue > 400000
  ) {
    return 'VALIDATION_AMOUNT_7';
  }
  if (
    loanType === LOAN.CAR &&
    levelPosition === 1 &&
    carState === 2 &&
    intValue > 300000
  ) {
    return 'VALIDATION_AMOUNT_8';
  }
  return true;
};

export const validateAdvancePaymentAmount = (
  value: string,
  salary: number,
  netFortnight: number,
  t: Function,
) => {
  const intValue = parseInt(value, 10);
  if (!Number(intValue)) {
    return t('INTEGER_VALIDATION');
  }
  if (intValue > salary * 0.25) {
    return t('ADVANCE_PAYMENT_AMOUNT_1');
  }
  if (intValue > netFortnight) {
    return t('ADVANCE_PAYMENT_AMOUNT_2');
  }
  return true;
};

export const getAmortization = (amount: number, monthsTerms: number) => {
  if (!amount || !monthsTerms) return null;
  return amount / monthsTerms;
};

export const getInitialInterest = (amount: number) => {
  if (!amount) return null;
  return (amount * INTEREST_RATE) / (100 * 12);
};

const formatDate = (date: Date) => {
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const year = date.getFullYear();
  return `${day}/${month}/${year}`;
};

const getAge = (date: string) => {
  return String(new Date().getFullYear() - new Date(date).getFullYear());
};

export const capitalize = (text: string) =>
  text?.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());
export const formatNumber = (number?: number) =>
  number?.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });

export const downloadBlobAsFile = (blob: Blob, filename: string) => {
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

export const generateBuroApprovalPDF = async (formData: any, user: MeUser) => {
  const { rfc, city, state, postalCode, cologne, street, streetNumber } =
    formData;
  const name = getFullName(user);
  const { phoneNumber } = user;

  const existingPdfBytes = await fetch(buroApproval).then(res =>
    res.arrayBuffer(),
  );
  const pdfDoc = await PDFDocument.load(existingPdfBytes);
  const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);

  const pages = pdfDoc.getPages();
  const firstPage = pages[0];
  const { height } = firstPage.getSize();

  firstPage.drawText('X', {
    x: 149,
    y: height - 300,
    size: 18,
    color: rgb(0, 0, 0),
  });

  const address = `${street} ${streetNumber}`;

  const fields = [
    { value: capitalize(name), x: 52, y: height - 344 },
    { value: formatDate(new Date()), x: 197, y: height - 387 },
    { value: rfc, x: 80, y: height - 404 },
    { value: capitalize(address), x: 114, y: height - 439, size: 8 },
    { value: capitalize(cologne), x: 383, y: height - 439, size: 8 },
    { value: capitalize(city), x: 86, y: height - 456, size: 8 },
    { value: capitalize(state), x: 255, y: height - 456, size: 8 },
    { value: capitalize(postalCode), x: 427, y: height - 456 },
    { value: phoneNumber, x: 197, y: height - 473 },
  ];

  fields.forEach(field =>
    firstPage.drawText(field.value, {
      x: field.x,
      y: field.y,
      size: field.size || 10,
      font: helveticaFont,
      color: rgb(0, 0, 0),
    }),
  );
  return pdfDoc;
};

export const generateFibaCreditRequestLetterPDF = async (
  profileData: any,
  user: MeUser,
  formData: any,
) => {
  const name = getFullName(user);

  const existingPdfBytes = await fetch(fibaCreditRequestLetter).then(res =>
    res.arrayBuffer(),
  );
  const pdfDoc = await PDFDocument.load(existingPdfBytes);
  const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);

  const pages = pdfDoc.getPages();
  const firstPage = pages[0];
  const { height } = firstPage.getSize();

  let xOffset = 0;
  switch (formData.loanType.loanType) {
    case LOAN.SHORT_TERM:
      xOffset = 0;
      break;
    case LOAN.CAR:
      xOffset = 90;
      break;
    case LOAN.FURNITURE:
      xOffset = 180;
      break;
  }

  const amortization = getAmortization(
    formData.amount.amount,
    formData.termMonths,
  );
  const initialInterest = getInitialInterest(formData.amount.amount);
  const initialMonthlyPayment =
    amortization && initialInterest && amortization + initialInterest;

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

  const placeText = `${profileData.municipality}, ${profileData.state}`;
  const fullAddress = `${profileData.street} ${profileData.streetNumber}\n${profileData.cologne}, ${profileData.city}, ${profileData.municipality}, ${profileData.state}, CP ${profileData.postalCode}\n${user.phoneNumber}`;

  const calculateSize = (text: string, width: number) => {
    return Math.min(Math.max((1.7 * width) / text.length, 5), 8);
  };

  const fields = [
    //first row
    {
      value: placeText,
      x: 30,
      y: 712,
      width: 227 - 28,
      size: placeText.length > 50 ? 5 : undefined,
    },
    { value: formatDate(new Date()), x: 250, y: height - 84 },
    { value: 'X', x: 348 + xOffset, y: height - 84 },
    //second row
    {
      value: formatPriceValue(formData.amount.amount, PriceType.PRICE),
      x: 45,
      y: height - 110,
    },
    { value: String(formData.termMonths), x: 150, y: height - 110 },
    { value: String(INTEREST_RATE), x: 201, y: height - 110 },
    {
      value: formData.loanInfo,
      x: 230,
      y: height - (formData.loanInfo.length > 45 ? 105 : 110),
      size: calculateSize(formData.loanInfo, 170),
      width: 170,
    },
    {
      value: formData.sellerInfo,
      x: 407,
      y: height - (formData.sellerInfo.length > 45 ? 105 : 110),
      size: calculateSize(formData.sellerInfo, 170),
      width: 170,
    },
    //third row
    {
      value: profileData.payroll || '-',
      x: 29,
      y: height - 159,
      width: 89 - 29,
      size: calculateSize(profileData.payroll || '-', 89 - 29),
    },
    {
      value: capitalize(name),
      x: 90,
      y: height - 159,
      width: 360 - 90,
      size: calculateSize(name, 360 - 90),
    },
    { value: formatDate(new Date(user.birthdate!)), x: 366, y: height - 159 },
    { value: getAge(user.birthdate!), x: 445, y: height - 159 },
    { value: profileData.rfc, x: 485, y: height - 159 },
    //fourth row
    {
      value: profileData.department,
      x: 30,
      y: height - 205,
      width: 196 - 30,
      size: calculateSize(profileData.department, 196 - 30),
    },
    {
      value: formatPriceValue(profileData.salary, PriceType.PRICE),
      x: 200,
      y: height - 205,
    },
    {
      value: profileData.jobPosition,
      x: 290,
      y: height - 205,
      width: 481 - 286,
      size: calculateSize(profileData.jobPosition, 481 - 286),
    },
    { value: formatDate(new Date(user.hiringDate!)), x: 484, y: height - 205 },
    { value: getAge(user.hiringDate!), x: 555, y: height - 205 },
    //fifth row
    {
      value: formatPriceValue(formData.amount.amount, PriceType.PRICE),
      x: 240,
      y: height - 240,
    },
    //sixth row
    { value: String(formData.termMonths), x: 240, y: height - 255 },
    { value: String(percentage * 100), x: 290, y: height - 255 },
    {
      value: formatPriceValue(salaryPercentage, PriceType.PRICE),
      x: 460,
      y: height - 255,
    },
    //seventh row
    { value: String(INTEREST_RATE), x: 240, y: height - 273 },
    {
      value: formatPriceValue(shortTermD, PriceType.PRICE_NEGATIVE),
      x: 460,
      y: height - 268,
    },
    {
      value: formatPriceValue(carD, PriceType.PRICE_NEGATIVE),
      x: 460,
      y: height - 280,
    },
    //eighth row
    {
      value: formatPriceValue(amortization, PriceType.PRICE),
      x: 240,
      y: height - 295,
    },
    {
      value: formatPriceValue(furnitureD, PriceType.PRICE_NEGATIVE),
      x: 460,
      y: height - 295,
    },
    //ninth row
    {
      value: formatPriceValue(initialInterest, PriceType.PRICE),
      x: 240,
      y: height - 308,
    },
    {
      value: formatPriceValue(
        profileData.mortgageDiscount,
        PriceType.PRICE_NEGATIVE,
      ),
      x: 460,
      y: height - 308,
    },
    //tenth row
    {
      value: formatPriceValue(initialMonthlyPayment, PriceType.PRICE),
      x: 240,
      y: height - 321,
    },
    {
      value: formatPriceValue(remainingPayment, PriceType.PRICE),
      x: 460,
      y: height - 321,
    },
    //eleventh row
    {
      value: profileData.boss || '-',
      x: 60,
      y: height - 395,
      width: 328 - 60,
      size: calculateSize(profileData.boss, 328 - 60),
    },
    {
      value: profileData.bossPosition || '-',
      x: 60,
      y: height - 407,
      width: 328 - 60,
      size: calculateSize(profileData.bossPosition, 328 - 60),
    },
    //twelfth row
    { value: profileData.bankAccount || '-', x: 30, y: height - 605, size: 5 },
    //thirteenth row
    {
      value: name,
      x: 110,
      y: height - 695,
    },
    {
      value: fullAddress,
      x: 110,
      y: height - 710,
      width: 480 - 110,
      size: calculateSize(name, 480 - 110),
    },
  ];

  fields.forEach(field =>
    firstPage.drawText(field.value, {
      x: field.x,
      y: field.y,
      size: field.size || 8,
      lineHeight: field.size || 8,
      font: helveticaFont,
      color: rgb(0, 0, 0),
      maxWidth: field.width,
      wordBreaks: [' '],
    }),
  );
  return pdfDoc;
};

export const generateBanbajioCreditRequestLetterPDF = async (
  profileData: any,
  user: MeUser,
  formData: any,
) => {
  const name = getFullName(user);

  const existingPdfBytes = await fetch(banbaCreditRequestLetter).then(res =>
    res.arrayBuffer(),
  );
  const pdfDoc = await PDFDocument.load(existingPdfBytes);
  const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);

  const pages = pdfDoc.getPages();
  const firstPage = pages[0];

  let xOffset = 0;
  switch (formData.loanType.loanType) {
    case LOAN.SHORT_TERM:
      xOffset = 0;
      break;
    case LOAN.CAR:
      xOffset = 90;
      break;
    case LOAN.FURNITURE:
      xOffset = 180;
      break;
  }

  const amortization = getAmortization(
    formData.amount.amount,
    formData.termMonths,
  );
  const initialInterest = getInitialInterest(formData.amount.amount);
  const initialMonthlyPayment =
    amortization && initialInterest && amortization + initialInterest;

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

  const priceToSmallPrint = (price: number, includeWords = false) => {
    let value = formatPriceValue(price, PriceType.PRICE).slice(1);
    if (includeWords) {
      value = `${value} ${new ToWords({ localeCode: 'es-MX' }).convert(Number(Number(price).toFixed(2))).toUpperCase()} PESOS`;
    }
    return value;
  };

  const place = `${profileData.municipality}, ${profileData.state}`;
  const nameText = capitalize(name);
  const amountText = priceToSmallPrint(formData.amount.amount, true);

  const fields = [
    //first row
    { value: 'X', x: 348 + xOffset, y: 692 },
    //second row
    {
      value: place,
      x: 120,
      y: 675,
      width: 100,
      size: place.length > 50 ? 6 : undefined,
    },
    { value: formatDate(new Date()), x: 306, y: 672 },
    { value: profileData.payroll || '-', x: 490, y: 672 },
    //third row
    {
      value: formatPriceValue(formData.amount.amount, PriceType.PRICE),
      x: 45,
      y: 635,
    },
    { value: String(formData.termMonths), x: 130, y: 635 },
    { value: String(INTEREST_RATE), x: 177, y: 635 },
    {
      value: formData.loanInfo,
      x: 288,
      y: 655,
      width: 400 - 288,
      size: formData.loanInfo.length > 50 ? 7 : undefined,
    },
    {
      value: formData.sellerInfo,
      x: 487,
      y: 655,
      width: 570 - 486,
      size: formData.loanInfo.length > 50 ? 7 : undefined,
    },
    //fourth row
    {
      value: nameText,
      x: 105,
      y: 595,
      width: 315 - 105,
      size: nameText.length > 50 ? 7 : undefined,
    },
    { value: formatDate(new Date(user.birthdate!)), x: 375, y: 595 },
    { value: profileData.rfc, x: 500, y: 595 },
    //fifth row
    {
      value: profileData.department,
      x: 80,
      y: 555,
      width: 205 - 80,
      size: profileData.department.length > 50 ? 7 : undefined,
    },
    {
      value: formatPriceValue(profileData.salary, PriceType.PRICE),
      x: 250,
      y: 555,
    },
    {
      value: profileData.jobPosition,
      x: 345,
      y: 555,
      width: 470 - 345,
      size: profileData.jobPosition.length > 50 ? 7 : undefined,
    },
    { value: formatDate(new Date(user.hiringDate!)), x: 515, y: 555 },
    //sixth row
    {
      value: formatPriceValue(formData.amount.amount, PriceType.PRICE),
      x: 220,
      y: 505,
    },
    //seventh row
    { value: String(formData.termMonths), x: 220, y: 492 },
    { value: String(percentage * 100), x: 305, y: 492 },
    {
      value: formatPriceValue(salaryPercentage, PriceType.PRICE),
      x: 490,
      y: 492,
    },
    //eighth row
    { value: String(INTEREST_RATE), x: 225, y: 470 },
    {
      value: formatPriceValue(shortTermD, PriceType.PRICE_NEGATIVE),
      x: 495,
      y: 476,
    },
    {
      value: formatPriceValue(carD, PriceType.PRICE_NEGATIVE),
      x: 495,
      y: 461,
    },
    //ninth row
    {
      value: formatPriceValue(amortization, PriceType.PRICE),
      x: 220,
      y: 446,
    },
    {
      value: formatPriceValue(furnitureD, PriceType.PRICE_NEGATIVE),
      x: 495,
      y: 446,
    },
    //tenth row
    {
      value: formatPriceValue(initialInterest, PriceType.PRICE),
      x: 220,
      y: 431,
    },
    {
      value: formatPriceValue(
        profileData.mortgageDiscount,
        PriceType.PRICE_NEGATIVE,
      ),
      x: 495,
      y: 431,
    },
    //eleventh row
    {
      value: formatPriceValue(initialMonthlyPayment, PriceType.PRICE),
      x: 220,
      y: 416,
    },
    {
      value: formatPriceValue(remainingPayment, PriceType.PRICE),
      x: 495,
      y: 416,
    },
    //twelfth row
    {
      value: profileData.boss || '-',
      x: 70,
      y: 340,
      size: profileData.boss.length > 50 ? 7 : undefined,
    },
    {
      value: profileData.bossPosition || '-',
      x: 70,
      y: 328,
      size: profileData.bossPosition.length > 50 ? 7 : undefined,
    },
    // small print
    {
      value: amountText,
      x: 65,
      y: 281,
      size: amountText.length > 50 ? (amountText.length > 70 ? 2 : 3) : 4,
    },
    { value: String(formData.termMonths), x: 242, y: 281, size: 5 },
    {
      value: priceToSmallPrint(initialMonthlyPayment!),
      x: 297,
      y: 281,
      size:
        priceToSmallPrint(initialMonthlyPayment!).length > 6
          ? priceToSmallPrint(initialMonthlyPayment!).length > 9
            ? 2
            : 3
          : 4,
    },
    {
      value: priceToSmallPrint(initialMonthlyPayment!),
      x: 359,
      y: 281,
      size:
        priceToSmallPrint(initialMonthlyPayment!).length > 6
          ? priceToSmallPrint(initialMonthlyPayment!).length > 9
            ? 2
            : 3
          : 4,
    },
    { value: String(INTEREST_RATE), x: 460, y: 275, size: 5 },
    {
      value: profileData.payroll,
      x: 400,
      y: 222,
      size: 5,
    },
    {
      value: profileData.payroll,
      x: 364,
      y: 181,
      size: 5,
    },
    // employee data
    { value: nameText, x: 92, y: 95, width: 572 - 92 },
    {
      value: `${profileData.street} ${profileData.streetNumber}\n${profileData.cologne}, ${profileData.city}, ${profileData.municipality}, ${profileData.state}, CP ${profileData.postalCode}\n${user.phoneNumber}`,
      x: 92,
      y: 77,
      width: 572 - 92,
      size: 7,
    },
  ];

  fields.forEach(field =>
    firstPage.drawText(field.value, {
      x: field.x,
      y: field.y,
      size: field.size || 8,
      lineHeight: field.size || 8,
      font: helveticaFont,
      color: rgb(0, 0, 0),
      maxWidth: field.width,
      wordBreaks: [' '],
    }),
  );
  return pdfDoc;
};

export const getLoanName = (loanType: LOAN) => {
  if (loanType === LOAN.SHORT_TERM) {
    return 'Corto Plazo';
  } else if (loanType === LOAN.CAR) {
    return 'Automóvil';
  } else if (loanType === LOAN.FURNITURE) {
    return 'Muebles';
  }
  return null;
};

export const formatCurrentDate = (date: Date) => {
  const day = date.getDate().toString().padStart(2, '0');
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const year = date.getFullYear();

  return `${day}/${month}/${year}`;
};

export const formatDateFromString = (dateString: string) => {
  const [year, month, day] = dateString.split('-');

  const formattedDay = day.padStart(2, '0');
  const formattedMonth = month.padStart(2, '0');

  return `${formattedDay}/${formattedMonth}/${year}`;
};

export const formatPriceValue = (value: any, type: PriceType) => {
  switch (type) {
    case PriceType.PRICE:
      return `$${new Intl.NumberFormat('en', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(value)}`;
    case PriceType.PRICE_NEGATIVE:
      return `- $${new Intl.NumberFormat('en', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(value)}`;
    case PriceType.PERCENTAGE:
      return `${value}%`;
    default:
      return value;
  }
};

export const handleWebViewPdfState = () => {
  const ReactNativeWebView = (window as ReactNativeWebViewType)
    .ReactNativeWebView;
  ReactNativeWebView &&
    ReactNativeWebView.postMessage(
      JSON.stringify({
        type: 'PDF_LOADING',
      }),
    );
};

export const handleWebViewPdf = (data: WebViewPdfData[]) => {
  const ReactNativeWebView = (window as ReactNativeWebViewType)
    .ReactNativeWebView;
  const message = {
    type: 'PDF_GENERATED',
    data,
  };

  ReactNativeWebView && ReactNativeWebView.postMessage(JSON.stringify(message));
};

export const calculatePaymentCapacity = (
  mortgageDiscount: number,
  salary: number,
  loanType: LOAN,
  initialMonthlyPayment: number,
  shortTermDiscount: number,
  carDiscount: number,
  furnitureDiscount: number,
) => {
  const percentage = mortgageDiscount > 0 ? 0.4 : 0.3;
  const salaryPercentage = salary * percentage;
  const shortTermD =
    loanType === LOAN.SHORT_TERM && initialMonthlyPayment
      ? shortTermDiscount + initialMonthlyPayment
      : shortTermDiscount;
  const carD =
    loanType === LOAN.CAR && initialMonthlyPayment
      ? carDiscount + initialMonthlyPayment
      : carDiscount;
  const furnitureD =
    loanType === LOAN.FURNITURE
      ? furnitureDiscount + (initialMonthlyPayment || 0)
      : furnitureDiscount;
  const remainingPayment =
    salaryPercentage - shortTermD - carD - furnitureD - mortgageDiscount;

  return {
    percentage,
    salaryPercentage,
    shortTermD,
    carD,
    furnitureD,
    remainingPayment,
  };
};

export const useGenerateBanbajioPDFDownload = () => {
  const margin = 16;
  const { isMobile } = useMobile();

  const generatePDF = async (element: HTMLDivElement, name: string) => {
    const canvas = await html2canvas(element, { scale: 3 });
    const data = canvas.toDataURL('image/webp', 1);
    const pdf = new jsPDF({
      orientation: 'portrait',
      format: 'a4',
    });
    const pdfWidth = pdf.internal.pageSize.getWidth();
    return new Promise(resolve => {
      const img = new Image();
      img.src = data;
      img.onload = () => {
        const imgProperties = pdf.getImageProperties(data);
        const aspectRatio = imgProperties.width / imgProperties.height;
        const width = pdfWidth - margin * 2;
        const height = width / aspectRatio;

        pdf.addImage(data, 'WEBP', margin, margin, width, height, '', 'NONE');
        isMobile
          ? handleWebViewPdf([{ name, url: pdf.output('dataurlstring') }])
          : pdf.save(name);
        resolve(null);
      };
    });
  };
  return generatePDF;
};
