import { RadioGrpButton } from '../../../Components/Forms/RadioGroup';
import { DatePicker, Space, Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import moment from 'moment';
import { DropDowns } from '../../../Components/Forms/DropDown.jsx';
import { Tables } from '../../../Components/Tables/Table';
import { BiSolidPrinter } from 'react-icons/bi';
import {
  getAllCustomerWithoutActive,
  PreferenceData,
} from '../../../Features/BookingScreen/BookingData/BookingData';
import {
  getSession,
  extractLastNumber,
  printDiv,
  ExtractDateFormate,
} from '../../../Services/Others';
import { changeBreadCrumb } from '../../../Features/AppPage/CenterPage';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import Buttons from '../../../Components/Forms/Buttons';
import { Form } from 'antd';
import { ArrowRightOutlined } from '@ant-design/icons';
import LedgerReportPdf from '../../paymentpdfPage/LedgerReportPdf.jsx';
import {
  LedgergetReport,
  getFirstOrderLedgerDate,
} from '../../../Features/Reports/Reports';
import '../../../Styles/Reports/LedgerReport/LedgerReport.scss';
import { isMobile } from 'react-device-detect';
import { ReportMobilePDFPrint } from '../../paymentpdfPage/ReportMobilePDFPrint.js';
import { useSelector } from 'react-redux';
import excelExport from '../../../Images/xls-export.png';
import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
import { downloadFile } from '../../../utils/downloadFile.js';

dayjs.extend(customParseFormat);

const { RangePicker } = DatePicker;
const dateFormat = 'DD-MM-YYYY';

const LedgerReport = () => {
  const dispatch = useDispatch();
  const [AllCustomer1, setAllCustomer1] = useState([]);
  const [SelectedCusId, setSelectedCusId] = useState(null);
  const [LedgerData, setLedgerData] = useState([]);
  const [SelectType, setSelectType] = useState('ALL');
  const [Type, setType] = useState('Y');
  const [Fromdate, setFromdate] = useState(null);
  const [Todate, setTodate] = useState(null);
  const [selectedMonth, setSelectedMonth] = useState(null);
  const [Year, setYear] = useState(null);
  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});
  const [page, setpage] = useState(1);
  const [FirstOrderLedgerDate, setFirstOrderLedgerDate] = useState('');
  const formRef = useRef(null);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const SettingDataSelector = useSelector(PreferenceData);
  const subDirectory = import.meta.env.BASE_URL;
  const MobileA4Print = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'mobilea4' &&
      setting?.SettingValue === 'Y'
  );
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },

    // {
    //   name: "Ledger",
    //   link: `${subDirectory}report/ledgerreport`,
    // },
  ];

  const style = `<style>
  
  .imgDiv{
    height:50px;
    display: flex;
    justify-content: center;
  }
  .Dates{
    margin-left:10px;
    width:230px;
    display: flex;
    justify-content: space-between;
    alignItems:center;
  }
  .DatesStyle{
    display: flex;
    gap:0.2rem;
  }
  .p
  {
    font-size: 10px;
  }
  .totalAmount{
    padding-left:90px;
    font: 15px Arial, sans-serif;
  }
  .Table ,.th ,.td {
    border: 1px solid black;
    border-collapse: collapse;
    font: 10px Arial, sans-serif;
  }
  .td{
    padding:4px
  }
 
  .th{
    padding:4px
  }
  .ItemWiseSales{
   
    display: flex;
    justify-content: center;
    font-size: 15px

  }
  .Table{
    margin-left:10px;
    width:90%;
    height :100x;
  }
    </style>`;
  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    fetchdata2();
  }, []);
  useEffect(() => {
    setLedgerData();
    setSelectedCusId(null);
    setFromdate(null);
    setTodate(null);
    setSelectedMonth(null);
    setYear(null);
    setSelectedCusId(null);
    fetchdata();
    formRef.current?.resetFields();
    // Assuming formRef is a ref assigned to your Form component
  }, [Type, SelectType]);

  const fetchdata = async () => {
    let res = await dispatch(
      getAllCustomerWithoutActive({
        CompId: CompId,
        AppId: AppId,
        branchId: BranchId,
      })
    ).unwrap();
    setAllCustomer1(res?.data?.data);
  };
  const fetchdata2 = async () => {
    let response = await dispatch(
      getFirstOrderLedgerDate({
        CompId: CompId,
        AppId: AppId,
        BranchId: BranchId,
      })
    ).unwrap();
    if (response?.data?.statusCode == 1) {
      setFirstOrderLedgerDate(response?.data?.data?.[0]?.OrderDate);
    }
  };

  const ledger = (e) => {
    formRef.current?.resetFields();
    setSelectType(e);
  };

  const ledgerDatePicker = (e) => {
    setType(e);
    formRef.current?.resetFields();
  };

  const CusSelect = (e) => {
    formRef.current?.setFieldsValue({ CustomerName: e });
    setSelectedCusId(e);
  };

  const onChange = (date, dateString) => {
    setYear(dateString);
    // setFromdate(null);
    // setTodate(null);
    // selectedMonth(null);
  };

  const handleCalendarChange = (dates, dateStrings) => {
    if (dates && dates[1]) {
      setFromdate(dateStrings[0]);
      setTodate(dateStrings[1]);
    }
  };
  const Datetrimmer = (data) => {
    let dateVal = moment(data, ['YYYY-MM-DDTHH:mm:ss']).format('DD-MM-YYYY');
    return dateVal;
    // const dateObject = new Date(data);

    // // Get day, month, and year components
    // const day = dateObject.toLocaleDateString("en-US", { day: "2-digit" });
    // const month = dateObject.toLocaleDateString("en-US", { month: "2-digit" });
    // const year = dateObject.getFullYear();

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

  const columns = [
    {
      title: 'SI no',
      dataIndex: 'sno',
      key: 'sno',
      align: 'center',
      width: 10,
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{index + 1}</a>
      ),
    },
    {
      title: 'Type',
      dataIndex: 'TypeName',
      key: 'TypeName',
      align: 'left',
      width: 10,
      render: (text, object, index) => (
        <a
          style={
            text == 'OB'
              ? { color: 'red', fontWeight: '500px', fontSize: '15px' }
              : { color: 'Black' }
          }
        >
          {text == 'OB' ? 'OB' : text}
        </a>
      ),
    },
    {
      title: ' Cus-Id',
      dataIndex: 'CustId',
      key: 'CustId',
      align: 'left',
      width: 100,
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>
          {text == null ? 'GEN' : extractLastNumber(text)}
        </a>
      ),
    },
    {
      title: 'Cus-Name',
      dataIndex: 'CustName',
      key: 'CustName',
      align: 'left',
      width: 150,
    },
    {
      title: 'RC.NO',
      dataIndex: 'ReceiptNo',
      key: 'ReceiptNo',
      align: 'left',
      width: 10,
    },
    {
      title: 'Mob.No',
      dataIndex: 'MobileNo',
      key: 'MobileNo',
      align: 'left',
      width: 100,
    },
    {
      title: 'Address',
      dataIndex: 'Address1',
      key: 'Address1',
      align: 'left',

      render: (text, object, index) => (
        <Tooltip title={`${text}`}>
          <p
            style={{
              color: 'black',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              width: '40px',
            }}
          >
            {text}
          </p>
        </Tooltip>
      ),
    },
    {
      title: 'Payment Mode',
      dataIndex: 'PaymentTypeName',
      key: 'PaymentTypeName',
      align: 'left',
      width: 150,
      // ellipsis: true,
    },
    {
      title: 'Date',
      dataIndex: 'Date',
      key: 'Date',
      align: 'center',
      width: 250,
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{ExtractDateFormate(text)}</a>
      ),
    },
    {
      title: 'Debit',
      dataIndex: 'Debit',
      key: 'Debit',
      align: 'right',
      width: 10,
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{text > 0 ? text : ' '}</a>
      ),
    },
    {
      title: 'Credit',
      dataIndex: 'Credit',
      key: 'Credit',
      align: 'right',
      width: 10,
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{text > 0 ? text : ' '}</a>
      ),
    },
    {
      title: 'Balance',
      // dataIndex: "company",
      key: 'company',
      align: 'center',
      width: 100,
      children: [
        {
          title: 'Credit',
          key: 'BalCredit',
          dataIndex: 'BalCredit',
          // width: 30,
          render: (text, object, index) => (
            <a style={{ color: 'red', fontSize: '20px' }}>
              {text > 0 ? text : ' '}
            </a>
          ),
        },
        {
          title: 'Debit',
          dataIndex: 'BalDebit',
          key: 'BalDebit',
          render: (text, object, index) => (
            <a style={{ color: 'green', fontSize: '15px' }}>
              {text > 0 ? text : ' '}
            </a>
          ),
        },
      ],
    },
  ];

  const handleOk = (date) => {
    // Handle the "OK" button click event
    setSelectedMonth(date.format('YYYY-MM'));
    setYear(null);
    setFromdate(null);
    setTodate(null);
  };
  const getReport = async (value) => {
    let data1 = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      Year: Year,
      Month: selectedMonth,
      Fromdate: Fromdate,
      Todate: Todate,
      CustId: SelectedCusId,
    };

    let response = await dispatch(LedgergetReport(data1)).unwrap();
    if (response?.data?.statusCode == 1) {
      setLedgerData(response?.data?.data);
    } else {
      setLedgerData();
    }
  };
  const handleChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };

  const handlePageChange = (current) => {
    setpage(current);
  };

  const Print = async () => {
    if (isMobile) {
      if (MobileA4Print) {
        ReportMobilePDFPrint({
          printId: 'RePrint',
          printStyle: style,
        });
      }
    } else {
      await printDiv('RePrint', style);
    }
  };

  const exportToExcel = async () => {
    if (!LedgerData || LedgerData.length === 0) return;

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Ledger Report');

    worksheet.views = [
      {
        state: 'frozen',
        ySplit: 2,
      },
    ];

    // HEADER ROW 1
    worksheet.addRow([
      'SI No',
      'Type',
      'Cus-Id',
      'Cus-Name',
      'RC.NO',
      'Mob.No',
      'Address',
      'Payment Mode',
      'Date',
      'Debit',
      'Credit',
      'Balance in',
      '',
    ]);

    // HEADER ROW 2
    worksheet.addRow([
      '',
      '',
      '',
      '',
      '',
      '',
      '',
      '',
      '',
      '',
      '',
      'Credit',
      'Debit',
    ]);

    // MERGE CELLS
    worksheet.mergeCells('A1:A2');
    worksheet.mergeCells('B1:B2');
    worksheet.mergeCells('C1:C2');
    worksheet.mergeCells('D1:D2');
    worksheet.mergeCells('E1:E2');
    worksheet.mergeCells('F1:F2');
    worksheet.mergeCells('G1:G2');
    worksheet.mergeCells('H1:H2');
    worksheet.mergeCells('I1:I2');
    worksheet.mergeCells('J1:J2');
    worksheet.mergeCells('K1:K2');
    worksheet.mergeCells('L1:M1');

    // worksheet.eachRow((row) => {
    //   row.eachCell((cell) => {
    //     cell.protection = {
    //       locked: true
    //     };
    //   });
    // });

    // Lock header rows
    [1, 2].forEach((rowNumber) => {
      const row = worksheet.getRow(rowNumber);
      row.eachCell((cell) => {
        cell.protection = { locked: true };
      });
    });

    // HEADER STYLE
    const headerRows = [1, 2];

    headerRows.forEach((rowNumber) => {
      const row = worksheet.getRow(rowNumber);

      row.eachCell((cell) => {
        cell.font = {
          bold: true,
          color: { argb: 'FFFFFFFF' }, // white text
        };

        cell.alignment = {
          vertical: 'middle',
          horizontal: 'center',
        };

        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FF2E7D32' }, // green header
        };

        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' },
        };
      });
    });

    // specifically ensure Balance in header center
    worksheet.getCell('L1').alignment = {
      horizontal: 'center',
      vertical: 'middle',
    };

    // COLUMN WIDTH
    worksheet.columns = [
      { width: 8 },
      { width: 10 },
      { width: 12 },
      { width: 20 },
      { width: 12 },
      { width: 15 },
      { width: 25 },
      { width: 15 },
      { width: 15 },
      { width: 12 },
      { width: 12 },
      { width: 12 },
      { width: 12 },
    ];

    // DATA ROWS
    LedgerData.forEach((row, index) => {
      const r = worksheet.addRow([
        index + 1,
        row.TypeName === 'OB' ? 'OB' : row.TypeName,
        row.CustId ? extractLastNumber(row.CustId) : 'GEN',
        row.CustName || '',
        row.ReceiptNo || '',
        row.MobileNo || '',
        row.Address1 || '',
        row.PaymentTypeName || '',
        ExtractDateFormate(row.Date) || '',
        row.Debit > 0 ? row.Debit : '',
        row.Credit > 0 ? row.Credit : '',
        row.BalCredit > 0 ? row.BalCredit : '',
        row.BalDebit > 0 ? row.BalDebit : '',
      ]);

      // 🔓 Unlock every cell in this row
      r.eachCell({ includeEmpty: true }, (cell) => {
        cell.protection = { locked: false };
      });

      // Credit red
      if (row.BalCredit > 0) {
        r.getCell(12).font = { color: { argb: 'FFFF0000' } };
      }

      // Debit green
      if (row.BalDebit > 0) {
        r.getCell(13).font = { color: { argb: 'FF008000' } };
      }
    });

    // Unlock all data rows
    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber > 2) {
        row.eachCell((cell) => {
          cell.protection = { locked: false };
        });
      }
    });

    await worksheet.protect('ledger123', {
      selectLockedCells: true,
      selectUnlockedCells: true,
      formatColumns: true, // allow column resize
      formatRows: false,
      insertColumns: false,
      insertRows: false,
      deleteColumns: false,
      deleteRows: false,
    });

    const buffer = await workbook.xlsx.writeBuffer();

    const blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-of  ficedocument.spreadsheetml.sheet',
    });

    const now = new Date();

    const day = String(now.getDate()).padStart(2, '0');
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const year = now.getFullYear();

    let hours = now.getHours();
    const minutes = String(now.getMinutes()).padStart(2, '0');

    const ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12;

    hours = String(hours).padStart(2, '0');

    const fileName = `Ledger Report_${day}-${month}-${year}_${hours}-${minutes}-${ampm}.xlsx`;
    downloadFile(
        buffer,
        fileName,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        (success) => {
          if (success) {
            console.log("File downloaded and opened successfully!");
          } else {
            console.log("Failed to download/open file.");
          }
        }
      );
    // saveAs(blob, fileName);
  };

  const FirstOrderLedgerDateRaw = dayjs(FirstOrderLedgerDate);

  const disabledDate = (current) => {
    return (
      current &&
      (current < FirstOrderLedgerDateRaw.startOf('day') ||
        current > dayjs().endOf('day'))
    );
  };

  return (
    <>
      <div className="MasterLedger-Report">
        <Form className="formDivAnt" ref={formRef} onFinish={getReport}>
          {/* <FormHeader title={"Ledger Report"} /> */}
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              width: '100%',
            }}
          >
            <div
              className="formHeader"
              style={{
                display: 'flex',
                width: '100%',
                justifyContent: 'space-between',
                flexWrap: 'wrap',
                alignItems: 'center',
              }}
            >
              {' '}
              <p className="LedgerReport-heading">Ledger</p>
              <div
                className="AllRadioButtonDate"
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  flexWrap: 'wrap',
                  alignItems: 'center',
                  gap: '0.5rem',
                }}
              >
                <div className="AllRadioButton">
                  <div className="RadioButton">
                    <RadioGrpButton
                      content={[
                        { value: 'ALL', label: 'All' },
                        { value: 'CUS', label: 'Customer' },
                      ]}
                      fieldState={true}
                      defaultSelect={SelectType}
                      onSelectFuntion={(e) => ledger(e)}
                    />
                  </div>{' '}
                  <div className="RadioButton-DMYPicker">
                    <RadioGrpButton
                      content={[
                        { value: 'Y', label: 'Year' },
                        { value: 'M', label: 'Month' },
                        { value: 'D', label: 'Date' },
                      ]}
                      fieldState={true}
                      defaultSelect={Type}
                      onSelectFuntion={(e) => ledgerDatePicker(e)}
                    />
                  </div>
                </div>

                {/* datepicer  */}
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    width: 'auto',
                  }}
                >
                  <div className="Ledger-datePicker">
                    <Space direction="horizontal">
                      {Type == 'Y' && (
                        <Form.Item
                          name="EffectiveFrom"
                          // hasFeedback
                          rules={[
                            {
                              required: true,
                              message: 'Please Enter The Year',
                            },
                          ]}
                        >
                          <DatePicker
                            picker="year"
                            disabledDate={(current) =>
                              current &&
                              (current.year() <
                                FirstOrderLedgerDateRaw.year() ||
                                current.year() > moment().year())
                            }
                            onChange={(date, dateString) =>
                              onChange(date, dateString)
                            }
                          />
                        </Form.Item>
                      )}
                      {Type == 'M' && (
                        <Form.Item
                          name="EffectiveFrom"
                          // hasFeedback
                          rules={[
                            {
                              required: true,
                              message: 'Please Enter The Month',
                            },
                          ]}
                        >
                          <DatePicker
                            picker="month"
                            disabledDate={(current) =>
                              current &&
                              (current <
                                FirstOrderLedgerDateRaw.startOf('month') ||
                                current > moment().endOf('month'))
                            }
                            onChange={(date, dateString) => handleOk(date)}
                          />
                        </Form.Item>
                      )}
                      {Type == 'D' && (
                        <Form.Item
                          name="EffectiveFrom"
                          // hasFeedback
                          rules={[
                            {
                              required: true,
                              message: 'Please Enter The Date',
                            },
                          ]}
                        >
                          <RangePicker
                            //  defaultValue={[dayjs(), dayjs()]}
                            format={dateFormat}
                            showTime
                            disabledDate={disabledDate}
                            //   onOk={handleOk}
                            onCalendarChange={handleCalendarChange}
                            inputReadOnly={true}
                          />
                        </Form.Item>
                      )}
                    </Space>
                  </div>
                  <div
                    className="dropDown-ledger"
                    style={{ paddingLeft: '30px' }}
                  >
                    {SelectType === 'CUS' && (
                      <Form.Item
                        name="CustomerName"
                        // hasFeedback
                        rules={[
                          {
                            required: true,
                            message: 'please choose The Customer ',
                          },
                        ]}
                      >
                        {/* <DropDowns
                                options={AllCustomer1?.map((option) => ({
                                  value: option.CustId,
                                  label: option.CustName,
                                }))}
                                placeholder="Customer Name"
                                // label={<label className="required">CustomerName</label>}
                                label="Config Type"
                                onChangeFunction={(e) => CusSelect(e)}
                                isOnchanges={true}
                                className="field-DropDown"
                                valueData={SelectedCusId}
                                width={20}
                              /> */}
                        <DropDowns
                          options={AllCustomer1?.map((option) => ({
                            value: option.CustId,
                            label: option.CustName || option?.MobileNo,
                          }))}
                          // defaultValue="Select" // Set "Select" as the default value
                          // placeholder="Name"
                          label={
                            <label className="required">CustomerName</label>
                          }
                          // onChangeFunction={(e)=>ConfigSelect(e)}
                          // isOnchanges={}
                          className="field-DropDown"
                          valueData={SelectedCusId}
                          onChangeFunction={(e) => CusSelect(e)}
                          // onFilter={(value, record) =>
                          //   String(record.TypeName)
                          //     .toLowerCase()
                          //     .includes(value.toLowerCase())
                          // }
                        />
                      </Form.Item>
                    )}
                  </div>
                </div>
                {/* datepicer  */}
              </div>
              <div className="Submit" style={{ paddingBottom: '10px' }}>
                <Buttons
                  buttonText="Search"
                  color="901D77"
                  icon={<ArrowRightOutlined />}
                  // handleSubmit={() => { getReport() }}
                />
              </div>
              <div className="ledger-PrintIcon">
                <BiSolidPrinter
                  onClick={LedgerData?.length > 0 ? () => Print() : () => {}}
                  className={
                    LedgerData?.length > 0
                      ? 'ItemWiseReport-printerIcon'
                      : 'ItemWiseReport-printerIcon-disabled'
                  }
                />
                <Tooltip
                  title={
                    LedgerData?.length > 0
                      ? 'Export as Excel'
                      : 'No data to Export'
                  }
                  placement="top"
                >
                  <div
                    style={{
                      width: '35px',
                      height: '35px',
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                      cursor:
                        LedgerData?.length > 0 ? 'pointer' : 'not-allowed',
                      opacity: LedgerData?.length > 0 ? 1 : 0.5,
                    }}
                  >
                    <img
                      width={'95%'}
                      height={'95%'}
                      src={excelExport}
                      alt="Excel Export"
                      onClick={
                        LedgerData?.length > 0
                          ? () => exportToExcel()
                          : () => {}
                      }
                    />
                  </div>
                </Tooltip>
              </div>
            </div>
          </div>

          <div className="LedgerTable">
            {/* <Tables
              data={LedgerData}
              columns={columns}
              pagination={handlePageChange}
              onChange={handleChange}
            /> */}
            <table className="custom-table">
              <thead>
                <tr>
                  <th rowSpan={2}>SI no</th>
                  <th rowSpan={2}>Type</th>
                  <th rowSpan={2}>Cus-Id</th>
                  <th rowSpan={2}>Cus-Name</th>
                  <th rowSpan={2}>RC.NO</th>
                  <th rowSpan={2}>Mob.No</th>
                  <th rowSpan={2} style={{ width: '90px' }}>
                    Address
                  </th>
                  <th rowSpan={2}>Payment Mode</th>
                  <th rowSpan={2}>Date</th>
                  <th rowSpan={2}>Debit</th>
                  <th rowSpan={2}>Credit</th>
                  <th colSpan={2} style={{ textAlign: 'center' }}>
                    Balance in
                  </th>
                </tr>
                <tr>
                  <th style={{ textAlign: 'center' }}>Credit</th>
                  <th style={{ textAlign: 'center' }}>Debit</th>
                </tr>
              </thead>
              <tbody>
                {LedgerData && LedgerData.length > 0 ? (
                  LedgerData.map((row, idx) => (
                    <tr key={idx}>
                      <td style={{ textAlign: 'center' }}>{idx + 1}</td>
                      <td
                        style={
                          row.TypeName === 'OB'
                            ? {
                                color: 'red',
                                fontWeight: 500,
                                fontSize: '15px',
                              }
                            : { color: 'black' }
                        }
                      >
                        {row.TypeName === 'OB' ? 'OB' : row.TypeName}
                      </td>
                      <td style={{ textAlign: 'left' }}>
                        {row.CustId == null
                          ? 'GEN'
                          : typeof extractLastNumber === 'function'
                            ? extractLastNumber(row.CustId)
                            : row.CustId}
                      </td>
                      <td style={{ textAlign: 'left' }}>{row.CustName}</td>
                      <td style={{ textAlign: 'left' }}>{row.ReceiptNo}</td>
                      <td style={{ textAlign: 'left' }}>{row.MobileNo}</td>
                      <td
                        style={{
                          textAlign: 'left',
                          maxWidth: '40px',
                          whiteSpace: 'nowrap',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                        }}
                      >
                        <span title={row.Address1}>{row.Address1}</span>
                      </td>
                      <td style={{ textAlign: 'left' }}>
                        {row.PaymentTypeName}
                      </td>
                      <td style={{ textAlign: 'center' }}>
                        {ExtractDateFormate(row.Date)}
                      </td>
                      <td style={{ textAlign: 'right' }}>
                        {row.Debit > 0 ? row.Debit : ''}
                      </td>
                      <td style={{ textAlign: 'right' }}>
                        {row.Credit > 0 ? row.Credit : ''}
                      </td>
                      <td
                        style={{
                          color: 'red',
                          fontSize: '20px',
                          textAlign: 'center',
                        }}
                      >
                        {row.BalCredit > 0 ? row.BalCredit : ''}
                      </td>
                      <td
                        style={{
                          color: 'green',
                          fontSize: '15px',
                          textAlign: 'center',
                        }}
                      >
                        {row.BalDebit > 0 ? row.BalDebit : ''}
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td
                      colSpan={13}
                      style={{ textAlign: 'center', padding: '10px' }}
                    >
                      Data not found
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </Form>
        <div style={{ display: 'none' }}>
          <LedgerReportPdf LedgerData={LedgerData} />
        </div>
      </div>{' '}
    </>
  );
};

export default LedgerReport;
