"use client";
import dayjs from "dayjs";

export const generatePDF = (
  accountNo: string,
  balance: string,
  txns: any[],
  customerName: string,
  periodFrom: string,
  periodTo: string,
  // branchName: string,
  branchCode: string,
  cifNumber: string,
  address: string
) => {
  const html2pdf = require("html2pdf.js");

  /* ---------------------------------------------------------
   * 1) BUILD TRANSACTION ROWS
   * --------------------------------------------------------- */

  const rows = txns
    .map((t: any) => {
      return `
        <tr class="txn-row">
          <td style="border:1px solid #d0d0d0;padding:8px 10px;text-align:center;font-size:11px;">${t.date}</td>
          <td style="border:1px solid #d0d0d0;padding:8px 10px;text-align:left;font-size:11px;">${t.name}</td>
          <td style="border:1px solid #d0d0d0;padding:8px 10px;text-align:right;font-size:11px;color:${t.type === "DR" ? "#d32f2f" : "#2e7d32"};font-weight:500;">
            ${parseFloat(t.amount).toLocaleString("en-IN", {
        minimumFractionDigits: 2,
      })} ${t.type}
          </td>
          <td style="border:1px solid #d0d0d0;padding:8px 10px;text-align:right;font-size:11px;font-weight:500;">${t.balance}</td>
        </tr>
      `;
    })
    .join("");

  /* ---------------------------------------------------------
   * 2) MAIN PAGE CONTENT
   * --------------------------------------------------------- */
  const firstPage = `
  <div style="font-family:'Times New Roman', serif; font-size:12px;line-height:1.5;">

    <style>
      @page { 
        margin: 15mm 10mm 20mm 10mm;
      }
      body {
        margin: 0;
        padding: 0;
      }
      .txn-row { 
        page-break-inside: avoid;
      }
      table {
        page-break-inside: auto;
      }
      tr {
        page-break-inside: avoid;
        page-break-after: auto;
      }
      thead {
        display: table-header-group;
      }
      tfoot {
        display: table-footer-group;
      }
    </style>

    <!-- HEADER -->
    <div style="
      display:flex;
      align-items:center;
      gap:12px;
      border-bottom:2px solid #1a5f3a;
      padding-bottom:12px;
      margin-bottom:15px;
    ">
      <img src="/logo.jpg" style="height:55px;width:auto;" />
      <div style="flex:1;">
        <h2 style="margin:0 0 3px 0;font-size:18px;color:#1a5f3a;letter-spacing:0.3px;">
          THE KANGRA CENTRAL CO-OPERATIVE BANK LTD.
        </h2>
        <p style="margin:0;font-size:10px;color:#666;">Head Office: Dharmsala, District Kangra (H.P.), Pin. 176215</p>
      </div>
      <div style="text-align:right;">
        <div style="font-size:11px;font-weight:bold;color:#1a5f3a;margin-bottom:2px;">e-Statement Service</div>
        <div style="font-size:9px;color:#666;">
          Generated: ${dayjs().format("DD/MM/YYYY HH:mm")}
        </div>
      </div>
    </div>

    <!-- ACCOUNT DETAILS -->
    <table style="
      width:100%;
      margin-bottom:12px;
      border:1px solid #d0d0d0;
      background:#f9f9f9;
      border-collapse:collapse;
    ">
      <tr>
        <td style="padding:8px 12px;border-bottom:1px solid #e0e0e0;width:50%;">
          <span style="font-size:10px;color:#666;display:block;margin-bottom:2px;">Account Name</span>
          <strong style="font-size:11px;color:#000;">${customerName}</strong>
        </td>
        <td style="padding:8px 12px;border-bottom:1px solid #e0e0e0;border-left:1px solid #e0e0e0;width:50%;">
          <span style="font-size:10px;color:#666;display:block;margin-bottom:2px;">Branch Name</span>
          <strong style="font-size:11px;color:#000;">${branchCode}</strong>
        </td>
      </tr>
      <tr>
        <td style="padding:8px 12px;border-bottom:1px solid #e0e0e0;">
          <span style="font-size:10px;color:#666;display:block;margin-bottom:2px;">Account Number</span>
          <strong style="font-size:11px;color:#000;">${accountNo}</strong>
        </td>
        <td style="padding:8px 12px;border-bottom:1px solid #e0e0e0;border-left:1px solid #e0e0e0;">
          <span style="font-size:10px;color:#666;display:block;margin-bottom:2px;">Branch Code</span>
          <strong style="font-size:11px;color:#000;">${branchCode}</strong>
        </td>
      </tr>
      <tr>
        <td style="padding:8px 12px;border-bottom:1px solid #e0e0e0;">
          <span style="font-size:10px;color:#666;display:block;margin-bottom:2px;">CIF Number</span>
          <strong style="font-size:11px;color:#000;">${cifNumber}</strong>
        </td>
        <td style="padding:8px 12px;border-bottom:1px solid #e0e0e0;border-left:1px solid #e0e0e0;">
          <span style="font-size:10px;color:#666;display:block;margin-bottom:2px;">Branch Address</span>
          <strong style="font-size:11px;color:#000;">DHARAMSHALA, KANGRA</strong>
        </td>
      </tr>
      <tr>
        <td colspan="2" style="padding:8px 12px;">
          <span style="font-size:10px;color:#666;display:block;margin-bottom:2px;">Address</span>
          <strong style="font-size:11px;color:#000;">${address}</strong>
        </td>
      </tr>
    </table>

    <!-- RED WARNING -->
    <div style="
      margin-bottom:15px;
      border:1px solid #f5c6cb;
      background:#f8d7da;
      padding:10px 12px;
      border-radius:4px;
      border-left:4px solid #d32f2f;
    ">
      <div style="display:flex;gap:10px;align-items:flex-start;">
        <div style="font-size:16px;color:#d32f2f;line-height:1;margin-top:1px;">&#9888;</div>
        <div style="font-size:10px;line-height:1.5;color:#721c24;">
          <strong>NEVER SHARE</strong> your Card number, CVV, PIN, OTP, Internet Banking User ID, Password or URB with
          anyone even if the caller claims to be a bank employee. Sharing these details can lead to unauthorized
          access to your account.
        </div>
      </div>
    </div>

    <!-- PERIOD -->
    <div style="
      text-align:center;
      margin:15px 0 12px 0;
      padding:10px;
      background:#f5f5f5;
      border-top:2px solid #1a5f3a;
      border-bottom:2px solid #1a5f3a;
    ">
      <h3 style="margin:0;font-size:13px;color:#1a5f3a;font-weight:600;">
        Account statement from <strong>${periodFrom}</strong> to <strong>${periodTo}</strong>
      </h3>
    </div>

    <!-- TABLE -->
    <table style="
      width:100%;
      border-collapse:collapse;
      font-size:11px;
      margin-bottom:15px;
      border:1px solid #d0d0d0;
    ">

      <thead style="display:table-header-group;">
        <tr style="background:#2e7d32;color:white;">
          <th style="border:1px solid #1a5f3a;padding:10px 8px;text-align:center;font-weight:600;font-size:11px;width:15%;">Date</th>
          <th style="border:1px solid #1a5f3a;padding:10px 8px;text-align:left;font-weight:600;font-size:11px;width:40%;">Mode / Particulars</th>
          <th style="border:1px solid #1a5f3a;padding:10px 8px;text-align:center;font-weight:600;font-size:11px;width:22.5%;">Withdrawals / Deposits</th>
          <th style="border:1px solid #1a5f3a;padding:10px 8px;text-align:center;font-weight:600;font-size:11px;width:22.5%;">Balance</th>
        </tr>
      </thead>
      <tbody style="background:white;">${rows}</tbody>
    </table>

    <!-- END OF STATEMENT -->
    <div style="
      text-align:center;
      margin-top:20px;
      padding:15px;
      border-top:2px solid #1a5f3a;
      page-break-before:auto;
      page-break-after:always;
    ">
      <p style="font-weight:bold;font-size:12px;color:#1a5f3a;margin:0;letter-spacing:1px;">
        *** END OF STATEMENT ***
      </p>
    </div>
  </div>
  `;

  /* ---------------------------------------------------------
   * 3) LAST PAGE
   * --------------------------------------------------------- */
  const lastPage = `
  <div style="font-family:'Times New Roman', serif; font-size:11px;line-height:1.6;margin-top:0;padding-top:20px;">
    <div style="
      border:2px solid #1a5f3a;
      padding:20px 25px;
      margin:0 20px;
      background:#fafafa;
      border-radius:4px;
    ">
      <h3 style="
        font-weight:bold;
        margin:0 0 15px 0;
        font-size:14px;
        color:#1a5f3a;
        border-bottom:2px solid #1a5f3a;
        padding-bottom:8px;
      ">IMPORTANT INFORMATION:</h3>
      
      <div style="color:#333;">
        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          The Kangra Central Cooperative Bank Officials or representatives will NEVER ask you for your personal information i.e. your card details, passwords, PIN, CVV, OTP etc. Do not share such details with anyone over phone, SMS or email.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Always stay vigilant to suspicious emails. Do not open any suspicious emails.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Always stay vigilant when giving out sensitive personal or account information.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Beware of messages that instill a sense of urgency (e.g., account will expire unless you "verify" your information). Contact the Bank directly if unsure.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Always log out of secondary devices and reset your passwords frequently.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Use strong passwords: Create strong passwords that are difficult for hackers to guess.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Use public Wi-Fi with caution: Be careful when using public Wi-Fi networks.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Back up your data regularly to a secure, encrypted, off-site location.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Follow corporate security policies: Adhere to your company's security guidelines.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Assess third-party app permissions carefully before granting access.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Lock your computer and mobile phone when not in use.
        </p>

        <p style="margin:0 0 10px 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Don't leave devices unattended. Keep all mobile devices, such as laptops and cell phones, physically secured.
        </p>

        <p style="margin:0 0 0 0;padding-left:15px;position:relative;">
          <span style="position:absolute;left:0;color:#1a5f3a;">•</span>
          Don't leave Bluetooth / Wireless turned on when not in use. Enable them only when needed and in a safe environment.
        </p>
      </div>
    </div>
  </div>
  `;

  /* ---------------------------------------------------------
   * 4) PDF GENERATION
   * --------------------------------------------------------- */
  const opt = {
    margin: [15, 10, 20, 10],
    filename: `Statement_${accountNo}_${dayjs().format("DDMMYYYY_HHmm")}.pdf`,
    image: { type: "jpeg", quality: 0.98 },
    html2canvas: { 
      scale: 2, 
      useCORS: true,
      letterRendering: true,
    },
    jsPDF: { 
      unit: "mm", 
      format: "a4", 
      orientation: "portrait",
      compress: true,
    },
    pagebreak: { 
      mode: ["css", "legacy"],
      before: '.page-break-before',
      after: '.page-break-after',
      avoid: ['tr', '.txn-row']
    },
  };

  html2pdf()
    .set(opt)
    .from(firstPage + lastPage)
    .toPdf()
    .get("pdf")
    .then((pdf: any) => {
      const total = pdf.internal.getNumberOfPages();
      const w = pdf.internal.pageSize.getWidth();
      const h = pdf.internal.pageSize.getHeight();

      const hasGState =
        typeof pdf.GState === "function" && typeof pdf.setGState === "function";

      for (let i = 1; i <= total; i++) {
        pdf.setPage(i);

        /* LIGHT WATERMARK */
        try {
          if (hasGState) {
            const light = pdf.GState({ opacity: 0.03 });
            pdf.setGState(light);
            pdf.addImage("/kccb_watermark.png", "PNG", 35, 70, 140, 140);
            pdf.setGState(pdf.GState({ opacity: 1 }));
          } else {
            pdf.addImage("/kccb_watermark.png", "PNG", 35, 70, 140, 140);
          }
        } catch { }

        /* FOOTER */
        pdf.setFont("times", "italic");
        pdf.setFontSize(9);
        pdf.setTextColor(100, 100, 100);
        pdf.text(
          "** This is only for information purpose and not for legal use **",
          w / 2,
          h - 12,
          { align: "center" }
        );

        /* PAGE NUMBER */
        pdf.setFont("times", "normal");
        pdf.setFontSize(9);
        pdf.setTextColor(0, 0, 0);
        pdf.text(`Page ${i} of ${total}`, w - 15, h - 12, {
          align: "right",
        });
      }
    })
    .save();
};
