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 moment from "moment";
import { string } from "zod";

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 createReceiptOld = async (details: propType) => {
  try {
    let receiptHtml = `
            <table style="width:100%;padding-left:80px;margin-top:50px;padding-right:80px;background-color:#fff;  font-family:Arial, Helvetica, sans-serif">
                <tr><td style="border-bottom:6px solid #15b36a;padding-top:40px;width:70%"></td>
                <td style="border-bottom:6px solid #15b36a;padding-top:40px;width:30%"></td></tr>
                <tr><th style="text-align:left;width:70%;height:25px; font-size:16px;">${
                  details.title
                } Receipt</th>
                <th style="text-align:right;width:30%;height:25px; font-size:9px;">Dated: ${
                  details.paidDate
                }</th></tr>
            </table>
            <table style="width:100%;padding-left:80px;margin-top:50px;padding-right:80px;background-color:#fff; font-size:14px; line-height:1.5;">
                <tr style="border:1px solid green"><td style="width:100%;height:80px">
                This is to acknowledge the receipt from ${
                  details.tenantName
                } the sum of Rs.<b>${details.amount}/-</b>
                (${getIndianCurrency(
                  details.amount
                )}) towards ${details.title.toLowerCase()} payment for the month of ${
      details.month
    }</b> towards the property bearing the address <b>${details.address}</b>.
                </td></tr>
            </table>
            <table style="width:100%;padding-left:80px;margin-top:35px;padding-right:80px;background-color:#fff; ">
                <tr><td style="width:60%;height:25px; font-size:14px;"><p><b>Landlord Details</b></p></td>
                <td style="width:40%;height:25px;text-align:right; font-size:14px;"><b>Signature</b></td></tr>
                <tr><td style="width:60%;height:25px; font-size:14px;">${
                  details.landlord
                }</td>
                <td style="width:40%;text-align:right;height:25px; font-size:14px;">(${
                  details.landlord
                })</td></tr>
            `;

    if (details["landlord-pan"] !== "") {
      receiptHtml += `<tr><td style="width:100%; height:25px; font-size:14px;">PAN: ${details["landlord-pan"]}</td></tr>`;
    }

    receiptHtml += `</table>
            <table style="width:100%;padding-left:80px;margin-top:50px;padding-right:80px;background-color:#fff">
                <tr><td style="width:100%;text-align:center;padding-top:5px;height:25px;color:#aaa5a5; font-size:14px;">
                This is system generated from Kipinn</td></tr>
            </table>
            <table style="width:100%;padding-left:80px;margin-top:20px;padding-right:80px;background-color:#fff">
                <tr><td><hr></td></tr>
            </table>`;

    const { tenantId, clientId, propId, roomId, bedId } = details.occupancy;

    const folderName = `tenant_${tenantId}`;

    const folderPath = `uploads/documents/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/client_${clientId}/prop_${propId}/room_${roomId}_bed_${bedId}/${folderName}`;

    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(
      `[createReceipt], Tenant Name [${details.tenantName}], Start Date [${
        details.paidDate
      }], Error: ${
        JSON.stringify(error?.response?.data) || error?.message || error
      }`
    );

    return false;
  }
};
const createReceipt = async (details: propType) => {
  try {
    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;
      }
      .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: 80%;">${details.propName}</h1></td>
          <td rowspan="2" style="width: 20%; text-align: right;"><img src="${details.logo}" alt=""></td>
        </tr>
        <tr>
          <td><p style="text-align: left; font-size:12px">${details.address}</p></td>
        </tr>
      </table>
    </div>
      <div class="highlight">
        <table class="table">
          <tbody>
            <tr>
              <td style="color: grey;">Payee Name</td>
              <td>${details.tenantName}</td>
              <td style="color: grey;">Owner 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>${details.transGId}</td>
              <td style="color: grey;">GST No</td>
              <td>-</td>
            </tr>
            <tr>
              <td style="color: grey;">Payment Date</td>
              <td>${details.paidDate}</td>
              <td style="color: grey;">Payment Mode</td>
              <td>${details.mode}</td>
            </tr>
          </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>
            <tr style="border-bottom: 1px solid #0078BD">
              <td style="width:70%">${details.title}</td>
              <td style="width:30%;text-align: center;">₹ ${details.amount}</td>
            </tr>

            <tr>
            <td><strong>Amount Paid by Tenant</strong></td>
            <td style="text-align: center;"><strong>₹ ${details.amount}</strong></td>
          </tr>
          </tbody>
        </table>
      </div>

     
      <div class="terms">
        <p><strong>Terms & Conditions:</strong></p>
        <ul>
          <li>
            This is an acknowledgment receipt of the payment made by the tenant
            through whatsoever mode of payment for the corresponding services.
          </li>
          <li>
            If an online payment fails for any reason, this receipt will be considered null and void.
          </li>
          <li>
            Refunds will not be provided under any circumstances for this receipt.
          </li>
        </ul>
      </div>
      <div class="powered-by">
        <strong>Powered by Kipinn</strong>
      </div>
    </div>
  </body>`;

    const { tenantId, clientId, propId, roomId, bedId } = details.occupancy;

    const folderName = `tenant_${tenantId}`;

    const folderPath = `uploads/documents/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/client_${clientId}/prop_${propId}/room_${roomId}_bed_${bedId}/${folderName}`;

    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(
      `[createReceipt], 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 createReceipt;
