import React, { useEffect, useState, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { Tooltip, Form } from 'antd';
import moment from 'moment';
import { DatePicProd } from '../../Components/Forms/DatePickerProduct.jsx';
import { Tables } from '../../Components/Tables/Table.jsx';
import { BiSolidPrinter } from 'react-icons/bi';
import './WholeSalePaymentPurchaseReport.scss';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import {
  getPaymentPurchaseReport,
  UserDataBasedOnBranchId,
} from '../../Features/BookingScreen/BookingData/BookingData.js';
import { getSession } from '../../Services/Others.js';
import { printDiv } from '../../Services/WSOthers.js';
import PurchasePaymentReport from '../PurchaseScreen/WholeSalePrint/PurchasePaymentReportPdf.jsx';
import { DropDowns } from '../../Components/Forms/DropDown.jsx';
import { isMobile } from 'react-device-detect';

const subDirectory = import.meta.env.BASE_URL;

const WholeSalePaymentPurchaseReport = () => {
  const formRef = useRef();
  const dispatch = useDispatch();
  const [datewiseData, setDatewiseData] = useState();
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const UserRole = getSession('UserType');
  const AppId = getSession('AppId');
  const [OrderFromDate, setOrderFromDate] = useState();
  const [OrderToDate, setOrderToDate] = useState();
  const [UserId, setUserId] = useState(
    UserRole != 'Employee' ? 0 : getSession('UserId')
  );
  const [userDropDown, setuserDropDown] = useState([]);
  const [selectedUserData, setSelectedUserData] = useState(null);
  const [page, setpage] = useState(1);
  const [receiptText, setreceiptText] = useState(null);
  const [WholeDataSource, setWholeDataSource] = useState([]);
  const [insideWholeDataSource, setinsideWholeDataSource] = useState([]);

  const [openDenomination, setOpenDenomination] = useState(false);

  console.log(WholeDataSource, 'WholeDataSource', insideWholeDataSource);

  useEffect(() => {
    if (WholeDataSource?.length > 0) {
      mobileDateWisePrintFun(WholeDataSource);
    }
  }, [WholeDataSource]);

  const reprintDate = (date) => {
    const salesDate = new Date(date);
    const formattedDate = salesDate.toLocaleDateString('en-GB', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    });
    return formattedDate;
  };

  const mobileDateWisePrintFun = async (data) => {
    let Dataa = WholeDataSource;

    let Tabledata = Dataa?.map((data, index) => {
      const snoSpacing = Math.max(0, 3 - String(index + 1).length);
      // Calculate dynamic spacing for Rate
      const rateSpacing = Math.max(0, 9 - String(data?.NetAmount).length);
      const QtySpacing = Math.max(
        0,
        3 - String(data?.CountOfPaymentType).length
      );

      // Generate formatted string with dynamic spacings
      const formattedString =
        ' '.repeat(snoSpacing) +
        parseInt(index + 1) +
        '  ' +
        (data?.PaymentMethod + ' '.repeat(22)).substring(0, 22) +
        '  ' +
        ' '.repeat(QtySpacing) +
        String(data?.CountOfPaymentType) +
        ' ' +
        ' '.repeat(rateSpacing) +
        String(data?.NetAmount) +
        ' ' +
        '\n';

      return formattedString;
    });
    const AmountSpace = Math.max(
      0,
      6 - String(parseFloat(TotalBill).toFixed(2)).length
    );
    const Billamountspace = Math.max(
      0,
      6 -
        String(datewiseData?.[0]?.WholeSaleExpenseNetAmount?.toFixed(2)).length
    );
    const Taxamountspace = Math.max(
      0,
      6 -
        String(datewiseData?.[0]?.WholeSaleExpenseTaxAmount?.toFixed(2)).length
    );
    const Netamountspace = Math.max(
      0,
      6 -
        String(datewiseData?.[0]?.WholeSaleExpenseNetAmount?.toFixed(2)).length
    );

    var receiptTextdata =
      "[C]<b><font size='big'>" +
      'Datewise Sales' +
      '</font></b>\n' +
      '[L]<b>From Date :' +
      reprintDate(OrderFromDate) +
      '[R]<b>' +
      ' ' +
      'To Date :' +
      reprintDate(OrderToDate) +
      '</b>\n' +
      '[C]------------------------------------------------\n' +
      '[L]<b>' +
      '' +
      'S.No' +
      '   ' +
      '  Payment Type       ' +
      '  ' +
      'Count ' +
      '  ' +
      'Amount ' +
      '' +
      '</b>' +
      '[L]\n' +
      '[C]------------------------------------------------\n' +
      Tabledata.join('') +
      '[C]<b>------------------------------------------------</b>\n' +
      '[L]<b>' +
      'Total Orders:' +
      datewiseData?.[0]?.Orders +
      '</b>' +
      '[R]<b>' +
      'TotalAmount:' +
      parseFloat(TotalBill).toFixed(2) +
      ' '.repeat(AmountSpace) +
      '</b>\n' +
      '[R]<b>' +
      'Total Bill:' +
      parseFloat(datewiseData?.[0]?.WholeSaleExpenseNetAmount).toFixed(2) +
      ' '.repeat(Billamountspace) +
      '</b>\n' +
      '[R]<b>' +
      'Total Tax:' +
      parseFloat(datewiseData?.[0]?.WholeSaleExpenseTaxAmount).toFixed(2) +
      ' '.repeat(Taxamountspace) +
      '</b>\n' +
      '[L]<b>------------------------------------------------</b>\n' +
      '[R]<b>' +
      'Net:' +
      parseFloat(datewiseData?.[0]?.WholeSaleExpenseNetAmount).toFixed(2) +
      ' '.repeat(Netamountspace) +
      '</b>\n';

    setreceiptText(receiptTextdata);
  };
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
  ];
  const style = `<style>

  @import url('https://fonts.googleapis.com/css2?family=Calistoga&display=swap');  
                     
    @media print {
              body { 
                  font-family:"Calistoga", serif; 
                  font-size: 10px;  
                  margin: 0;
                  padding: 0;
              }
          }    
  * {
              margin: 0;
              padding: 0;
              box-sizing: border-box;
              font-family:"Calistoga", serif; 
                         }
.purchase-report {
  font-family:"Calistoga", serif;
  max-width: max-content;
  margin: 0 auto;
  border: 1px solid #000;
 padding:  1px 1px;
  text-align: center;
  background-color: #ffffff;
}

.wc-header {
        display: flex;
        align-items: flex-start;
        gap: 4px;
        padding: 4px 4px;
    }
    
    .imagelogo {
        width: 65px;
        height: 60px;
    }
    
    .mandiName {
        font-size: 13px;
        font-weight: 700;
        width: 100%;
    }
    
    .wcadd1 {
        font-size: 10px;
        font-weight: 600;
    }
    
    .wcadd2 {
        font-size: 10px;
        font-weight: 600;
    }
    
    .wcphone {
        font-size: 8px;
        font-weight: 600;
    }
    
    .infoOfMandi {
        width: 100%;
        // text-align: center;
    }
    
    .wc-datetime {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 8px;
        width: 95%;
    }
    
    .wc-date {
        font-size: 11px;
        font-weight: 600;
        padding: 1px 0;
    }
    
    .wc-supName {
        font-size: 11px;
        font-weight: 600;
    }

.header {
  text-align: center;
  margin-bottom: 1px;
  padding-bottom: 10px;
  display: flex;
  gap: 10px;
}

.logo {
  width: 65px;
  height: 90px;
  margin-bottom: 1px;
}

.date-time {
  display: flex;
  font-size: 10px;
  align-items: center;
  justify-content: space-between;
  width: 95%;
  padding: 0px 1px;
  padding-bottom: 2px;
  border-bottom: 1px solid #000;
}


.table-container {
   width: 100%;
}

.table {
  width: 95%;
  border-collapse: collapse;
//  margin-left:2px;
  }

 .table th, .table td {
    border: 1px solid #000;
    padding: 1px 1px;
    text-align: center;
  }
  

.total {
  text-align: right;
}

.footer {
  margin-top: 20px;
  text-align: center;
  // border-top: 1px solid #000;
  padding-top: 10px;
}

.summary {
  text-align: right;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}
.boldText {
 
}
.noneBorder {
  border: none !important;
}

.infoOfMandi {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 2px;
}
.printmandiName {
  border-bottom: 1px solid #000;
  text-align: left;
  font-size: 20px;
  word-wrap: break-word;
  padding: 6px 0;
  font-weight: 500;
}
.databody {
  > tr:nth-child(1) {
    width: 10%;
  }
  > tr:nth-child(2) {
    width: 30%;
  }
  > tr:nth-child(3) {
    width: 30%;
  }
  > tr:nth-child(4) {
    width: 30%;
  }
  > tr > td {
    font-size: 10px !important;
   }
}
.prtTitle {
  font-size: 16px;
  width: 100%;
  text-align: center;
  padding:4px 4px;
}

.tableHead {
  font-size: 10px !important;
}
table th, .table td {
  text-align: center;
  border-width: 1px;
  border-style: solid;
  border-color: rgb(0, 0, 0);
  border-image: initial;
  padding: 4px 1px !important;
}
   .Add-Shortname{
        display: flex;
        width: 95%;
        justify-content: space-between;
        
    }
        .Address{
        display:flex;
        flex-direction:column;
        width:77%
        }
    .ShortNameDiv{
        display:flex;
        width:23%;
        font-size: 16px;
        font-weight: 700;
        background: #252525 !important;
        color:white;
        text-align:center;
        justify-content:center;
        align-items:center;
        margin:2px ;
        padding: 0px 5px;
        border: 1px solid black;
        border-radius:5px;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
        }
      </style>`;

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    fetchInitialData();
    if (UserRole != 'Employee') {
      userDropData();
    }
  }, []);

  const userDropData = async () => {
    const gettinguserDropDown = await dispatch(
      UserDataBasedOnBranchId(BranchId)
    ).unwrap();
    if (gettinguserDropDown?.data?.statusCode === 1) {
      let finaluserDropDown = gettinguserDropDown?.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );
      finaluserDropDown.push({ UserId: 0, UserName: 'All User' });

      setSelectedUserData(0);
      formRef.current?.setFieldsValue({
        UserId: 0,
      });

      setuserDropDown(finaluserDropDown);
    }
  };

  const fetchInitialData = async () => {
    let currentDate = new Date().toJSON().slice(0, 10);
    formRef?.current?.setFieldsValue({
      Fromdate: currentDate,
      Todate: currentDate,
    });
    setOrderFromDate(currentDate + 'T00:00:00');
    setOrderToDate(currentDate + 'T00:00:00');
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      OrderFromDate: currentDate,
      OrderToDate: currentDate,
      UserId: UserRole != 'Employee' ? 0 : UserId,
    };

    let response = await dispatch(getPaymentPurchaseReport(data)).unwrap();
    if (response?.data?.statusCode === 1) {
      setDatewiseData(response?.data?.data?.[0]);

      setWholeDataSource(response?.data?.data?.[0]?.OrderDetails);
    } else {
      setDatewiseData([]);
    }
  };

  const columns = [
    {
      title: 'SI NO',
      dataIndex: 'SINO',
      key: 'SINO',
      align: 'center',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },

    {
      title: 'Type',
      dataIndex: 'PaymentMethod',
      key: 'PaymentMethod',
      align: 'left',
    },
    {
      title: 'Qty',
      dataIndex: 'CountOfPaymentType',
      key: 'CountOfPaymentType',
      align: 'right',
    },
    {
      title: 'Amount',
      dataIndex: 'NetAmount',
      key: 'NetAmount',
      align: 'right',
    },
  ];

  const OrderFromDatefetch = async (date, dateString) => {
    if (dateString === '') {
      setOrderFromDate();
    }
    if (dateString) {
      const Date3 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      formRef.current?.setFieldsValue({ Fromdate: Date3 });
      await setOrderFromDate(Date3);
    }
  };

  const UserDropDownChange = async (e) => {
    setUserId(e);
    let mob = userDropDown?.filter((item) => item?.UserId === e);
    formRef.current?.setFieldsValue({
      UserId: e,
      MobileNo: mob?.[0]?.MobileNo,
    });
    setSelectedUserData(e);
  };

  const OrderToDatefetch = async (date, dateString) => {
    if (dateString === '') {
      setOrderToDate();
    }
    if (dateString) {
      const Date4 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      formRef.current?.setFieldsValue({ Todate: Date4 });
      await setOrderToDate(Date4);
    }
  };
  const Print = async () => {
    let LogoImage = '';
    let OrderId = '';
    let UpiId = '';
    let TokenData = '';
    let FooterPrint = '';
    if (isMobile) {
      var textEncoded = encodeURI(receiptText);
      var TypeCheck = 'PrintReceipt';
      var scheme = 'pozoprinter';
      var packageName = 'com.example.pozoprinter';

      window.location.href =
        scheme +
        '://' +
        textEncoded +
        '#Intent;scheme=' +
        scheme +
        ';package=' +
        packageName +
        'ImgS' +
        LogoImage +
        'ImgE' +
        TypeCheck +
        'TokenS' +
        TokenData +
        'TokenE' +
        'EstimateS' +
        '' +
        'EstimateE' +
        'HasFooterTextS' +
        FooterPrint +
        'HasFooterTextE' +
        ';end;';
    } else {
      await printDiv('RePrint', style);
    }
  };

  const onFinish = async (values) => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      OrderFromDate: OrderFromDate?.split('T')?.[0],
      OrderToDate: OrderToDate?.split('T')?.[0],
      UserId: UserId,
    };

    let response = await dispatch(getPaymentPurchaseReport(data)).unwrap();
    if (response?.data?.statusCode === 1) {
      setDatewiseData(response?.data?.data?.[0]);
      setWholeDataSource(response?.data?.data?.[0]?.OrderDetails);
    } else {
      setDatewiseData([]);
      setWholeDataSource([]);
    }
  };
  const TotalBill = datewiseData?.[0]?.WholeSaleExpenseNetAmount;

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

  let count = WholeDataSource?.reduce((accumulator, currentValue) => {
    return accumulator + currentValue?.CountOfPaymentType;
  }, 0);

  let amount = WholeDataSource?.reduce((accumulator, currentValue) => {
    return accumulator + currentValue?.BillAmount;
  }, 0);
  return (
    <div className="PurchaseReport-payment-container">
      <div style={{ display: 'none' }}>
        <PurchasePaymentReport
          OrderFromDate={OrderFromDate?.split('T')?.[0]}
          OrderToDate={OrderToDate?.split('T')?.[0]}
          dataSource={WholeDataSource}
          TotalBill={amount}
          TotalOrders={count}
          TotalBillAmount={amount}
          TotalNetAmount={amount}
          getAddress={datewiseData}
        />
      </div>
      <Form ref={formRef} onFinish={onFinish}>
        <div
          className="PurchaseReport-payment-dateandheading"
          style={{ display: 'flex' }}
        >
          <p className="PurchaseReport-payment-heading"> Purchase Payment</p>

          <div className="PurchaseReport-payment-dateaAnd-buttons">
            <div
              className="PurchaseReport-payment-Date-picker"
              style={{ display: 'flex', flexDirection: 'row', rowGap: '1rem' }}
            >
              <div className="PurchaseReport-payment-datepic">
                <div className="PurchaseReport-payment-DateFrom">
                  <div className="PurchaseReport-payment-Date">
                    <p className="PurchaseReport-payment-Date-from-heading">
                      From Date
                    </p>
                  </div>
                  <Form.Item
                    name="Fromdate"
                    rules={[
                      {
                        required: true,
                        pattern: /^(?!\s*$).+/,
                        message: 'Please Enter the From Date ',
                      },
                    ]}
                  >
                    <DatePicProd
                      onChange={OrderFromDatefetch}
                      style={{ width: '24vw', height: '2.6rem' }}
                      valueData={OrderFromDate}
                      canSelectPast={true}
                      cancelFuture={true}
                    />
                  </Form.Item>
                </div>

                <div>
                  <div>
                    <p>To Date</p>
                  </div>
                  <Form.Item
                    name="Todate"
                    rules={[
                      {
                        required: true,
                        pattern: /^(?!\s*$).+/,
                        message: 'Please Enter the To Date ',
                      },
                    ]}
                  >
                    <DatePicProd
                      onChange={OrderToDatefetch}
                      style={{ width: '24vw', height: '2.6rem' }}
                      valueData={OrderToDate}
                      canSelectPast={true}
                      cancelFuture={true}
                      minDate={OrderFromDate}
                    />
                  </Form.Item>
                </div>
                <div className="datewise-userDropDown">
                  {UserRole != 'Employee' && (
                    <Form.Item
                      name="UserId"
                      rules={[
                        {
                          required: true,
                          message: 'Please Select User Name',
                        },
                      ]}
                    >
                      <DropDowns
                        options={userDropDown?.map((option) => ({
                          value: option?.UserId,
                          label: option?.UserName,
                        }))}
                        label={<label>User Name</label>}
                        id="UserId"
                        field="UserId"
                        fieldState={true}
                        fieldApi={true}
                        className="field-DropDown-Emp"
                        onChangeFunction={(e) => UserDropDownChange(e)}
                        isOnchanges={selectedUserData ? true : false}
                        valueData={selectedUserData}
                      />
                    </Form.Item>
                  )}
                </div>
              </div>
            </div>
            <div className="PurchaseReport-payment-submit-prnt">
              <div>
                <Tooltip title="Submit to search">
                  <button
                    type="submit"
                    className="PurchaseReport-payment-submit-btn"
                  >
                    SUBMIT
                  </button>
                </Tooltip>
              </div>

              <div>
                <Tooltip title="Print">
                  <BiSolidPrinter
                    className={
                      WholeDataSource?.length > 0
                        ? 'PurchaseReport-payment-printerIcon'
                        : 'PurchaseReport-payment-printerIcon-disabled'
                    }
                    onClick={Print}
                  />
                </Tooltip>
              </div>
            </div>
          </div>
        </div>

        <div className="PurchaseReport-payment-coontent-body">
          <div
            className={
              openDenomination
                ? 'PurchaseReport-payment-table-withDenom'
                : 'PurchaseReport-payment-table-withoutDenom'
            }
          >
            <div className="PurchaseReport-payment-table">
              <Tables
                columns={columns}
                data={WholeDataSource}
                pagination={handlePageChange}
              />
            </div>
            <div className="PurchaseReport-payment-Amount-Collected-container">
              <div className="PurchaseReport-payment-Amount-Collected-table">
                <table className="PurchaseReport-payment-Amount-Collected-table-div">
                  <thead>
                    <tr>
                      <th className="reportHeaderEnd">
                        {' '}
                        Qty <span>:</span>{' '}
                      </th>
                      <th className="reportValueEnd">{count}</th>
                    </tr>
                    <tr>
                      <th className="reportHeaderEnd">
                        Total <span>:</span>{' '}
                      </th>
                      <th className="reportValueEnd">{amount}</th>
                    </tr>
                  </thead>
                  <tbody></tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </Form>
    </div>
  );
};

export default WholeSalePaymentPurchaseReport;
