import log from "../config/log";
import CONSTANTS from "../config/constants";
import fs from "fs";
import fsPromises from "fs/promises";
import occupanciesTypes from "../schemas/occupancy.schema";
// @ts-ignore
import pdf from "pdf-creator-node";
import transactionDB from "../models/transaction.model";
import getRentReciptPoints from "./getRentReciptPoints";
import moment from "moment";
import { string } from "zod";
import settingsDB from "../models/settings.model";


type propType = {
  title: string;
  roomNum: string;
  mode: string;
  dueDate: string;
  propName: string;
  transGId: string;
  paidDate: string;
  month: string;
  tenantName: string;
  amount: number;
  address: string;
  landlord: string;
  landlordNumber: string;
  logo: string;
  "landlord-pan"?: string;
  occupancy: occupanciesTypes;
  flatName: string;
  propType: number;
};

const createReceiptMultipleDues = async (details: any) => {
  try {
    let transactionId = details.transGId;
    if (transactionId.length > 16) {
      transactionId = `${details.transGId.substring(0, 20)}`;
    }
    //log.info(`[createReceiptMultipleDues], [${JSON.stringify(details)}]`);
    const { tenantId, clientId, propId, roomId, bedId } = details.occupancy;
    let settings = await settingsDB.getByClientIdAndPropId({
      clientId: clientId,
      propId: propId,
    });
    let propertyName = details.propName;
    if(settings?.brandName) {
      propertyName = settings?.brandName;
    }
    details.address = details.address.length > 40 ? details.address.substring(0, 40) + "..." : details.address;
    let terms = await getRentReciptPoints(clientId);
    let receiptHtml = `<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Rent Receipt</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        zoom: 0.80;
      }
      .container {
        padding: 1em;
        margin: 0 auto;
      }
      .header {
        background-color: #0078BD;
        color: white;
        text-align: center;
        padding: 1em;
        height: auto;
      }
      .header img {
        max-width: 120px;
        max-height: 80px
      }
      .header h1 {
        margin: 0;
        font-size: 1.5em;
      }
      .header p {
        font-size: 0.9em;
        margin: 0.2em 0;
      }
      .table {
        width: 100%;
        border-spacing: 0;
        border-collapse: collapse;
      }
      .table td {
        padding: 0.5em;
        text-align: left;
      }
      .table th {
        background-color: #0078BD;
        color: white;
         width: 100%;
      }
      .highlight {
        width: 100%;
        padding-top: 1em;
        padding-bottom: 1em;
        margin: 1em 0;
      }
      .payment-details
      {
        margin: 1em 0;
        margin-bottom: 50px;
      }
      .terms
      {
        font-size: 0.8em;
      }
      .terms ul {
        padding-left: 1.5em;
      }
      .powered-by {
        position: absolute;
        bottom: 0;
        width: 100%;
        background-color: #0078BD;
        color: white;
        text-align: center;
        padding: 2px;
        font-size: 8px;
      }
      @media (max-width: 600px) {
        .header h1 {
          font-size: 1.2em;
        }
        .table th,
        .table td {
          font-size: 0.9em;
        }
        .powered-by {
           padding-bottom: 5px;
          padding-top: 5px;
          font-size: 0.5em;
        }
      }    
    </style>
  </head>
  <body>
    <div class="container">
     <div class="header">
      <table style="width: 100%; color: white;">
        <tr>
          <td><h1 style="text-align: left; width: 85%;">${propertyName}</h1></td>
          <td rowspan="2" style="width: 15%; text-align: right;"><img height="50" src="${details.logo}" alt=""></td>
        </tr>
        <tr>
          <td><p style="text-align: left; font-size:12px">${details.address}</p></td>
        </tr>
      </table>
    </div>`;
    if(1 === details.isGstEnabled) {
    receiptHtml += `<div class="highlight" style="padding-top: 0;padding-bottom: 0;">
            <table class="table">
                <tbody>
                    <tr>
                        <td style="width: 30%"></td>
                        <td style="width: 30%"></td>
                        <td style="width: 20%"></td>
                        <td style="width: 20%"><span style="color: grey;">Invoice No#</span>${details.transactionInvoiceNo}</td>
                    </tr>
                    <tr>
                        <td style="width: 30%"></td>
                        <td style="width: 30%"></td>
                        <td style="width: 20%;"></td>
                        <td style="width: 20%"><span style="color: grey;">GST#</span>${details.gstNo}</td>
                    </tr>
                </tbody>
            </table>
      </div>`;
    }
      receiptHtml += `<div class="highlight" style="padding-top: 0;">
        <table class="table">
          <tbody>
            <tr>
              <td style="color: grey;">Payee Name</td>
              <td>${details.tenantName}</td>
              <td style="color: grey;">Name</td>
              <td>${details.landlord}</td>
            </tr>
            <tr>`;
    if (details.propType === CONSTANTS.PROPERTY_TYPE.FLAT) {
      receiptHtml += `<td style="color: grey;">Flat No</td>
              <td>${details.flatName} (${details.roomNum})</td>`;
    } else {
      receiptHtml += `<td style="color: grey;">Room No</td>
              <td>${details.roomNum}</td>`;
    }
    receiptHtml += `<td style="color: grey;">Contact No</td>
              <td>${details.landlordNumber}</td>
            </tr>
            <tr>
              <td style="color: grey;">Transaction ID</td>
              <td>${transactionId}</td>
              <td style="color: grey;">Payment Date</td>
              <td>${details.paidDate}</td>
            </tr>
            <tr>
              <td style="color: grey;">Payment Mode</td>
              <td>${details.mode}</td>
              <td style="color: grey;"></td>
              <td></td>
            </tr>`;
    
    receiptHtml += `</tbody>
        </table>
      </div>
      <div class="payment-details">
        <table class="table">
          <thead>
            <tr style="font-size: 14px">
              <th style="text-align: left; padding-left: 10px;width:70%;">Payment Details</th>
              <th style="text-align: center;width:30%">Paid Amount</th>
            </tr>
          </thead>
          <tbody>`;
    for (const dueStat of details.dueStats) {
      receiptHtml += `<tr style="border-bottom: 1px solid #0078BD">
            <td style="width:70%">${dueStat.title}</td>
            ${
              dueStat.amount < 0 
              ? `<td style="width:30%;text-align: right;padding-right: 10%">-₹${Math.abs(dueStat.amount)}</td>` 
              : `<td style="width:30%;text-align: right;padding-right: 10%">₹${dueStat.amount}</td>`
            } 
                  </tr>
            `;
    }
    receiptHtml += `
            <tr>
              <td><strong>Amount Paid by Tenant</strong></td>
              <td style="text-align: right;padding-right: 10%"><strong>₹${details.amount}</strong></td>
            </tr>
          </tbody>
        </table>
      </div>

     
      <div class="terms">
        <p><strong>Terms & Conditions:</strong></p>
	${terms}
      </div>
      <div class="powered-by">
        <strong>Powered by Kipinn</strong>
      </div>
    </div>
  </body>`;


    const folderName = `tenant_${tenantId}`;
    const currentYear = moment().year();
    const folderPath = `uploads/documents/${currentYear}/receipt/client_${clientId}/prop_${propId}/room_${roomId}_bed_${bedId}/${folderName}`;

    if (!fs.existsSync(folderPath)) {
      await fsPromises.mkdir(folderPath, { recursive: true });
    }

    const urlBasePath = `${process.env.UPLOAD_PATH}/documents/${currentYear}/receipt/client_${clientId}/prop_${propId}/room_${roomId}_bed_${bedId}/${folderName}`;

    const filename = `Receipt_${moment(details.paidDate).format("YYYYMMDD")}_${bedId}_${new Date().getTime().toString().slice(5)}.pdf`;
    // const filename = `${details.title.split(" ").join("_")}_${moment(
    //   details.month
    // ).format("MMM_YYYY")}(${new Date().getTime().toString().slice(5)}).pdf`;

    const url = `${urlBasePath}/${filename}`;

    var document = {
      html: receiptHtml,
      path: `${folderPath}/${filename}`,
      data: {},
      type: "",
    };

    const options = {
      format: "A4",
      orientation: "portrait",
      border: "10mm",
      childProcessOptions: {
        env: {
          OPENSSL_CONF: "/dev/null",
        },
      },
    };

    await pdf.create(document, options);

    return url;
  } catch (error: any) {
    log.info(
      `[createReceiptMultipleDues], Tenant Name [${
        details.tenantName
      }], Start Date [${details.paidDate}], Error: ${
        JSON.stringify(error?.response?.data) || error?.message || error
      }`
    );

    return false;
  }
};

function getIndianCurrency(number: number) {
  let decimal = Math.round((number - Math.floor(number)) * 100);
  let no = Math.floor(number);
  let digits_length = no.toString().length;
  let i = 0;
  let str: (string | null)[] = [];
  let words: { [key: number]: string } = {
    0: "",
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four",
    5: "Five",
    6: "Six",
    7: "Seven",
    8: "Eight",
    9: "Nine",
    10: "Ten",
    11: "Eleven",
    12: "Twelve",
    13: "Thirteen",
    14: "Fourteen",
    15: "Fifteen",
    16: "Sixteen",
    17: "Seventeen",
    18: "Eighteen",
    19: "Nineteen",
    20: "Twenty",
    30: "Thirty",
    40: "Forty",
    50: "Fifty",
    60: "Sixty",
    70: "Seventy",
    80: "Eighty",
    90: "Ninety",
  };
  let digits = ["", "Hundred", "Thousand", "Lakh", "Crore"];

  while (i < digits_length) {
    let divider = i == 2 ? 10 : 100;
    let numberPart: number = Math.floor(no % divider);
    no = Math.floor(no / divider);
    i += divider == 10 ? 1 : 2;

    if (numberPart) {
      let plural: string = str.length && numberPart > 9 ? "s" : "";
      let hundred: string = str.length == 1 && str[0] ? " and " : "";
      str.push(
        numberPart < 21
          ? (words[numberPart] || "") +
              " " +
              digits[str.length] +
              " " +
              plural +
              hundred
          : (words[Math.floor(numberPart / 10) * 10] || "") +
              " " +
              (words[numberPart % 10] || "") +
              " " +
              digits[str.length] +
              " " +
              plural +
              hundred
      );
    } else {
      str.push(null);
    }
  }

  let Rupees = str.reverse().filter(Boolean).join("");
  let Paise =
    decimal > 0
      ? "." +
        ((words[Math.floor(decimal / 10)] || "") +
          " " +
          (words[decimal % 10] || "")) +
        " Paise"
      : "";
  return (Rupees ? Rupees + "Rupees " : "") + Paise;
}

export default createReceiptMultipleDues;
