import React, { useEffect, useState, useRef, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Tooltip, Form, Switch, DatePicker } from 'antd';
import moment from 'moment';
import { DatePicProd } from '../../../Components/Forms/DatePickerProduct.jsx';
import { Tables } from '../../../Components/Tables/Table';
import { BiSolidPrinter } from 'react-icons/bi';
import { Search } from '../../../Components/Forms/Search';
import '../../../Styles/Reports/ItemWiseReport/ItemWiseReport.scss';
import { changeBreadCrumb } from '../../../Features/AppPage/CenterPage';
import {
  getItemWiseReport,
  UserDataBasedOnBranchId,
  getCatItemWiseReport,
  WholeSalegetItemWiseReport,
} from '../../../Features/Reports/Reports';
import { getSession, printDiv } from '../../../Services/WSOthers';
import ItemwiseReportPdf from '../../paymentpdfPage/ItemwiseReportPdf';
import CategoryWiseReportPdf from '../../paymentpdfPage/CategorywiseReport.jsx';
import { DropDowns } from '../../../Components/Forms/DropDown.jsx';
import DynamicPieChart from '../../DashBoard/PieChart.jsx';
import { isMobile } from 'react-device-detect';
import {
  getPreferenceData,
  PreferenceData,
} from '../../../Features/BookingScreen/BookingData/BookingData.js';
import { ReportMobilePDFPrint } from '../../paymentpdfPage/ReportMobilePDFPrint.js';
import { ApplicationPreferences } from '../../../Features/BrachLogin/BranchLogin.js';

const subDirectory = import.meta.env.BASE_URL;
const ItemWiseReport = () => {
  const today = new Date();
  const formattedToday = today.toISOString()?.split('T')[0];
  const dispatch = useDispatch();
  const formRef = useRef();
  const { RangePicker } = DatePicker;
  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});
  const [sortedInfo2, setSortedInfo2] = useState({});
  const [searchedText, setSearchedText] = useState('');
  const [searchedText2, setSearchedText2] = useState('');
  const [OrderFromDate, setOrderFromDate] = useState(formattedToday);
  const [OrderToDate, setOrderToDate] = useState(formattedToday);
  const [ItemWiseData, setItemWiseData] = useState();
  const [CateWiseData, setCateWiseData] = useState();
  const [userDropDown, setuserDropDown] = useState([]);
  const [chartData, setchartdata] = useState([]);
  const [allowDecimal, setAllowDecimal] = useState(false);
  const [apiCall, setapiCall] = useState(false);
  const [chart, setchart] = useState(false);
  const [selectedUserData, setSelectedUserData] = useState(null);
  const [receiptTextItemWise, setreceiptTextItemWise] = useState();
  const [receiptTextCatWise, setreceiptTextCatWise] = useState();
  const [ShowStock, setShowStock] = useState(false);
  const SettingDataSelector = useSelector(PreferenceData);
  const UomPrint = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
    (i) => i.SettingIdName === 'PrintUom'
  )?.[0];
  const appPreferences = useSelector(ApplicationPreferences);
  const commonModulePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Common Module'
  )?.PreferenceCatDetails;
  const sportsAppPreference = commonModulePreference?.find(
    (preference) =>
      preference?.PreferredSubCatName === 'SportsApp' &&
      preference?.PreferredStatus === 'Y'
  );
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserRole = getSession('UserType');
  const [UserId, setUserId] = useState(
    UserRole != 'Employee' ? 0 : getSession('UserId')
  );
  const AppType =
    getSession('AppType')?.toLowerCase() == 'wholesale' ? true : false;
  const MobileA4Print = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'mobilea4' &&
      setting?.SettingValue === 'Y'
  );

  useEffect(() => {
    getPreference();
  }, []);
  useEffect(() => {
    // if (CateWiseData && CateWiseData.length > 0) {
    const finalData = CateWiseData?.map((e) => {
      const ProdCatName = e.ProdCatName || 'Others';
      const name = e.ProdCatName || 'Others';
      const y = e.TotalAmt || 0;
      return { ...e, name, y, ProdCatName };
    });
    setchartdata(finalData);
    // }
  }, [CateWiseData]);

  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
  ];
  const style = `<style>
   @import url('https://fonts.googleapis.com/css2?family=Podkova:wght@400..800&display=swap');  
             
           @media print {
                     body { 
                         font-family:"Podkova", serif; 
                         font-size: 13px; /* Adjust font size for print */
                         margin: 0;
                         padding: 0;
                     }
                 }    
          * {
                     margin: 0;
                     padding: 0;
                     box-sizing: border-box;
                     font-family:"Podkova", serif; 
                 }

  .imgDiv {
    height: 50px;
    display: flex;
    justify-content: center;
  }
  .Dates {
    margin-left: 10px;
    width: 90%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 2px 0;
  }
  .DatesStyle {
    display: flex;
    gap: 0.2rem;
  }
  .p {
    font-size: 10px;
  }
  .totalAmount {
    font-size: 15px;
    text-align: right;
    padding: 4px 0;
    width: 90%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}
  .totaldetails {
    width: 91%;  
    display: flex;
    justify-content: flex-end;
    font-size: 10px;
  }

.Table,
.th,
.td {
    border: 1px solid black;
    border-collapse: collapse;
     font-size: 10px;
  }
  .td {
    padding: 4px
  }
 
  .th {
    padding: 4px
  }
  
  .ItemWiseSales {
    display: flex;
    justify-content: center;
    font-size: 15px;
    font-weight: 500;
  }
  .Table {
    margin-left: 10px;
    width: 90%;
    height: 100x;
  }
    </style>`;

  const openChart = (value) => {
    setchart(!chart);
  };

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    fetchInitialData();
  }, []);

  useEffect(() => {
    setchart(false);
  }, [apiCall]);
  useEffect(() => {
    if (UserRole != 'Employee') {
      userDropData();
    }
  }, []);
  useEffect(() => {
    if (apiCall) {
      setSelectedUserData(0);
      fetchCatData();
    } else {
      setSelectedUserData(0);
      fetchInitialData();
    }
  }, [apiCall]);
  const getPreference = async () => {
    const data = { AppId: AppId, CompId: CompId, BranchId: BranchId };
    const { data: res } = await dispatch(getPreferenceData(data)).unwrap();
    const decimalSetting = res?.data?.[0]?.SettingDtlDetails?.find(
      (setting) =>
        setting?.SettingIdName?.toLowerCase() === 'decimal' &&
        setting?.SettingValue === 'Y'
    );
    if (decimalSetting) {
      setAllowDecimal(true);
    }
  };
  const fetchCatData = async () => {
    let data1 = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      OrderFromDate: OrderFromDate?.split('T')?.[0],
      OrderToDate: OrderToDate?.split('T')?.[0],
      UserId: 0,
      type: 'P',
    };

    let response = await dispatch(getCatItemWiseReport(data1)).unwrap();
    if (response?.data?.statusCode == 1) {
      setCateWiseData(response?.data?.data);
    } else {
      setCateWiseData([]);
    }
  };
  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,
    };

    if (AppType) {
      let Response = await dispatch(WholeSalegetItemWiseReport(data)).unwrap();
      setItemWiseData(Response?.data?.data);
    } else {
      let Response = await dispatch(getItemWiseReport(data)).unwrap();
      setItemWiseData(Response?.data?.data);
    }
  };

  const handleChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };
  const handleChange2 = (pagination, filters, sorter) => {
    setSortedInfo2(sorter);
  };

  // const onComplete = useCallback(() => {
  //   setMessageData(null);
  //   setMessageType(null);
  // }, [])

  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };
  const onSearch2 = (value) => {
    setSearchedText2(value);
  };
  const onSearchChange2 = (e) => {
    setSearchedText2(e?.target?.value);
  };
  const Print = async () => {
    if (isMobile) {
      if (MobileA4Print) {
        ReportMobilePDFPrint({
          printId: 'RePrint',
          printStyle: style,
        });
      } else {
        let LogoImage = '';
        let TokenData = '';
        let FooterPrint = '';
        var textEncoded = encodeURI(receiptTextItemWise);
        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 Print2 = async () => {
    if (isMobile) {
      if (MobileA4Print) {
        ReportMobilePDFPrint({
          printId: 'RePrint2',
          printStyle: style,
        });
      } else {
        let LogoImage = '';
        let TokenData = '';
        let FooterPrint = '';
        var textEncoded = encodeURI(receiptTextCatWise);
        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('RePrint2', style);
    }
  };
  const UserDropDownChange = async (e) => {
    setUserId(e);
    setSelectedUserData(e);

    const selectedUser = userDropDown?.find((item) => item?.UserId === e);

    if (selectedUser) {
      let mob = userDropDown?.filter((item) => item?.UserId === e);
      formRef.current?.setFieldsValue({
        UserId: e,
        MobileNo: mob?.[0]?.MobileNo,
      });
    }
    // setCateWiseData(null);
  };

  function safeRound(amountStr) {
    if (amountStr == null) return allowDecimal ? '0.00' : '0';

    const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
    const num = Number(cleaned);

    if (isNaN(num)) return allowDecimal ? '0.00' : '0';

    return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
  }

  const DateWisTableData = ItemWiseData?.map((item, index) => ({
    SINO: index + 1,
    ItemName: sportsAppPreference
      ? `${item?.ProdSubCatName || ''} - ${item?.ProdName || ''}`.trim() ||
        'Others'
      : !AppType
        ? UomPrint?.SettingValue === 'N'
          ? `${item?.ProdName} ${(item?.UOMName || '')?.toLowerCase() === 'half' ? '(Half)' : ''}`
          : `${item?.ProdName}(${item?.Size} ${item?.UOMName})`
        : `${item?.ProdName}`,
    Quantity: item?.SalesQty,
    BalanceQty:item?.BalanceQty,
    Amount: item?.TotalAmt,
    StockAvailable:item?.StockAvailable,
  }));
  const itemData = DateWisTableData;

  console.log(itemData, 'itemData');
  const OrderFromDatefetch = async (dateObj) => {
    if (!dateObj) {
      setOrderFromDate();
      return;
    }

    const Date3 = moment(dateObj.toDate()).format('YYYY-MM-DDTHH:mm:ss');
    formRef.current?.setFieldsValue({ Fromdate: Date3 });
    setOrderFromDate(Date3);
  };

  const OrderToDatefetch = async (dateObj) => {
    if (!dateObj) {
      setOrderToDate();
      return;
    }

    const Date4 = moment(dateObj.toDate()).format('YYYY-MM-DDTHH:mm:ss');
    formRef.current?.setFieldsValue({ Todate: Date4 });
    setOrderToDate(Date4);
  };
  const onFinish = async () => {
    try {
      let data = {
        CompId: CompId,
        BranchId: BranchId,
        AppId: AppId,
        OrderFromDate: OrderFromDate?.split('T')?.[0],
        OrderToDate: OrderToDate?.split('T')?.[0],
        UserId: UserId,
      };
      let data1 = {
        CompId: CompId,
        BranchId: BranchId,
        AppId: AppId,
        OrderFromDate: OrderFromDate?.split('T')?.[0],
        OrderToDate: OrderToDate?.split('T')?.[0],
        UserId: UserId,
        type: 'P',
      };
      if (!apiCall) {
        if (AppType) {
          let Response = await dispatch(
            WholeSalegetItemWiseReport(data)
          ).unwrap();
          setItemWiseData(Response?.data?.data);
        } else {
          let Response = await dispatch(getItemWiseReport(data)).unwrap();
          setItemWiseData(Response?.data?.data);
        }
      } else {
        let response = await dispatch(getCatItemWiseReport(data1)).unwrap();
        if (response?.data?.statusCode === 1) {
          setCateWiseData(response?.data?.data);
        } else {
          // setMessageType("warning");
          // setMessageData("No Data Found");
          setCateWiseData([]);
        }
      }
    } catch (error) {
      console.error('An error occurred:', error);
    }
  };

  let filterRate1 = CateWiseData?.map((item) => item.BillAmount);
  const TotalAmount2 = filterRate1?.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
  );

  let filterTaxRate1 = CateWiseData?.map((item) => item.TaxAmt);
  const TotalTaxAmount2 = filterTaxRate1?.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
  );

  let filterRate = ItemWiseData?.map((item) => item.BillAmount);
  const TotalAmount = filterRate?.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
  );

  let filterTaxRate = ItemWiseData?.map((item) => item.TaxAmt);
  const TotalTaxAmount = filterTaxRate?.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
  );

  const onChange = (checked) => {
    setapiCall(checked);
  };

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

  useEffect(() => {
    if (itemData?.length > 0) {
      console.log(itemData, 'itemDataitemData');
      mobileItemWisePrintFun(itemData);
    }
  }, [itemData]);

  useEffect(() => {
    if (CateWiseData?.length > 0) {
      mobileCatWisePrintFun(CateWiseData);
    }
  }, [CateWiseData]);
  const formatAmount = (value) => {
    return allowDecimal
      ? parseFloat(value || 0).toFixed(2)
      : Math.round(value || 0);
  };
  const mobileCatWisePrintFun = async (printdata) => {
    let Tabledata = printdata?.map((data, index) => {
      const snoSpacing = Math.max(0, 3 - String(index + 1).length);
      // Calculate dynamic spacing for Rate
      const QtySpacing = Math.max(0, 5 - String(data?.SalesQty).length);
      const rateSpacing = Math.max(0, 7 - String(data?.TotalAmt).length);

      // Calculate dynamic spacing for TotalAmt

      // Generate formatted string with dynamic spacings
      const formattedString =
        ' '.repeat(snoSpacing) +
        parseInt(index + 1) +
        '  ' +
        (data?.ProdCatName + ' '.repeat(20)).substring(0, 20) +
        ' ' +
        ' '.repeat(QtySpacing) +
        String(data?.SalesQty) +
        '  ' +
        ' '.repeat(rateSpacing) +
        String(data?.TotalAmt) +
        ' ' +
        '\n';

      return formattedString;
    });

    const Billamountspace = Math.max(
      0,
      6 - String(formatAmount(TotalAmount)).length
    );
    const Taxamountspace = Math.max(
      0,
      6 - String(formatAmount(TotalTaxAmount)).length
    );
    const Chargesamountspace = Math.max(
      0,
      6 - String(formatAmount(CateWiseData?.[0]?.ExtrachargeAmount)).length
    );
    const Preorderamountspace = Math.max(
      0,
      6 - String(formatAmount(CateWiseData?.[0]?.PreOrderNetAmount)).length
    );
    const Discountamountspace = Math.max(
      0,
      6 - String(formatAmount(CateWiseData?.[0]?.TotalOfferAmount)).length
    );
    const Netamountspace = Math.max(
      0,
      6 -
        String(
          formatAmount(
            TotalAmount +
              (TotalTaxAmount || 0) +
              (CateWiseData?.[0]?.ExtrachargeAmount || 0) +
              (CateWiseData?.[0]?.PreOrderNetAmount || 0) -
              (CateWiseData?.[0]?.TotalOfferAmount || 0)
          )
        ).length
    );
    var data = CateWiseData && CateWiseData[0] ? CateWiseData[0] : {};
    var receiptTextdata =
      "[C]<b><font size='big'>" +
      'Category Wise Sales' +
      '</font></b>\n' +
      '[L]<b>From Date :' +
      reprintDate(OrderFromDate) +
      '[L]<b>' +
      '   ' +
      'To Date :' +
      reprintDate(OrderToDate) +
      '</b>\n' +
      '[C]------------------------------------------------\n' +
      '[L]<b>' +
      '' +
      'S.No' +
      '   ' +
      '  Category        ' +
      ' ' +
      'Quantity ' +
      '  ' +
      'Amount ' +
      '' +
      '</b>' +
      '[L]\n' +
      '[C]------------------------------------------------\n' +
      Tabledata.join('') +
      '[C]<b>------------------------------------------------</b>\n' +
      '[R]<b>Bill Amount:' +
      formatAmount(TotalAmount) +
      ' '.repeat(Billamountspace) +
      '</b>\n';
    // Tax
    if (TotalTaxAmount > 0) {
      receiptTextdata +=
        '[R]<b>Tax:' +
        formatAmount(TotalTaxAmount) +
        ' '.repeat(Taxamountspace) +
        '</b>\n';
    }

    // Charges
    if ((data?.ExtrachargeAmount || 0) > 0) {
      receiptTextdata +=
        '[R]<b>Charges:' +
        formatAmount(data.ExtrachargeAmount) +
        ' '.repeat(Chargesamountspace) +
        '</b>\n';
    }

    // Preorder
    if ((data?.PreOrderNetAmount || 0) > 0) {
      receiptTextdata +=
        '[R]<b>Preorder:' +
        formatAmount(data.PreOrderNetAmount) +
        ' '.repeat(Preorderamountspace) +
        '</b>\n';
    }

    // Discount
    var discountAmount = data?.TotalOfferAmount;
    if ((discountAmount || 0) > 0) {
      receiptTextdata +=
        '[R]<b>Discount(-):' +
        formatAmount(discountAmount) +
        ' '.repeat(Discountamountspace) +
        '</b>\n';
    }

    receiptTextdata +=
      '[L]<b>------------------------------------------------</b>\n' +
      '[R]<b>Net:' +
      formatAmount(
        Math.round(
          TotalAmount +
            (TotalTaxAmount || 0) +
            (data?.ExtrachargeAmount || 0) +
            (data?.PreOrderNetAmount || 0) -
            (data?.TotalOfferAmount || 0)
        )
      ) +
      ' '.repeat(Netamountspace) +
      '</b>\n';

    setreceiptTextCatWise(receiptTextdata);
  };

  const mobileItemWisePrintFun = async (printdata) => {
    let Tabledata = printdata?.map((data, index) => {
      const snoSpacing = Math.max(0, 3 - String(index + 1).length);
      // Calculate dynamic spacing for Rate
      const QtySpacing = Math.max(0, 5 - String(data?.Quantity).length);
      const rateSpacing = Math.max(0, 8 - String(data?.Amount).length);
      const StockSpacing = Math.max(0, 4 - String(data?.BalanceQty).length);

      // Calculate dynamic spacing for TotalAmt

      // Generate formatted string with dynamic spacings
      const formattedString =
        ' '.repeat(snoSpacing) +
        parseInt(index + 1) +
        '  ' +
        (data?.ItemName + ' '.repeat(22)).substring(0, 22) +
       (ShowStock ? '  ' :'' ) +
       (ShowStock ? ' '.repeat(StockSpacing):'' ) +
        (ShowStock ? String(data?.BalanceQty):'') +
        '  ' +
        ' '.repeat(QtySpacing) +
        String(data?.Quantity) +
        ' ' +
        ' '.repeat(rateSpacing) +
        String(data?.Amount) +
        ' ' +
        '\n';

      return formattedString;
    });

    const Billamountspace = Math.max(
      0,
      6 - String(formatAmount(TotalAmount)).length
    );
    const Taxamountspace = Math.max(
      0,
      6 - String(formatAmount(TotalTaxAmount)).length
    );
    const Chargesamountspace = Math.max(
      0,
      6 - String(formatAmount(ItemWiseData?.[0]?.ExtrachargeAmount)).length
    );
    const Preorderamountspace = Math.max(
      0,
      6 - String(formatAmount(ItemWiseData?.[0]?.PreOrderNetAmount)).length
    );
    const Discountamountspace = Math.max(
      0,
      6 - String(formatAmount(ItemWiseData?.[0]?.TotalOfferAmount)).length
    );
    const Netamountspace = Math.max(
      0,
      6 -
        String(
          formatAmount(
            TotalAmount +
              (TotalTaxAmount || 0) +
              (ItemWiseData?.[0]?.ExtrachargeAmount || 0) +
              (ItemWiseData?.[0]?.PreOrderNetAmount || 0) -
              (ItemWiseData?.[0]?.TotalOfferAmount || 0)
          )
        ).length
    );
    var data = ItemWiseData && ItemWiseData[0] ? ItemWiseData[0] : {};
    var receiptTextdata =
      "[C]<b><font size='big'>" +
      'Itemwise Sales' +
      '</font></b>\n' +
      '[L]<b>From Date :' +
      reprintDate(OrderFromDate) +
      '[L]<b>' +
      '   ' +
      'To Date :' +
      reprintDate(OrderToDate) +
      '</b>\n' +
      '[C]------------------------------------------------\n' +
      '[L]<b>' +
      '' +
      'S.No' +
      '   ' +
      '  Item Name       ' +
      (ShowStock ?
       ' ' :'  ') +
      (ShowStock ?'Curr Stock':'   ' )+ 
      '  ' +
      'Qty ' +
      '  ' +
      'Amount ' +
      '' +
      '</b>' +
      '[L]\n' +
      '[C]------------------------------------------------\n' +
      Tabledata.join('') +
      '[C]<b>------------------------------------------------</b>\n' +
      '[R]<b>Bill Amount:' +
      formatAmount(TotalAmount) +
      ' '.repeat(Billamountspace) +
      '</b>\n';
    // Tax
    if (TotalTaxAmount > 0) {
      receiptTextdata +=
        '[R]<b>Tax:' +
        formatAmount(TotalTaxAmount) +
        ' '.repeat(Taxamountspace) +
        '</b>\n';
    }

    // Charges
    if ((data?.ExtrachargeAmount || 0) > 0) {
      receiptTextdata +=
        '[R]<b>Charges:' +
        formatAmount(data.ExtrachargeAmount) +
        ' '.repeat(Chargesamountspace) +
        '</b>\n';
    }

    // Preorder
    if ((data?.PreOrderNetAmount || 0) > 0) {
      receiptTextdata +=
        '[R]<b>Preorder:' +
        formatAmount(data.PreOrderNetAmount) +
        ' '.repeat(Preorderamountspace) +
        '</b>\n';
    }

    // Discount
    var discountAmount = data?.TotalOfferAmount;
    if ((discountAmount || 0) > 0) {
      receiptTextdata +=
        '[R]<b>Discount(-):' +
        formatAmount(discountAmount) +
        ' '.repeat(Discountamountspace) +
        '</b>\n';
    }

    receiptTextdata +=
      '[L]<b>------------------------------------------------</b>\n' +
      '[R]<b>Net:' +
      formatAmount(
        Math.round(
          TotalAmount +
            (TotalTaxAmount || 0) +
            (data?.ExtrachargeAmount || 0) +
            (data?.PreOrderNetAmount || 0) -
            (data?.TotalOfferAmount || 0)
        )
      ) +
      ' '.repeat(Netamountspace) +
      '</b>\n';
    setreceiptTextItemWise(receiptTextdata);
  };

  return (
    <div className="ItemWiseReport-container" style={{ overflow: 'auto' }}>
      <div style={{ display: 'none' }}>
        <ItemwiseReportPdf
          datewiseData={ItemWiseData}
          OrderFromDate={OrderFromDate?.split('T')?.[0]}
          OrderToDate={OrderToDate?.split('T')?.[0]}
          TotalAmount={TotalAmount}
          itemData={itemData}
          TotalTaxAmount={TotalTaxAmount}
          TotalCharges={ItemWiseData?.[0]?.ExtrachargeAmount}
          TotalPreOrderAmount={ItemWiseData?.[0]?.PreOrderNetAmount}
          TotalDiscount={ItemWiseData?.[0]?.TotalOfferAmount}
          ShowStock={ShowStock}
        />
        <CategoryWiseReportPdf
          OrderFromDate={OrderFromDate?.split('T')?.[0]}
          OrderToDate={OrderToDate?.split('T')?.[0]}
          TotalAmount={TotalAmount2}
          itemData={CateWiseData}
          TotalTaxAmount={TotalTaxAmount2}
          TotalCharges={CateWiseData?.[0]?.ExtrachargeAmount}
          TotalPreOrderAmount={CateWiseData?.[0]?.PreOrderNetAmount}
          TotalDiscount={CateWiseData?.[0]?.TotalOfferAmount}
        />
      </div>

      <div style={{ overflow: 'auto' }}>
        <Form ref={formRef} onFinish={onFinish}>
          <p className="ItemWiseReport-heading" style={{ overflow: 'auto' }}>
            <div style={{ display: 'flex', gap: '0.5rem' }}>
              <div>
                {!AppType
                  ? apiCall
                    ? 'Category Wise Sales Report'
                    : 'By Item'
                  : 'By Item'}
              </div>
              <div>{!AppType && <Switch onChange={onChange} />}</div>
          <label >
            <input
              type="checkbox"
              checked={ShowStock}
              onChange={(e) => setShowStock(e.target.checked)}
            />
            <span>Show Stock</span>
          </label>
            </div>
          </p>
          <div className="ItemWiseReport-dateaAnd-buttons">
            <div className="ItemWiseReport-Date-picker">


              <Form.Item
                name="dateRange"
                // label={<p className="ItemWiseReport-Date-from-heading required">Date Range</p>}
              >
                <RangePicker
                  onChange={(dates) => {
                    const [from, to] = dates || [];
                    OrderFromDatefetch(from);
                    OrderToDatefetch(to);
                  }}
                  value={[OrderFromDate, OrderToDate]}
                  allowClear
                  disabledDate={(current) => current && current > new Date()} // prevent future dates
                  format="DD-MM-YYYY"
                />
              </Form.Item>
            </div>

            <div className="dropDownandsumit">
              {UserRole !== 'Employee' && (
                <div className="dropdownUserid">
                  <div>
                    <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="itemwiseDropdown"
                        onChangeFunction={(e) => UserDropDownChange(e)}
                        isOnchanges={selectedUserData ? true : false}
                        valueData={selectedUserData}
                      />
                    </Form.Item>
                  </div>
                </div>
              )}
              <div className="Submit_Print">
                <div className="ItemWiseReport-submit-btn-container">
                  <Tooltip title="Submit to search">
                    <button className="ItemWiseReport-submit-btn">
                      {/* <FiSearch /> */}
                      SEARCH
                    </button>
                  </Tooltip>
                </div>

                <div className="ItemWiseReport-PrinttAndSubmit">
                  <div className="ItemWiseReport-PrinterIcon-Container">
                    <Tooltip title="Print">
                      {!apiCall ? (
                        <BiSolidPrinter
                          onClick={Print}
                          className={
                            itemData?.length > 0
                              ? 'ItemWiseReport-printerIcon'
                              : 'ItemWiseReport-printerIcon-disabled'
                          }
                        />
                      ) : (
                        <BiSolidPrinter
                          onClick={Print2}
                          className={
                            CateWiseData?.length > 0
                              ? 'ItemWiseReport-printerIcon'
                              : 'ItemWiseReport-printerIcon-disabled'
                          }
                        />
                      )}
                    </Tooltip>
                  </div>
                  <div>
                    {!apiCall ? (
                      <Tooltip title={'Search by Item Name'}>
                        <div className="search-purchase">
                          <Search
                            placeholder="Search by Item Name"
                            onSearch={onSearch}
                            onSearchChange={onSearchChange}
                          />
                        </div>
                      </Tooltip>
                    ) : !chart ? (
                      <Tooltip title={'Search by Category Name'}>
                        <div>
                          <Search
                            placeholder="Search by Category Name"
                            onSearch={onSearch2}
                            onSearchChange={onSearchChange2}
                          />
                        </div>
                      </Tooltip>
                    ) : (
                      ''
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="ItemWiseReport-search">
            {apiCall && (
              <div
                className="toggle"
                style={{
                  display: 'flex',
                  gap: '0.5rem',
                  fontFamily: 'Poppins',
                }}
              >
                <div>Pie Chart</div>
                <div>
                  <Switch onChange={openChart} />
                </div>
                <div>Table Data</div>
              </div>
            )}
          </div>

          {!apiCall ? (
            <div className="ItemWiseReport-table">
              {/* <Tables
                columns={columns}
                data={itemData}
                onChange={handleChange}
              /> */}
              <table className="custom-table">
                <thead>
                  <tr>
                    <th style={{ textAlign: 'center' }}>SL.NO</th>
                    <th style={{ textAlign: 'center' }}>Item Name</th>
                  {ShowStock && <th style={{ textAlign: 'center' }}>Current Stock Qty</th> }
                    <th style={{ textAlign: 'center' }}>Sales Qty</th>
                    <th style={{ textAlign: 'center' }}>Amount</th>
                  </tr>
                </thead>
                <tbody>
                  {itemData &&
                  itemData.filter(
                    (row) =>
                      !searchedText ||
                      (row.ItemName &&
                        row.ItemName?.toLowerCase()?.includes(
                          searchedText?.toLowerCase()
                        ))
                  ).length > 0 ? (
                    itemData
                      .filter(
                        (row) =>
                          !searchedText ||
                          (row.ItemName &&
                            row.ItemName?.toLowerCase()?.includes(
                              searchedText?.toLowerCase()
                            ))
                      )
                      .map((row, idx) => (
                        <tr key={idx}>
                          <td style={{ textAlign: 'center' }}>{idx + 1}</td>
                          <td style={{ textAlign: 'left' }}>{row?.ItemName}</td>
                         {ShowStock && <td style={{ textAlign: 'center' }}>{row?.StockAvailable ==='Y' ? row?.BalanceQty || 0 : '-'}</td> }
                          <td style={{ textAlign: 'center' }}>
                            {row.Quantity}
                          </td>
                          <td style={{ textAlign: 'right' }}>
                            {safeRound(row.Amount)}
                          </td>
                        </tr>
                      ))
                  ) : (
                    <tr>
                      <td
                        colSpan="4"
                        style={{ textAlign: 'center', padding: '10px' }}
                      >
                        Data not found
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          ) : !chart ? (
            <div className="ItemWiseReport-table">
              {/* <Tables
                columns={columns2}
                data={chartData}
                onChange={handleChange2}
              /> */}
              <table className="custom-table">
                <thead>
                  <tr>
                    <th style={{ textAlign: 'center', width: '120px' }}>
                      SL NO
                    </th>
                    <th style={{ textAlign: 'center' }}>Category</th>
                    <th style={{ textAlign: 'center' }}>Qty</th>
                    <th style={{ textAlign: 'center', width: '190px' }}>
                      Amount
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {chartData &&
                  chartData.filter(
                    (row) =>
                      !searchedText2 ||
                      ((row.ProdCatName || row.name) &&
                        (row.ProdCatName || row.name)
                          ?.toLowerCase()
                          ?.includes(searchedText2?.toLowerCase()))
                  ).length > 0 ? (
                    chartData
                      .filter(
                        (row) =>
                          !searchedText2 ||
                          ((row.ProdCatName || row.name) &&
                            (row.ProdCatName || row.name)
                              ?.toLowerCase()
                              ?.includes(searchedText2?.toLowerCase()))
                      )
                      .map((row, idx) => (
                        <tr key={idx}>
                          <td style={{ textAlign: 'center' }}>{idx + 1}</td>
                          {sportsAppPreference ? (
                            <td style={{ textAlign: 'left' }}>
                              {row?.ProdCatName || row?.name
                                ? `${row?.ProdCatName || row?.name} ${row?.ProdSubCatName ? ` (${row.ProdSubCatName})` : ''}`
                                : ''}
                            </td>
                          ) : (
                            <td style={{ textAlign: 'left' }}>
                              {' '}
                              {row.ProdCatName || row.name}
                            </td>
                          )}
                          <td style={{ textAlign: 'center' }}>
                            {row.SalesQty}
                          </td>
                          <td style={{ textAlign: 'right' }}>
                            {safeRound(row.TotalAmt || row.y)}
                          </td>
                        </tr>
                      ))
                  ) : (
                    <tr>
                      <td
                        colSpan="4"
                        style={{ textAlign: 'center', padding: '10px' }}
                      >
                        Data not found
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          ) : (
            <DynamicPieChart chartData={chartData} />
          )}

          <div className="ItemWiseReport-netAmount">
            {!apiCall ? (
              <div className="ItemWiseReport-Amount-Collected-table">
                <table className="ItemWiseReport-Amount-Collected-table-div">
                  <tbody>
                    <tr>
                      <td>Bill Amount</td>
                      <td>{safeRound(TotalAmount)}</td>
                    </tr>
                    {TotalTaxAmount > 0 && (
                      <tr>
                        <td>Tax</td>
                        <td>{safeRound(TotalTaxAmount)}</td>
                      </tr>
                    )}
                    {ItemWiseData?.[0]?.ExtrachargeAmount > 0 && (
                      <tr>
                        <td>Charges</td>
                        <td>
                          {safeRound(ItemWiseData?.[0]?.ExtrachargeAmount)}
                        </td>
                      </tr>
                    )}
                    {ItemWiseData?.[0]?.PreOrderNetAmount > 0 && (
                      <tr>
                        <td>Preorder</td>
                        <td>
                          {safeRound(ItemWiseData?.[0]?.PreOrderNetAmount)}
                        </td>
                      </tr>
                    )}
                    {ItemWiseData?.[0]?.TotalOfferAmount > 0 && (
                      <tr>
                        <td>Discount(-)</td>
                        <td>
                          {safeRound(ItemWiseData?.[0]?.TotalOfferAmount)}
                        </td>
                      </tr>
                    )}

                    <p className="ItemWiseReport-border-dashed"></p>
                    <tr>
                      <th className="ItemWiseReport-netAmount">Net</th>
                      <th className="ItemWiseReport-netAmount">
                        {safeRound(
                          TotalAmount +
                            (TotalTaxAmount || 0) +
                            (ItemWiseData?.[0]?.PreOrderNetAmount
                              ? ItemWiseData?.[0]?.PreOrderNetAmount
                              : 0) +
                            (ItemWiseData?.[0]?.ExtrachargeAmount
                              ? ItemWiseData?.[0]?.ExtrachargeAmount
                              : 0) -
                            (ItemWiseData?.[0]?.TotalOfferAmount
                              ? ItemWiseData?.[0]?.TotalOfferAmount
                              : 0)
                        ) || 0}
                      </th>
                    </tr>
                  </tbody>
                </table>
              </div>
            ) : (
              !chart && (
                <div className="ItemWiseReport-Amount-Collected-table">
                  <table className="ItemWiseReport-Amount-Collected-table-div">
                    <tbody>
                      <tr>
                        <td>Bill Amount</td>
                        <td>{safeRound(TotalAmount2)}</td>
                      </tr>
                      {TotalTaxAmount2 > 0 && (
                        <tr>
                          <td>Tax</td>
                          <td>{safeRound(TotalTaxAmount2)}</td>
                        </tr>
                      )}
                      {CateWiseData?.[0]?.ExtrachargeAmount > 0 && (
                        <tr>
                          <td>Charges</td>
                          <td>
                            {safeRound(CateWiseData?.[0]?.ExtrachargeAmount)}
                          </td>
                        </tr>
                      )}
                      {CateWiseData?.[0]?.PreOrderNetAmount > 0 && (
                        <tr>
                          <td>Preorder</td>
                          <td>
                            {safeRound(CateWiseData?.[0]?.PreOrderNetAmount)}
                          </td>
                        </tr>
                      )}
                      {CateWiseData?.[0]?.TotalOfferAmount > 0 && (
                        <tr>
                          <td>Discount(-)</td>
                          <td>
                            {safeRound(CateWiseData?.[0]?.TotalOfferAmount)}
                          </td>
                        </tr>
                      )}
                      <p className="ItemWiseReport-border-dashed"></p>
                      <tr>
                        <th className="ItemWiseReport-netAmount">Net</th>
                        <th className="ItemWiseReport-netAmount">
                          {safeRound(
                            TotalAmount2 +
                              (TotalTaxAmount2 || 0) +
                              (CateWiseData?.[0]?.PreOrderNetAmount
                                ? CateWiseData?.[0]?.PreOrderNetAmount
                                : 0) +
                              (CateWiseData?.[0]?.ExtrachargeAmount
                                ? CateWiseData?.[0]?.ExtrachargeAmount
                                : 0) -
                              (CateWiseData?.[0]?.TotalOfferAmount
                                ? CateWiseData?.[0]?.TotalOfferAmount
                                : 0) || 0
                          )}
                        </th>
                      </tr>
                    </tbody>
                  </table>
                </div>
              )
            )}
          </div>
        </Form>
      </div>
    </div>
  );
};

export default ItemWiseReport;
