import { React, useState, useContext, useEffect } from "react";

import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Button } from "primereact/button";
import { useRef } from "react";
import axios from "axios";
import { Toast } from "primereact/toast";
import { AutoComplete } from "primereact/autocomplete";
import { authUser } from "@/Components/AuthProvider";
import { Calendar } from "primereact/calendar";
import { Dropdown } from "primereact/dropdown";
import { SHOP_INFO } from "@/Utils/constants";
function DailyKhataReport({ auth }) {
  const { permission, warehouseList } = useContext(authUser);
  const [type, setType] = useState("All");
  const [startDate, setStartDate] = useState();
  const [endDate, setEndDate] = useState();
  const [location, setLocation] = useState([]);
  const [data, setData] = useState([]);

  const [expanse, setExpanse] = useState([]);
  const [payment, setPayment] = useState([]);
  const [opening, setOp] = useState(0);

  const [shop, setShop] = useState([]);
  const conponentPDF = useRef();
  const toast = useRef(null);

  const [customer, setCustomer] = useState([]);
  const [salesRerun, setSalesReturn] = useState([]);
  const [customerId, setCustomerID] = useState(null);
  const [searchCustomer, setSearchValue] = useState({
    customer: "",
  });

  const cols = [
    { field: "index", header: "SINo" },
    { field: "opening_date", header: "Opening Date" },
    { field: "name", header: "Name" },
    { field: "number", header: "Number" },
    { field: "company", header: "Company" },
    { field: "opening_balance", header: "Opening Balance" },
  ];

  const exportColumns = cols.map((col) => ({
    title: col.header,
    dataKey: col.field,
  }));

  useEffect(() => {
    axios.get("daily-khata-report-search").then((res) => {
      setData(res.data);
    });

    if (!permission.includes("report_super_admin_access")) {
      setLocation(auth.user.shop_id);
    }
  }, []);

  const dateWise = (date, location_id = null) => {
    if (date) {
      axios
        .get("daily-khata-report-search", {
          params: {
            startDate: new Date(date).toLocaleDateString("en-US"),
            location_id: location_id ? location_id : location,
          },
        })
        .then((res) => {
          setData(res.data);
        });
    } else {
      toast.current.show({
        severity: "warn",
        summary: "Warning",
        detail: "Please select start date",
        life: 3000,
      });
    }
  };

  const handlePrint = () => {
    const printContent = document.getElementById('daily-khata-content');
    const originalContent = document.body.innerHTML;

    // Create a new window for printing
    const printWindow = window.open('', '_blank', 'width=800,height=600');

    printWindow.document.write(`
            <html>
                <head>
                    <title>Daily Khata Report</title>
                    <style>
                        body { 
                            font-family: Arial, sans-serif; 
                            margin: 20px;
                            font-size: 12px;
                        }
                        .print-header {
                            text-align: center;
                            margin-bottom: 20px;
                            border-bottom: 2px solid #333;
                            padding-bottom: 10px;
                        }
                        .print-date-info {
                            margin-bottom: 20px;
                            font-weight: bold;
                        }
                        table { 
                            width: 100%; 
                            border-collapse: collapse; 
                            margin-bottom: 20px;
                        }
                        th, td { 
                            border: 1px solid #ddd; 
                            padding: 8px; 
                            text-align: left; 
                        }
                        th { 
                            background-color: #f5f5f5; 
                            font-weight: bold;
                        }
                        .total-row { 
                            background-color: #f0f0f0; 
                            font-weight: bold; 
                        }
                        .closing-cash {
                            background-color: #e3f2fd;
                            padding: 10px;
                            border: 1px solid #2196f3;
                            border-radius: 4px;
                            font-weight: bold;
                            text-align: center;
                            margin-top: 20px;
                        }
                        .tables-container {
                            display: flex;
                            gap: 20px;
                        }
                        .table-section {
                            flex: 1;
                        }
                        .received-header {
                            background-color: #c8e6c9 !important;
                        }
                        .payment-header {
                            background-color: #ffcdd2 !important;
                        }
                        @media print {
                            body { margin: 0; }
                            .no-print { display: none; }
                        }
                    </style>
                </head>
                <body>
                    <div class="print-header">
                        <h1>${SHOP_INFO.name}</h1>
                  
                        <p>${SHOP_INFO.address}</p>
                        ${SHOP_INFO.phone ? `<p>Phone: ${SHOP_INFO.phone}</p>` : ''}
                        <p>Email: ${SHOP_INFO.email}</p>
                        <p style="margin-top: 10px; color: #666;">Printed on: ${new Date().toLocaleDateString()}</p>
                        <h2>Daily Khata Report</h2>
                    </div>
                    
                    <div class="print-date-info">
                        <p><strong>Date:</strong> ${new Date().toLocaleDateString("en-US")}</p>
                        <p><strong>Opening Cash In Hand:</strong> ${Number(data?.OpeningCashInHand || 0).toFixed(2)}</p>
                    </div>

                    <div class="tables-container">
                        <div class="table-section">
                            <table>
                                <thead>
                                    <tr class="received-header">
                                        <th colspan="2">Received</th>
                                    </tr>
                                    <tr>
                                        <th style="width: 65%">Particulars</th>
                                        <th style="width: 35%; text-align: right;">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${data?.toDayCollection?.map(item => `
                                        <tr>
                                            <td>Sales Collection from ${item?.customer?.name} ${item?.customer?.code} ${item?.invoice ? `-(${item?.invoice?.invoice_no})` : ''}</td>
                                            <td style="text-align: right;">${Number(item?.payment || 0).toFixed(2)}</td>
                                        </tr>
                                    `).join('') || ''}
                                    ${data?.toDayIncome?.map(income => `
                                        <tr>
                                            <td>Income ${income?.catagory?.category}</td>
                                            <td style="text-align: right;">${Number(income?.amount || 0).toFixed(2)}</td>
                                        </tr>
                                    `).join('') || ''}
                                    ${data?.toDayLoanEntry?.map(item => `
                                        <tr>
                                            <td>Loan Entry (${item?.provider?.name || ''})</td>
                                            <td style="text-align: right;">${Number(item?.amount || 0).toFixed(2)}</td>
                                        </tr>
                                    `).join('') || ''}
                                    <tr class="total-row">
                                        <td><strong>Total Received</strong></td>
                                        <td style="text-align: right;"><strong>${Number(totalReceived || 0).toFixed(2)}</strong></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <div class="table-section">
                            <table>
                                <thead>
                                    <tr class="payment-header">
                                        <th colspan="2">Payment</th>
                                    </tr>
                                    <tr>
                                        <th style="width: 65%">Particulars</th>
                                        <th style="width: 35%; text-align: right;">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${data?.toDaySupplierPayment?.map(item => `
                                        <tr>
                                            <td>Payment to ${item?.supplier?.name} ${item?.supplier?.code}</td>
                                            <td style="text-align: right;">${Number(item?.payment || 0).toFixed(2)}</td>
                                        </tr>
                                    `).join('') || ''}
                                    ${data?.toDayExpance?.map(item => `
                                        <tr>
                                            <td>${item?.catagory?.category}</td>
                                            <td style="text-align: right;">${Number(item?.amount || 0).toFixed(2)}</td>
                                        </tr>
                                    `).join('') || ''}
                                    ${data?.toDaySalesReturn?.map(item => `
                                        <tr>
                                            <td>Sales Return ${item?.customer?.name} ${item?.customer?.code} ${item?.reference_no ? `-(${item?.reference_no})` : ''}</td>
                                            <td style="text-align: right;">${Number(item?.total || 0).toFixed(2)}</td>
                                        </tr>
                                    `).join('') || ''}
                                    ${data?.toDayLoanPayment?.map(item => `
                                        <tr>
                                            <td>Loan Payment ${item?.loan?.provider?.name ? `-(${item.loan.provider.name})` : ''}</td>
                                            <td style="text-align: right;">${Number(item?.amount || 0).toFixed(2)}</td>
                                        </tr>
                                    `).join('') || ''}
                                    ${data?.toDayEmployeeSalary?.map(item => `
                                        <tr>
                                            <td>Employee Salary ${item?.employee?.user?.name ? `-(${item.employee.user.name})` : ''}</td>
                                            <td style="text-align: right;">${Number(item?.amount || 0).toFixed(2)}</td>
                                        </tr>
                                    `).join('') || ''}
                                    <tr class="total-row">
                                        <td><strong>Total Payment</strong></td>
                                        <td style="text-align: right;"><strong>${Number(totalPayment || 0).toFixed(2)}</strong></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="closing-cash">
                        Closing Cash In Hand: ${Number(closingCashInHand || 0) < 0 ? '(' + Math.abs(Number(closingCashInHand || 0)).toFixed(2) + ')' : Number(closingCashInHand || 0).toFixed(2)}
                    </div>
                </body>
            </html>
        `);

    printWindow.document.close();
    printWindow.focus();

    // Wait for content to load then print
    setTimeout(() => {
      printWindow.print();
      printWindow.close();
    }, 250);
  };

  const exportPDF = () => {
    import("jspdf").then((jsPDF) => {
      import("jspdf-autotable").then(() => {
        const doc = new jsPDF.default("p", "mm", "a4");
        const pageWidth = doc.internal.pageSize.getWidth();

        // Add a title or header above the table
        doc.setFontSize(15);
        doc.setFont("Arial", "bold");
        doc.text("Unity", 70, 20); // Position the header at (x, y)

        doc.setFontSize(12);
        doc.setFont("Arial", "bold");
        doc.text("Customer or Retailer Opening Balance.", 70, 27);

        // Add start date and end date
        const startDateText = `Start Date: ${new Date(
          startDate
        ).toLocaleDateString("en-US")}`;
        const endDateText = endDate
          ? `to End Date: ${new Date(endDate).toLocaleDateString(
            "en-US"
          )}`
          : "";
        const dateText = endDate
          ? `${startDateText} ${endDateText}`
          : startDateText;
        const dateTextWidth = doc.getTextWidth(dateText);
        doc.setFontSize(10);
        doc.setFont("Arial", "normal");

        doc.text(dateText, (pageWidth + 14 - dateTextWidth) / 2, 33);

        // Format the data to include the formatted date
        const formattedData = dailyKhataReport.map((item, index) => ({
          ...item,
          index: index + 1,
          opening_date: new Date(
            item.opening_date
          ).toLocaleDateString("en-US"),
          name:
            item?.customer_opening?.client.name +
            " (" +
            item?.customer_opening?.client.code +
            ")",
          number: item?.customer_opening?.client.number,
          company: item.supplier ? item.supplier.name : "N/A",
          opening_balance: item.opening_balance
            ? `${item.opening_balance} `
            : "N/A",
        }));

        // Calculate the total of opening balances
        const totalOpeningBalance = formattedData.reduce(
          (sum, item) => sum + Number(item?.opening_balance || 0),
          0
        );
        // Customize header styles
        const headStyles = {
          fillColor: [69, 69, 69], // Background color (RGB)
          textColor: [255, 255, 255], // Text color (RGB)
          fontStyle: "bold", // Font style
          halign: "center", // Horizontal alignment (center)
        };

        // Customize body styles
        const bodyStyles = {
          lineWidth: 0.1, // Border width for body
          lineColor: [69, 69, 69], // Border color (RGB)
        };
        const footerStyles = {
          fillColor: [69, 69, 69], // Background color (RGB)
          textColor: [255, 255, 255], // Text color (RGB)
        };
        const columnStyles = {
          opening_date: { halign: "center" }, // Center align for this column
          name: { halign: "left" }, // Left align for this column
          number: { halign: "center" }, // Right align for this column
          company: { halign: "center" }, // Left align for this column
          opening_balance: { halign: "right" }, // Right align for this column
        };
        doc.autoTable(exportColumns, formattedData, {
          headStyles: headStyles, // Apply header styles
          columnStyles: columnStyles,
          bodyStyles: bodyStyles,
          theme: "grid",
          didDrawCell: function (data) {
            let doc = data.doc;
            let lastY = data.cell.y + data.cell.height + 6; // Adjust the position below the table
            // Check if the current cell is the last cell of the last row
            doc.setFontSize(13);
            doc.setFont("Arial", "bold");
            // Set font to bold for the totals

            if (
              data.row.index === data.table.body.length - 1 &&
              data.column.index === data.table.columns.length - 1
            ) {
              // Add your custom content below the table
              // Calculate the x positions for right-aligned text
              const pageWidth = doc.internal.pageSize.getWidth();
              const totalSalesString =
                "Total value:  " +
                Number(totalOpeningBalance || 0).toFixed(2);

              const totalPurchaseWidth =
                doc.getTextDimensions(totalSalesString).w;

              const salesX = pageWidth - totalPurchaseWidth - 14; // Adjust padding as needed

              // Add the text
              doc.text(totalSalesString, salesX, lastY);

              // Add the text
            }
          },
          footStyles: footerStyles,
          startY: 40, // Adjust this value to position the table below the header
        });
        doc.save(`Customer/Retailer Opening ${dateText}.pdf`);
      });
    });
  };

  let collectionTotal = data?.toDayCollection?.reduce((acc, item) => {
    const payment = Number(item?.payment || 0);
    return acc + payment;
  }, 0) || 0;

  let incomeTotal = data?.toDayIncome?.reduce((acc, item) => {
    const amount = Number(item?.amount || 0);
    return acc + amount;
  }, 0) || 0;

  // Loan entries considered as income (cash in) when apply_on_cash = 1 and running
  let loanEntryTotal = data?.toDayLoanEntry?.reduce((acc, item) => {
    const amount = Number(item?.amount || 0);
    return acc + amount;
  }, 0) || 0;

  let totalReceived = collectionTotal + incomeTotal + loanEntryTotal;

  let paymentTotal = data?.toDaySupplierPayment?.reduce((acc, item) => {
    const payment = Number(item?.payment || 0);
    return acc + payment;
  }, 0) || 0;

  let expanceTotal = data?.toDayExpance?.reduce((acc, item) => {
    const amount = Number(item?.amount || 0);
    return acc + amount;
  }, 0) || 0;

  let salesReturnTotal = data?.toDaySalesReturn?.reduce((acc, item) => {
    const total = Number(item?.total || 0);
    return acc + total;
  }, 0) || 0;

  let loanPaymentTotal = data?.toDayLoanPayment?.reduce((acc, item) => {
    const amount = Number(item?.amount || 0);
    return acc + amount;
  }, 0) || 0;

  // Employee salaries (cash out)
  let salaryPaymentTotal = data?.toDayEmployeeSalary?.reduce((acc, item) => {
    const amount = Number(item?.amount || 0);
    return acc + amount;
  }, 0) || 0;

  let totalPayment = paymentTotal + expanceTotal + salesReturnTotal + loanPaymentTotal + salaryPaymentTotal;
  let closingCashInHand = Number(data?.OpeningCashInHand || 0) + totalReceived - totalPayment;

  return (
    <AuthenticatedLayout
      user={auth.user}
      header={
        <>
          <h2 className="text-skin-header font-medium ">
            Daily Khata
          </h2>{" "}
          <p className="text-skin-sub-header font-semibold text-xs">
            {" "}
            Home - Daily-Khata
          </p>
        </>
      }
      headerButton={<></>}
    >
      <Toast ref={toast} />

      <div className="card p-5">
        <div className="flex flex-wrap items-center gap-4 mb-5">
          <Calendar
            value={startDate}
            className="w-full md:w-1/6"
            placeholder="Start Date"
            onChange={(e) => {
              setStartDate(e.value), dateWise(e.value);
            }}
          />
          {permission.includes("report_super_admin_access") && (
            <Dropdown
              value={location}
              options={warehouseList}
              optionLabel="name"
              optionValue="id"
              placeholder="Select a Warehouse"
              showClear
              disabled={
                !permission.includes("report_super_admin_access")
              }
              onChange={(e) => {
                setLocation(e.target.value ?? null);
                dateWise(startDate, e.target.value);
              }}
              className="w-full md:w-1/6 rounded-lg shadow-sm"
              inputClassName="h-11 px-4 text-sm"
            />
          )}
          <Button
            icon="pi pi-print"
            label="Print"
            onClick={handlePrint}
            className="p-button-outlined p-button-secondary"
            disabled={!data || Object.keys(data).length === 0}
          />
        </div>

        <div className="relative overflow-x-auto sm:rounded-lg" id="daily-khata-content">
          <div>
            <p>Date: {new Date().toLocaleDateString("en-us")}</p>
            <p>Opening Cash In Hand: {Number(data?.OpeningCashInHand || 0).toFixed(2)}</p>
          </div>

          {/* Shop Info Header - Hidden on screen, visible when printing */}
          <div className="text-center mb-6 pb-4 print:block hidden">
            <h1 className="text-2xl font-bold text-gray-800 uppercase">
              {SHOP_INFO.name}
            </h1>
            <p className="text-sm text-gray-600 mt-1">
              {SHOP_INFO.businessType} | Owner:{" "}
              {SHOP_INFO.owner}
            </p>
            <p className="text-sm text-gray-600">
              {SHOP_INFO.address}
            </p>
            {SHOP_INFO.phone && (
              <p className="text-sm text-gray-600">
                Phone: {SHOP_INFO.phone}
              </p>
            )}
            <p className="text-sm text-gray-600">
              Email: {SHOP_INFO.email}
            </p>
            <p className="text-sm text-gray-500 mt-2">
              Printed on: {new Date().toLocaleDateString()}
            </p>
            <h2 className="text-xl font-bold text-gray-800 mt-4">
              Daily Khata Report
            </h2>
          </div>
        </div>

        <div className="w-full mt-10">
          <div class="flex flex-col md:flex-row gap-6">
            <div class="w-full md:w-1/2">
              <table class="w-full border border-gray-300 shadow rounded-md table-auto">
                <thead>
                  <tr class="bg-green-100">
                    <th
                      colspan="2"
                      class="px-4 py-2 text-left text-sm font-semibold text-gray-700"
                    >
                      Received
                    </th>
                  </tr>

                  <tr class="bg-gray-50 text-sm text-gray-600">
                    <th class="px-4 py-2 text-left w-[65%]">
                      Particulars
                    </th>
                    <th class="px-4 py-2 text-right w-[35%]">
                      Amount
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {data?.toDayCollection?.map(
                    (item, index) => (
                      <tr class="border-t  border-gray-200">
                        <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 w-[80%]">
                          Sales Collection from{" "}
                          {item?.customer?.name}{" "}
                          {item?.customer?.code}
                          {item?.invoice && (
                            <span>
                              {" -"}(
                              {
                                item?.invoice
                                  ?.invoice_no
                              }
                              )
                            </span>
                          )}
                        </td>
                        <td class="px-4 py-2 text-sm text-gray-800 text-right">
                          {Number(item?.payment || 0).toFixed(2)}
                        </td>
                      </tr>
                    )
                  )}
                  {data?.toDayIncome?.map((income, index) => (
                    <tr class="border-t  border-gray-200">
                      <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 w-[80%]">
                        Income{" "}
                        {income?.catagory?.category}{" "}
                      </td>
                      <td class="px-4 py-2 text-sm text-gray-800 text-right">
                        {Number(income?.amount || 0).toFixed(2)}
                      </td>
                    </tr>
                  ))}
                  {data?.toDayLoanEntry?.map((item, index) => (
                    <tr class="border-t  border-gray-200">
                      <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 w-[80%]">
                        Loan Entry{" "}
                        {item?.provider?.name
                          ? `(${item.provider.name})`
                          : ""}
                      </td>
                      <td class="px-4 py-2 text-sm text-gray-800 text-right">
                        {Number(item?.amount || 0).toFixed(2)}
                      </td>
                    </tr>
                  ))}

                  <tr class="bg-gray-100 font-semibold border-t border-gray-300">
                    <td class="px-4 py-2 text-gray-900">
                      Total Received
                    </td>
                    <td class="px-4 py-2 text-gray-900 text-right">
                      {Number(totalReceived || 0).toFixed(2)}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div class="w-full md:w-1/2">
              <table class="w-full border border-gray-300 shadow rounded-md table-auto">
                <thead>
                  <tr class="bg-red-100">
                    <th
                      colspan="2"
                      class="px-4 py-2 text-left text-sm font-semibold text-gray-700"
                    >
                      Payment
                    </th>
                  </tr>
                  <tr class="bg-gray-50 text-sm text-gray-600">
                    <th class="px-4 py-2 text-left w-[65%]">
                      Particulars
                    </th>
                    <th class="px-4 py-2 text-right w-[35%]">
                      Amount
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {data?.toDaySupplierPayment?.map(
                    (item, index) => (
                      <tr class="border-t  border-gray-200">
                        <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 w-[80%]">
                          Payment to{" "}
                          {item?.supplier?.name}{" "}
                          {item?.supplier?.code}
                        </td>
                        <td class="px-4 py-2 text-sm text-gray-800 text-right">
                          {Number(item?.payment || 0).toFixed(2)}
                        </td>
                      </tr>
                    )
                  )}
                  {data?.toDayExpance?.map((item, index) => (
                    <tr class="border-t  border-gray-200">
                      <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 w-[80%]">
                        {" "}
                        {item?.catagory?.category}{" "}
                      </td>
                      <td class="px-4 py-2 text-sm text-gray-800 text-right">
                        {Number(item?.amount || 0).toFixed(2)}
                      </td>
                    </tr>
                  ))}

                  {data?.toDayEmployeeSalary?.map((item, index) => (
                    <tr class="border-t  border-gray-200">
                      <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 w-[80%]">
                        Employee Salary {item?.employee?.user?.name
                          ? `(${item.employee.user.name})`
                          : ""}
                      </td>
                      <td class="px-4 py-2 text-sm text-gray-800 text-right">
                        {Number(item?.amount || 0).toFixed(2)}
                      </td>
                    </tr>
                  ))}

                  {data.toDaySalesReturn?.map(
                    (item, index) => (
                      <tr class="border-t  border-gray-200">
                        <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 w-[80%]">
                          Sales Return{" "}
                          {item?.customer?.name}{" "}
                          {item?.customer?.code}
                          {item?.reference_no && (
                            <span>
                              {" -"}(
                              {item?.reference_no}
                              )
                            </span>
                          )}
                        </td>
                        <td class="px-4 py-2 text-sm text-gray-800 text-right">
                          {Number(item?.total || 0).toFixed(2)}
                        </td>
                      </tr>
                    )
                  )}

                  {data?.toDayLoanPayment?.map((item, index) => (
                    <tr class="border-t  border-gray-200">
                      <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 w-[80%]">
                        Loan Payment{" "}
                        {item?.loan?.provider?.name
                          ? `(${item.loan.provider.name})`
                          : ""}
                      </td>
                      <td class="px-4 py-2 text-sm text-gray-800 text-right">
                        {Number(item?.amount || 0).toFixed(2)}
                      </td>
                    </tr>
                  ))}

                  <tr class="bg-gray-100 font-semibold border-t border-gray-300">
                    <td class="px-4 py-2 text-gray-900">
                      Total Payment
                    </td>
                    <td class="px-4 py-2 text-gray-900 text-right">
                      {Number(totalPayment || 0).toFixed(2)}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <div class="mt-6 px-4 py-3 bg-blue-50 text-blue-800 text-sm font-semibold border border-blue-200 rounded-md shadow-sm">
            Closing Cash In Hand:{" "}
            <span class="float-right">
              {Number(closingCashInHand || 0) < 0
                ? "(" + Math.abs(Number(closingCashInHand || 0)).toFixed(2) + ")"
                : Number(closingCashInHand || 0).toFixed(2)}
            </span>
          </div>

          {/* Sales Due Table */}
          {data?.toDaySalesDue && data?.toDaySalesDue?.length > 0 && (
            <div class="mt-8">
              <h3 class="text-lg font-semibold text-gray-800 mb-4">Sales Due</h3>
              <table class="w-full border border-gray-300 shadow rounded-md table-auto">
                <thead>
                  <tr class="bg-yellow-100">
                    <th class="px-4 py-2 text-left text-sm font-semibold text-gray-700 border border-gray-300">
                      Customer
                    </th>
                    <th class="px-4 py-2 text-left text-sm font-semibold text-gray-700 border border-gray-300">
                      Invoice No
                    </th>
                    <th class="px-4 py-2 text-right text-sm font-semibold text-gray-700 border border-gray-300">
                      Grand Total
                    </th>
                    <th class="px-4 py-2 text-right text-sm font-semibold text-gray-700 border border-gray-300">
                      Total Paid
                    </th>
                    <th class="px-4 py-2 text-right text-sm font-semibold text-gray-700 border border-gray-300">
                      Due
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {data?.toDaySalesDue?.map((customerData, customerIndex) => (
                    <>
                      {customerData?.invoices?.map((invoice, invoiceIndex) => (
                        <tr key={`${customerIndex}-${invoiceIndex}`} class="border-t border-gray-200">
                          <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800">
                            {invoiceIndex === 0 && (
                              <>
                                {customerData?.customer?.name || 'N/A'}{" "}
                                {customerData?.customer?.code && `(${customerData?.customer?.code})`}
                              </>
                            )}
                          </td>
                          <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800">
                            {invoice?.invoice_no || 'N/A'}
                          </td>
                          <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 text-right">
                            {Number(invoice?.grand_total || 0).toFixed(2)}
                          </td>
                          <td class="px-4 py-2 border-r border-gray-300 text-sm text-gray-800 text-right">
                            {Number(invoice?.total_paid || 0).toFixed(2)}
                          </td>
                          <td class="px-4 py-2 text-sm text-gray-800 text-right">
                            {Number(invoice?.due || 0).toFixed(2)}
                          </td>
                        </tr>
                      ))}
                      <tr class="bg-gray-100 font-semibold border-t-2 border-gray-400">
                        <td class="px-4 py-2 border-r border-gray-300 text-gray-900" colSpan="2">
                          Total ({customerData?.customer?.name || 'N/A'})
                        </td>
                        <td class="px-4 py-2 border-r border-gray-300 text-gray-900 text-right">
                          {Number(customerData?.total_grand_total || 0).toFixed(2)}
                        </td>
                        <td class="px-4 py-2 border-r border-gray-300 text-gray-900 text-right">
                          {Number(customerData?.total_paid || 0).toFixed(2)}
                        </td>
                        <td class="px-4 py-2 text-gray-900 text-right">
                          {Number(customerData?.total_due || 0).toFixed(2)}
                        </td>
                      </tr>
                    </>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </AuthenticatedLayout>
  );
}

export default DailyKhataReport;
