import { EnquiryReportFilterDto, UnitsOfWeightInput } from '@gtpl/shared-models/sale-management';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Table, Tag, Tooltip } from 'antd'
import { useForm } from 'antd/lib/form/Form';
import React, { useEffect, useRef, useState } from 'react'
import { SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { ColumnProps } from 'antd/lib/table';
import { Excel } from 'antd-table-saveas-excel';
import moment from 'moment';
import { EnquiryLifecycleStatusEnum } from '@gtpl/shared-models/enquiry-management';
import { CountryService, SkuService } from '@gtpl/shared-services/masters';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

const EnquiryCompleteManagementReport = () => {
    const saleOrderService=new SaleOrderService();
    const countryService = new CountryService();
    const skuService = new SkuService()
    const [enquiryReport,setEnquiryReport]=useState([]);
    const {Option}=Select;
    const [form] = Form.useForm();
    const [enquiryNumbers, setEnquiryNumbers] = useState<any[]>([]);
    const [productsData,setProductsData] = useState<any[]>([]);
    const [countriesData,setCountriesData] = useState<any[]>([])
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState<number>(null);
    const {RangePicker}=DatePicker
    const [isVisible,setIsVisible]=useState<boolean>(false)
    const [buyerName, setbuyerName] = useState<any[]>([]);
    const [agentNames, setagentNames] = useState<any[]>([]);
    const [salePersonName, setsalePersonName] = useState<any[]>([]);


    useEffect(()=>{
        // getData();
        getAllEnquiryNumbers();
        getAllCountries()
        getAllProducts()
        getBuyerForEnqReport()
        getAgentForEnqReport()
        getSalePersonForEnqReport()
    },[])

    const getData = () => {
        const req = new EnquiryReportFilterDto()
        if (form.getFieldValue('enquiryNumber') !== undefined) {
          req.enquiryNumber = form.getFieldValue('enquiryNumber')
        }
        if(form.getFieldValue('enquiryDate')!=undefined){
        req.fromDate=moment(form.getFieldValue('enquiryDate')[0]).format('YYYY-MM-DD')
        }
        if(form.getFieldValue('enquiryDate')!=undefined){
        req.toDate=moment(form.getFieldValue('enquiryDate')[1]).format('YYYY-MM-DD')
        }
        if (form.getFieldValue('country') !== undefined) {
            req.countryId = form.getFieldValue('country')
          }
          if (form.getFieldValue('product') !== undefined) {
            req.skuCodeId = form.getFieldValue('product')
          }
          if (form.getFieldValue('buyerId') !== undefined) {
            req.buyerId = form.getFieldValue('buyerId')
          } if (form.getFieldValue('agentId') !== undefined) {
            req.agentId = form.getFieldValue('agentId')
          } if (form.getFieldValue('salePersonId') !== undefined) {
            req.salesPersonId = form.getFieldValue('salePersonId')
          }
        saleOrderService.getCompleteEnquiryManagementReport(req).then(res => {
            if (res.status) {
                setEnquiryReport(res.data);
                setIsVisible(true)
            } else {
              setEnquiryReport([])
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        })
    };

    const getAllEnquiryNumbers = () => {
        saleOrderService.getEnquiryNumbers().then(res => {
            if (res.status) {
                setEnquiryNumbers(res.data);
            } else {
              setEnquiryNumbers([])
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        })
    };

    const getBuyerForEnqReport = () => {
      saleOrderService.getBuyerForEnqReport().then(res => {
          if (res.status) {
              setbuyerName(res.data);
          } else {
            setbuyerName([])
              AlertMessages.getErrorMessage(res.internalMessage);
          }
      })
  };

  const getAgentForEnqReport = () => {
    saleOrderService.getAgentForEnqReport().then(res => {
        if (res.status) {
            setagentNames(res.data);
        } else {
          setagentNames([])
            AlertMessages.getErrorMessage(res.internalMessage);
        }
    })
};

const getSalePersonForEnqReport = () => {
  saleOrderService.getSalePersonForEnqReport().then(res => {
      if (res.status) {
          setsalePersonName(res.data);
      } else {
        setsalePersonName([])
          AlertMessages.getErrorMessage(res.internalMessage);
      }
  })
};

    const getAllProducts = () => {
        saleOrderService.getEnquiryManagementReportProductData().then(res => {
            if (res.status) {
                setProductsData(res.data);
            } else {
                setProductsData([])
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        })
    };

    const getAllCountries = () => {
        countryService.getAllCountries().then(res => {
            if (res.status) {
                setCountriesData(res.data);
            } else {
                setCountriesData([])
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        })
    };

    const onReset = () => {
        form.resetFields();
        // getData();
        setIsVisible(false)
      };

      function handleSearch(selectedKeys, confirm, dataIndex) {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };
    function handleReset(clearFilters) {
        clearFilters();
        setSearchText('');
    };
    const getColumnSearchProps = (dataIndex: string) => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <div style={{ padding: 8 }}>
                <Input
                    ref={searchInput}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{ width: 188, marginBottom: 8, display: 'block' }}
                />
                <Button
                    type="primary"
                    onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
                    icon={<SearchOutlined />}
                    size="small"
                    style={{ width: 90, marginRight: 8 }}
                >
                    Search
                </Button>
                <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
                    Reset
                </Button>
            </div>
        ),
        filterIcon: filtered => (
            <SearchOutlined type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
        ),
        onFilter: (value, record) =>
            record[dataIndex]
                ? record[dataIndex]
                    .toString()
                    .toLowerCase()
                    .includes(value.toLowerCase())
                : false,
        onFilterDropdownVisibleChange: visible => {
            if (visible) { setTimeout(() => searchInput.current.select()); }
        },
        render: text =>
            text ? (
                searchedColumn === dataIndex ? (
                    <Highlighter
                        highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                        searchWords={[searchText]}
                        autoEscape
                        textToHighlight={text.toString()}
                    />
                ) : text
            ) : null
    });
    const enquiryStatusFilters = Object.values(EnquiryLifecycleStatusEnum).map(status => ({
        text: status,
        value: status
    }));
    // const Columns: ColumnProps<any>[]=[
    //     {
    //         title: 'S.No',
    //         width:"20px",
    //         render: (text, object, index) => (page - 1) * pageSize + (index + 1)
        
    //       },
    //     {
    //         title:"Enquiry Number",
    //         dataIndex:"enquiryNumber",
    //         fixed:'left',
    //         render:(text)=>{
    //             const enquiryNumber=text?text:"-"
    //             return(
    //                 <>{enquiryNumber}</>
    //             )
    //         },
    //         sorter: (a, b) => a.enquiryNumber?.localeCompare(b.enquiryNumber),
    //         sortDirections: ['descend', 'ascend'],
    //         ...getColumnSearchProps('enquiryNumber')
    //     },
    //     {
    //         title:"Enquiry Date",
    //         dataIndex:"enqDate",
    //         render:(value)=>{
    //             const date=moment(value).format("DD-MM-YYYY")
    //             return(
    //                 <>{date}</>
    //             )
    //         }
    //     },

    //     {
    //         title:"Source From",
    //         dataIndex:"sourceFrom"
    //     },
    //     {
    //         title:"Country",
    //         dataIndex:"country"
    //     },  
    //     {
    //         title:"Order Type",
    //         dataIndex:"orderType",
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => (
    //                     <div key={index}>{item.orderType}</div>
    //                 ));
    //             }
    //             return null;
    //         }
    //     },
    //     {
    //         title:"Category",
    //         dataIndex:"category",
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => (
    //                     <div key={index}>{item.category}</div>
    //                 ));
    //             }
    //             return null;
    //         }
    //     },
    //     {
    //         title: "Product",
    //         dataIndex: "shortCode",
    //         sorter: (a, b) => {
    //             const shortCodeA = a.products && a.products[0]?.details[0]?.shortCode;
    //             const shortCodeB = b.products && b.products[0]?.details[0]?.shortCode;
        
    //             if (!shortCodeA) return 1;
    //             if (!shortCodeB) return -1;
                
    //             return shortCodeA.localeCompare(shortCodeB);
    //         },
    //         sortDirections: ["ascend", "descend"],
    //         ...getColumnSearchProps('shortCode'),
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => (
    //                     <div key={index}>{item.shortCode}</div>
    //                 ));
    //             }
    //             return null;
    //         }
    //     },
        
    //     {
    //         title:"Brand",
    //         dataIndex:"brandName",
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => (
    //                     <div key={index}>{item.brandName}</div>
    //                 ));
    //             }
    //             return null;
    //         },
    //     },
    //     {
    //         title:"No Of Containers",
    //         dataIndex:"noOfContainers",
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => (
    //                     <div key={index}>{item.noOfContainers}</div>
    //                 ));
    //             }
    //             return null;
    //         },
    //     },
    //     {
    //         title: "Pack Style",
    //         dataIndex: "packStyle",
    //         sorter: (a, b) => {
    //             const packStyleA = a.products && a.products[0]?.details[0]?.packStyle;
    //             const packStyleB = b.products && b.products[0]?.details[0]?.packStyle;
        
    //             if (!packStyleA) return 1;
    //             if (!packStyleB) return -1;
                
    //             return packStyleA.localeCompare(packStyleB);
    //         },
    //         sortDirections: ["ascend", "descend"],
    //         ...getColumnSearchProps('packStyle'),
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => (
    //                     <div key={index}>{item.packStyle}</div>
    //                 ));
    //             }
    //             return null;
    //         }
    //     },
    //     {
    //         title: "Net Shrimp Weight",
    //         dataIndex: "netShrimpWeight",
    //         sorter: (a, b) => {
    //             const netShrimpWeightA = parseFloat(a.products?.[0]?.details?.[0]?.netShrimpWeight) || 0;
    //             const netShrimpWeightB = parseFloat(b.products?.[0]?.details?.[0]?.netShrimpWeight) || 0;
                
    //             return netShrimpWeightA - netShrimpWeightB;
    //         },
    //         sortDirections: ["ascend", "descend"],
    //         ...getColumnSearchProps("netShrimpWeight"),
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => {
    //                     const formattedValue = new Intl.NumberFormat("en-IN", {
    //                         minimumFractionDigits: 0,
    //                         maximumFractionDigits: 2
    //                     }).format(parseFloat(item.netShrimpWeight || 0));
                        
    //                     return <div key={index}>{formattedValue}</div>;
    //                 });
    //             }
    //             return null;
    //         }
    //     },
    //     {
    //         title: "Unit Price",
    //         dataIndex: "unitPrice",
    //         sorter: (a, b) => {
    //             const unitPriceA = parseFloat(a.products?.[0]?.details?.[0]?.unitPrice) || 0;
    //             const unitPriceB = parseFloat(b.products?.[0]?.details?.[0]?.unitPrice) || 0;
                
    //             return unitPriceA - unitPriceB;
    //         },
    //         sortDirections: ["ascend", "descend"],
    //         ...getColumnSearchProps("unitPrice"),
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => {
    //                     const formattedValue = new Intl.NumberFormat("en-IN", {
    //                         minimumFractionDigits: 0,
    //                         maximumFractionDigits: 2
    //                     }).format(parseFloat(item.unitPrice || 0));
                        
    //                     return <div key={index}>{formattedValue}</div>;
    //                 });
    //             }
    //             return null;
    //         }
    //     },
    //     {
    //         title: "No. Of Cases",
    //         dataIndex: "cases",
    //         sorter: (a, b) => {
    //             const casesA = a.products && a.products[0]?.details[0]?.cases;
    //             const casesB = b.products && b.products[0]?.details[0]?.cases;
        
    //             if (!casesA) return 1;
    //             if (!casesB) return -1;
                
    //             return casesA.localeCompare(casesB);
    //         },
    //         sortDirections: ["ascend", "descend"],
    //         ...getColumnSearchProps('cases'),
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => (
    //                     <div key={index}>{item.cases}</div>
    //                 ));
    //             }
    //             return null;
    //         }
    //     },
    //     {
    //        title:"Pack Count",
    //        dataIndex:"packCount",
    //        render: (text, record) => {
    //         if (record.products && record.products[0]?.details.length > 0) {
    //             return record.products[0].details.map((item, index) => (
    //                 <div key={index}>{item.packCount}</div>
    //             ));
    //         }
    //         return null;
    //     },
    //     },
    //     {
    //         title: "Net Case Weight",
    //         dataIndex: "caseWeight",
    //         sorter: (a, b) => {
    //             const caseWeightA = parseFloat(a.products?.[0]?.details?.[0]?.caseWeight) || 0;
    //             const caseWeightB = parseFloat(b.products?.[0]?.details?.[0]?.caseWeight) || 0;
                
    //             return caseWeightA - caseWeightB;
    //         },
    //         sortDirections: ["ascend", "descend"],
    //         ...getColumnSearchProps("caseWeight"),
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => {
    //                     const formattedValue = new Intl.NumberFormat("en-IN", {
    //                         minimumFractionDigits: 0,
    //                         maximumFractionDigits: 2
    //                     }).format(parseFloat(item.caseWeight || 0));
                        
    //                     return <div key={index}>{formattedValue}</div>;
    //                 });
    //             }
    //             return null;
    //         }
    //     },
    //     {
    //         title: "Net Amount",
    //         dataIndex: "netAmount",
    //         sorter: (a, b) => {
    //             const netAmountA = parseFloat(a.products?.[0]?.details?.[0]?.netAmount) || 0;
    //             const netAmountB = parseFloat(b.products?.[0]?.details?.[0]?.netAmount) || 0;
                
    //             return netAmountA - netAmountB;
    //         },
    //         sortDirections: ["ascend", "descend"],
    //         ...getColumnSearchProps("netAmount"),
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => {
    //                     const formattedValue = new Intl.NumberFormat("en-IN", {
    //                         minimumFractionDigits: 0,
    //                         maximumFractionDigits: 2
    //                     }).format(parseFloat(item.netAmount || 0));
                        
    //                     return <div key={index}>{formattedValue}</div>;
    //                 });
    //             }
    //             return null;
    //         }
    //     },
    //     {
    //         title: "Total P/L",
    //         dataIndex: "finalProfitLoss",
    //         sorter: (a, b) => {
    //             const netAmountA = parseFloat(a.products?.[0]?.details?.[0]?.finalProfitLoss) || 0;
    //             const netAmountB = parseFloat(b.products?.[0]?.details?.[0]?.finalProfitLoss) || 0;
                
    //             return netAmountA - netAmountB;
    //         },
    //         sortDirections: ["ascend", "descend"],
    //         ...getColumnSearchProps("finalProfitLoss"),
    //         render: (text, record) => {
    //             if (record.products && record.products[0]?.details.length > 0) {
    //                 return record.products[0].details.map((item, index) => {
    //                     const formattedValue = new Intl.NumberFormat("en-IN", {
    //                         minimumFractionDigits: 0,
    //                         maximumFractionDigits: 2
    //                     }).format(parseFloat(item.finalProfitLoss || 0));
                        
    //                     return <div key={index}>{formattedValue}</div>;
    //                 });
    //             }
    //             return null;
    //         }
    //     },
    //     {
    //         title: "Total P/L In Rupees",
    //         dataIndex: "netWeight",
    //         sorter: (a, b) => {
    //             const exchangeRate = 85;
    //             const getTotalPLInRupees = (record) => {
    //                 const details = record.products?.[0]?.details || [];
    //                 return details.reduce((sum, detail) => {
    //                     const qtyUOMId = UnitsOfWeightInput.find(e => e.value === detail.qtyUOM)?.name === 'lb' ||
    //                                     UnitsOfWeightInput.find(e => e.value === detail.qtyUOM)?.name === 'oz'
    //                         ? UnitsOfWeightInput.find(e => e.name === 'lb').value
    //                         : UnitsOfWeightInput.find(e => e.name === 'kg').value;
    //                     const priceUOM = detail.priceUOM || qtyUOMId; 
    //                     let weight = parseFloat(detail.netWeight || 0);
    
    //                     if (qtyUOMId !== priceUOM) {
    //                         if (priceUOM === UnitsOfWeightInput.find(e => e.name === 'lb').value) {
    //                             weight = weight / 0.454; 
    //                         } else {
    //                             weight = weight * 0.454; 
    //                         }
    //                     }
    
    //                     const finalPL = parseFloat(detail.finalProfitLoss || 0);
    //                     return sum + (weight * finalPL * exchangeRate);
    //                 }, 0);
    //             };
    //             return getTotalPLInRupees(a) - getTotalPLInRupees(b);
    //         },
    //         sortDirections: ["ascend", "descend"],
    //         render: (text, record) => {
    //             const exchangeRate = 85;
    //             const details = record.products?.[0]?.details;
    
    //             if (!Array.isArray(details)) return null;
    
    //             return details.map((item, index) => {
    //                 const qtyUOMId = UnitsOfWeightInput.find(e => e.value === item.qtyUOM)?.name === 'lb' ||
    //                                 UnitsOfWeightInput.find(e => e.value === item.qtyUOM)?.name === 'oz'
    //                     ? UnitsOfWeightInput.find(e => e.name === 'lb').value
    //                     : UnitsOfWeightInput.find(e => e.name === 'kg').value;
    //                 const priceUOM = item.priceUOM || qtyUOMId; 
    //                 let weight = parseFloat(item.netWeight || 0);
    
    //                 if (qtyUOMId !== priceUOM) {
    //                     if (priceUOM === UnitsOfWeightInput.find(e => e.name === 'lb').value) {
    //                         weight = weight / 0.454; // kg to lb
    //                     } else {
    //                         weight = weight * 0.454; // lb to kg
    //                     }
    //                 }
    
    //                 const finalPL = parseFloat(item.finalProfitLoss || 0);
    //                 const totalPLInRupees = weight * finalPL * exchangeRate;
    
    //                 const formattedValue = new Intl.NumberFormat("en-IN", {
    //                     minimumFractionDigits: 2,
    //                     maximumFractionDigits: 2
    //                 }).format(totalPLInRupees);
    
    //                 return <div key={index}>{formattedValue}</div>;
    //             });
    //         }
    //     },
          
        
        
        
    //     {
    //         title: "Status",
    //         dataIndex: "enqStatus",
    //         // fixed: 'right',
    //         render: (text) => {
    //             const enqStatus = text || "-";
    //             return <>{enqStatus}</>;
    //         },
    //         filters: enquiryStatusFilters,
    //         onFilter: (value, record) => record.enqStatus === value
    //     },
    //     {
    //         title: "Rejected Reason",
    //         dataIndex: "reasonName",
            
    //         sorter: (a, b) => (a.reasonName || "").localeCompare(b.reasonName || ""),
    //         sortDirections: ['descend', 'ascend'],
    //         ...getColumnSearchProps('reasonName'),
    //         render: (text,record) => (record.reasonName ? record.reasonName : "-"),
    //     },
    //     {
    //         title: "Rejected Description",
    //         dataIndex: "rejectedDescription",
    //         sorter: (a, b) => (a.rejectedDescription || "").localeCompare(b.rejectedDescription || ""),
    //         sortDirections: ['descend', 'ascend'],
    //         ...getColumnSearchProps('rejectedDescription'),
    //         render: (text, record) => (
    //             record.rejectedDescription ? (
    //                 <Tooltip title={record.rejectedDescription}>
    //                     {record.rejectedDescription.length > 50 
    //                         ? `${record.rejectedDescription.substring(0, 50)}...` 
    //                         : record.rejectedDescription}
    //                 </Tooltip>
    //             ) : "-"
    //         ),
    //     }
        
        
        
    // ]
    // correct
    const Columns: ColumnProps<any>[] = [
        {
          title: 'S.No',
          width: "20px",
          render: (text, object, index) => (page - 1) * pageSize + (index + 1)
        },
        {
          title: "Enquiry Number",
          dataIndex: "enquiryNumber",
          fixed: 'left',
          render: (text) => {
            const enquiryNumber = text ? text : "-";
            return <>{enquiryNumber}</>;
          },
          sorter: (a, b) => a.enquiryNumber?.localeCompare(b.enquiryNumber),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('enquiryNumber')
        },
        {
          title: "Enquiry Date",
          dataIndex: "enqDate",
          render: (value) => {
            const date = moment(value).format("DD-MM-YYYY");
            return <>{date}</>;
          },
           sorter: (a, b) => a.enqDate?.localeCompare(b.enqDate),
          sortDirections: ['descend', 'ascend'],
        },
        {
          title: "Source From",
          dataIndex: "sourceFrom",
          sorter: (a, b) => a.sourceFrom?.localeCompare(b.sourceFrom),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('sourceFrom')
        },
        {
          title: "Country",
          dataIndex: "country",
            sorter: (a, b) => a.country?.localeCompare(b.country),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('country')
        },
        {
          title: "Buyer",
          dataIndex: "buyerName",
          render:(text, record) => {
            return record.buyerName ? record.buyerName : "-";
          },
             sorter: (a, b) => a.buyerName?.localeCompare(b.buyerName),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('buyerName')
        },
        {
          title: "Agent",
          dataIndex: "agentName",
          render:(text, record) => {
            return record.agentName ? record.agentName : "-";
          },
          sorter: (a, b) => a.agentName?.localeCompare(b.agentName),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('agentName')

        },
        {
          title: "Sale Person",
          dataIndex: "salePerson",
          render:(text, record) => {
            return record.salePerson ? record.salePerson : "-";
          },
           sorter: (a, b) => a.salePerson?.localeCompare(b.salePerson),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('salePerson')

        },
        {
          title: "Order Type",
          dataIndex: "orderType",
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => (
                  <div key={`${groupIndex}-${index}`}>{item.orderType}</div>
                ))
              );
            }
            return null;
          }
        },
        {
          title: "Category",
          dataIndex: "category",
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => (
                  <div key={`${groupIndex}-${index}`}>{item.category}</div>
                ))
              );
            }
            return null;
          }
        },
        {
          title: "Product",
          dataIndex: "shortCode",
          sorter: (a, b) => {
            const shortCodeA = a.products?.[0]?.details[0]?.shortCode || '';
            const shortCodeB = b.products?.[0]?.details[0]?.shortCode || '';
            return shortCodeA.localeCompare(shortCodeB);
          },
          sortDirections: ["ascend", "descend"],
          ...getColumnSearchProps('shortCode'),
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => (
                  <div key={`${groupIndex}-${index}`}>{item.shortCode}</div>
                ))
              );
            }
            return null;
          }
        },
        {
          title: "Brand",
          dataIndex: "brandName",
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => (
                  <div key={`${groupIndex}-${index}`}>{item.brandName}</div>
                ))
              );
            }
            return null;
          }
        },
        {
          title: "No Of Containers",
          dataIndex: "noOfContainers",
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => (
                  <div key={`${groupIndex}-${index}`}>{item.noOfContainers}</div>
                ))
              );
            }
            return null;
          }
        },
        {
          title: "Pack Style",
          dataIndex: "packStyle",
          sorter: (a, b) => {
            const packStyleA = a.products?.[0]?.details[0]?.packStyle || '';
            const packStyleB = b.products?.[0]?.details[0]?.packStyle || '';
            return packStyleA.localeCompare(packStyleB);
          },
          sortDirections: ["ascend", "descend"],
          ...getColumnSearchProps('packStyle'),
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => (
                  <div key={`${groupIndex}-${index}`}>{item.packStyle}</div>
                ))
              );
            }
            return null;
          }
        },
        {
          title: "Net Shrimp Weight",
          dataIndex: "netShrimpWeight",
          sorter: (a, b) => {
            const netShrimpWeightA = parseFloat(a.products?.[0]?.details?.[0]?.netShrimpWeight) || 0;
            const netShrimpWeightB = parseFloat(b.products?.[0]?.details?.[0]?.netShrimpWeight) || 0;
            return netShrimpWeightA - netShrimpWeightB;
          },
          sortDirections: ["ascend", "descend"],
          ...getColumnSearchProps("netShrimpWeight"),
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => {
                  const formattedValue = new Intl.NumberFormat("en-IN", {
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 2
                  }).format(parseFloat(item.netShrimpWeight || 0));
                  return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
                })
              );
            }
            return null;
          }
        },
        {
          title: "Unit Price",
          dataIndex: "unitPrice",
          sorter: (a, b) => {
            const unitPriceA = parseFloat(a.products?.[0]?.details?.[0]?.unitPrice) || 0;
            const unitPriceB = parseFloat(b.products?.[0]?.details?.[0]?.unitPrice) || 0;
            return unitPriceA - unitPriceB;
          },
          sortDirections: ["ascend", "descend"],
          ...getColumnSearchProps("unitPrice"),
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => {
                  const formattedValue = new Intl.NumberFormat("en-IN", {
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 2
                  }).format(parseFloat(item.unitPrice || 0));
                  return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
                })
              );
            }
            return null;
          }
        },
        {
          title: "No. Of Cases",
          dataIndex: "cases",
          sorter: (a, b) => {
            const casesA = a.products?.[0]?.details[0]?.cases || '';
            const casesB = b.products?.[0]?.details[0]?.cases || '';
            return casesA.localeCompare(casesB);
          },
          sortDirections: ["ascend", "descend"],
          ...getColumnSearchProps('cases'),
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => (
                  <div key={`${groupIndex}-${index}`}>{item.cases}</div>
                ))
              );
            }
            return null;
          }
        },
        {
          title: "Pack Count",
          dataIndex: "packCount",
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => (
                  <div key={`${groupIndex}-${index}`}>{item.packCount}</div>
                ))
              );
            }
            return null;
          }
        },
        {
          title: "Net Case Weight",
          dataIndex: "caseWeight",
          sorter: (a, b) => {
            const caseWeightA = parseFloat(a.products?.[0]?.details?.[0]?.caseWeight) || 0;
            const caseWeightB = parseFloat(b.products?.[0]?.details?.[0]?.caseWeight) || 0;
            return caseWeightA - caseWeightB;
          },
          sortDirections: ["ascend", "descend"],
          ...getColumnSearchProps("caseWeight"),
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => {
                  const formattedValue = new Intl.NumberFormat("en-IN", {
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 2
                  }).format(parseFloat(item.caseWeight || 0));
                  return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
                })
              );
            }
            return null;
          }
        },
        {
          title: "Net Amount",
          dataIndex: "netAmount",
          sorter: (a, b) => {
            const netAmountA = parseFloat(a.products?.[0]?.details?.[0]?.netAmount) || 0;
            const netAmountB = parseFloat(b.products?.[0]?.details?.[0]?.netAmount) || 0;
            return netAmountA - netAmountB;
          },
          sortDirections: ["ascend", "descend"],
          ...getColumnSearchProps("netAmount"),
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => {
                  const formattedValue = new Intl.NumberFormat("en-IN", {
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 2
                  }).format(parseFloat(item.netAmount || 0));
                  return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
                })
              );
            }
            return null;
          }
        },
        {
          title: "Total P/L",
          dataIndex: "finalProfitLoss",
          sorter: (a, b) => {
            const netAmountA = parseFloat(a.products?.[0]?.details?.[0]?.finalProfitLoss) || 0;
            const netAmountB = parseFloat(b.products?.[0]?.details?.[0]?.finalProfitLoss) || 0;
            return netAmountA - netAmountB;
          },
          sortDirections: ["ascend", "descend"],
          ...getColumnSearchProps("finalProfitLoss"),
          render: (text, record) => {
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => {
                  const formattedValue = new Intl.NumberFormat("en-IN", {
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 2
                  }).format(parseFloat(item.finalProfitLoss || 0));
                  return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
                })
              );
            }
            return null;
          }
        },
        {
          title: "Total P/L In Rupees",
          dataIndex: "netWeight",
          sorter: (a, b) => {
            const exchangeRate = 85;
            const getTotalPLInRupees = (record) => {
              const details = record.products?.flatMap(product => product.details) || [];
              return details.reduce((sum, detail) => {
                const qtyUOMId = UnitsOfWeightInput.find(e => e.value === detail.qtyUOM)?.name === 'lb' ||
                                UnitsOfWeightInput.find(e => e.value === detail.qtyUOM)?.name === 'oz'
                  ? UnitsOfWeightInput.find(e => e.name === 'lb').value
                  : UnitsOfWeightInput.find(e => e.name === 'kg').value;
                const priceUOM = detail.priceUOM || qtyUOMId;
                let weight = parseFloat(detail.netWeight || 0);
      
                if (qtyUOMId !== priceUOM) {
                  if (priceUOM === UnitsOfWeightInput.find(e => e.name === 'lb').value) {
                    weight = weight / 0.454; // kg to lb
                  } else {
                    weight = weight * 0.454; // lb to kg
                  }
                }
      
                const finalPL = parseFloat(detail.finalProfitLoss || 0);
                return sum + (weight * finalPL * exchangeRate);
              }, 0);
            };
            return getTotalPLInRupees(a) - getTotalPLInRupees(b);
          },
          sortDirections: ["ascend", "descend"],
          render: (text, record) => {
            const exchangeRate = 85;
            if (record.products && record.products.length > 0) {
              return record.products.map((product, groupIndex) =>
                product.details.map((item, index) => {
                  const qtyUOMId = UnitsOfWeightInput.find(e => e.value === item.qtyUOM)?.name === 'lb' ||
                                  UnitsOfWeightInput.find(e => e.value === item.qtyUOM)?.name === 'oz'
                    ? UnitsOfWeightInput.find(e => e.name === 'lb').value
                    : UnitsOfWeightInput.find(e => e.name === 'kg').value;
                  const priceUOM = item.priceUOM || qtyUOMId;
                  let weight = parseFloat(item.netWeight || 0);
      
                  if (qtyUOMId !== priceUOM) {
                    if (priceUOM === UnitsOfWeightInput.find(e => e.name === 'lb').value) {
                      weight = weight / 0.454; // kg to lb
                    } else {
                      weight = weight * 0.454; // lb to kg
                    }
                  }
      
                  const finalPL = parseFloat(item.finalProfitLoss || 0);
                  const totalPLInRupees = weight * finalPL * exchangeRate;
      
                  const formattedValue = new Intl.NumberFormat("en-IN", {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                  }).format(totalPLInRupees);
      
                  return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
                })
              );
            }
            return null;
          }
        },
        {
          title: " Enquiry Status",
          dataIndex: "enqStatus",
          render: (text) => {
            const enqStatus = text || "-";
            return <>{enqStatus}</>;
          },
          filters: enquiryStatusFilters,
          onFilter: (value, record) => record.enqStatus === value
        },
        {
          title: "Status",
          dataIndex: "enqStatus",
          render: (text) => {
            const enqStatus = text || "-";
            if (enqStatus === "CLOSED") {
              return <>Order Confirmed</>;
            } else {
              return <>Order Not Confirmed</>;
            }
          },
          filters: [
            { text: "Order Confirmed", value: "CONFIRMED" },
            { text: "Order Not Confirmed", value: "NOT_CONFIRMED" },
          ],
          onFilter: (value, record) => {
            if (value === "CONFIRMED") return record.enqStatus === "CLOSED";
            if (value === "NOT_CONFIRMED") return record.enqStatus !== "CLOSED";
            return true;
          }
        },
        {
          title: "Rejected Reason",
          dataIndex: "reasonName",
          sorter: (a, b) => (a.reasonName || "").localeCompare(b.reasonName || ""),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('reasonName'),
          render: (text, record) => (record.reasonName ? record.reasonName : "-"),
        },
        {
          title: "Rejected Description",
          dataIndex: "rejectedDescription",
          sorter: (a, b) => (a.rejectedDescription || "").localeCompare(b.rejectedDescription || ""),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('rejectedDescription'),
          render: (text, record) => (
            record.rejectedDescription ? (
              <Tooltip title={record.rejectedDescription}>
                {record.rejectedDescription.length > 50
                  ? `${record.rejectedDescription.substring(0, 50)}...`
                  : record.rejectedDescription}
              </Tooltip>
            ) : "-"
          ),
        },
                {
          title: "Cancel Reason",
          dataIndex: "cancelReason",
          sorter: (a, b) => (a.cancelReason || "").localeCompare(b.cancelReason || ""),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('cancelReason'),
          render: (text, record) => (record.cancelReason ? record.cancelReason : "-"),
        }

      ];

    // const Columns: ColumnProps<any>[] = [
    //     {
    //       title: 'S.No',
    //       width: "20px",
    //       render: (text, object, index) => (page - 1) * pageSize + (index + 1)
    //     },
    //     {
    //       title: "Enquiry Number",
    //       dataIndex: "enquiryNumber",
    //       fixed: 'left',
    //       render: (text) => {
    //         const enquiryNumber = text ? text : "-";
    //         return <>{enquiryNumber}</>;
    //       },
    //       sorter: (a, b) => a.enquiryNumber?.localeCompare(b.enquiryNumber),
    //       sortDirections: ['descend', 'ascend'],
    //       ...getColumnSearchProps('enquiryNumber')
    //     },
    //     {
    //       title: "Enquiry Date",
    //       dataIndex: "enqDate",
    //       render: (value) => {
    //         const date = moment(value).format("DD-MM-YYYY");
    //         return <>{date}</>;
    //       }
    //     },
    //     {
    //       title: "Source From",
    //       dataIndex: "sourceFrom"
    //     },
    //     {
    //       title: "Country",
    //       dataIndex: "country"
    //     },
    //     {
    //       title: "Order Type",
    //       dataIndex: "orderType",
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => (
    //               <div key={`${groupIndex}-${index}`}>{item.orderType}</div>
    //             ))
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Category",
    //       dataIndex: "category",
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => (
    //               <div key={`${groupIndex}-${index}`}>{item.category}</div>
    //             ))
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Product",
    //       dataIndex: "shortCode",
    //       sorter: (a, b) => {
    //         const shortCodeA = a.products?.[0]?.details[0]?.shortCode || '';
    //         const shortCodeB = b.products?.[0]?.details[0]?.shortCode || '';
    //         return shortCodeA.localeCompare(shortCodeB);
    //       },
    //       sortDirections: ["ascend", "descend"],
    //       ...getColumnSearchProps('shortCode'),
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => (
    //               <div key={`${groupIndex}-${index}`}>{item.shortCode}</div>
    //             ))
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Brand",
    //       dataIndex: "brandName",
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => (
    //               <div key={`${groupIndex}-${index}`}>{item.brandName}</div>
    //             ))
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "No Of Containers",
    //       dataIndex: "noOfContainers",
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => (
    //               <div key={`${groupIndex}-${index}`}>{item.noOfContainers}</div>
    //             ))
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Pack Style",
    //       dataIndex: "packStyle",
    //       sorter: (a, b) => {
    //         const packStyleA = a.products?.[0]?.details[0]?.packStyle || '';
    //         const packStyleB = b.products?.[0]?.details[0]?.packStyle || '';
    //         return packStyleA.localeCompare(packStyleB);
    //       },
    //       sortDirections: ["ascend", "descend"],
    //       ...getColumnSearchProps('packStyle'),
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => (
    //               <div key={`${groupIndex}-${index}`}>{item.packStyle}</div>
    //             ))
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Net Shrimp Weight",
    //       dataIndex: "netShrimpWeight",
    //       sorter: (a, b) => {
    //         const netShrimpWeightA = parseFloat(a.products?.[0]?.details?.[0]?.netShrimpWeight) || 0;
    //         const netShrimpWeightB = parseFloat(b.products?.[0]?.details?.[0]?.netShrimpWeight) || 0;
    //         return netShrimpWeightA - netShrimpWeightB;
    //       },
    //       sortDirections: ["ascend", "descend"],
    //       ...getColumnSearchProps("netShrimpWeight"),
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => {
    //               const formattedValue = new Intl.NumberFormat("en-IN", {
    //                 minimumFractionDigits: 0,
    //                 maximumFractionDigits: 2
    //               }).format(parseFloat(item.netShrimpWeight || 0));
    //               return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
    //             })
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Unit Price",
    //       dataIndex: "unitPrice",
    //       sorter: (a, b) => {
    //         const unitPriceA = parseFloat(a.products?.[0]?.details?.[0]?.unitPrice) || 0;
    //         const unitPriceB = parseFloat(b.products?.[0]?.details?.[0]?.unitPrice) || 0;
    //         return unitPriceA - unitPriceB;
    //       },
    //       sortDirections: ["ascend", "descend"],
    //       ...getColumnSearchProps("unitPrice"),
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => {
    //               const formattedValue = new Intl.NumberFormat("en-IN", {
    //                 minimumFractionDigits: 0,
    //                 maximumFractionDigits: 2
    //               }).format(parseFloat(item.unitPrice || 0));
    //               return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
    //             })
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "No. Of Cases",
    //       dataIndex: "cases",
    //       sorter: (a, b) => {
    //         const casesA = a.products?.[0]?.details[0]?.cases || '';
    //         const casesB = b.products?.[0]?.details[0]?.cases || '';
    //         return casesA.localeCompare(casesB);
    //       },
    //       sortDirections: ["ascend", "descend"],
    //       ...getColumnSearchProps('cases'),
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => (
    //               <div key={`${groupIndex}-${index}`}>{item.cases}</div>
    //             ))
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Pack Count",
    //       dataIndex: "packCount",
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => (
    //               <div key={`${groupIndex}-${index}`}>{item.packCount}</div>
    //             ))
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Net Case Weight",
    //       dataIndex: "caseWeight",
    //       sorter: (a, b) => {
    //         const caseWeightA = parseFloat(a.products?.[0]?.details?.[0]?.caseWeight) || 0;
    //         const caseWeightB = parseFloat(b.products?.[0]?.details?.[0]?.caseWeight) || 0;
    //         return caseWeightA - caseWeightB;
    //       },
    //       sortDirections: ["ascend", "descend"],
    //       ...getColumnSearchProps("caseWeight"),
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => {
    //               const formattedValue = new Intl.NumberFormat("en-IN", {
    //                 minimumFractionDigits: 0,
    //                 maximumFractionDigits: 2
    //               }).format(parseFloat(item.caseWeight || 0));
    //               return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
    //             })
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Net Amount",
    //       dataIndex: "netAmount",
    //       sorter: (a, b) => {
    //         const netAmountA = parseFloat(a.products?.[0]?.details?.[0]?.netAmount) || 0;
    //         const netAmountB = parseFloat(b.products?.[0]?.details?.[0]?.netAmount) || 0;
    //         return netAmountA - netAmountB;
    //       },
    //       sortDirections: ["ascend", "descend"],
    //       ...getColumnSearchProps("netAmount"),
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => {
    //               const formattedValue = new Intl.NumberFormat("en-IN", {
    //                 minimumFractionDigits: 0,
    //                 maximumFractionDigits: 2
    //               }).format(parseFloat(item.netAmount || 0));
    //               return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
    //             })
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Total P/L",
    //       dataIndex: "finalProfitLoss",
    //       sorter: (a, b) => {
    //         const netAmountA = parseFloat(a.products?.[0]?.details?.[0]?.finalProfitLoss) || 0;
    //         const netAmountB = parseFloat(b.products?.[0]?.details?.[0]?.finalProfitLoss) || 0;
    //         return netAmountA - netAmountB;
    //       },
    //       sortDirections: ["ascend", "descend"],
    //       ...getColumnSearchProps("finalProfitLoss"),
    //       render: (text, record) => {
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => {
    //               const formattedValue = new Intl.NumberFormat("en-IN", {
    //                 minimumFractionDigits: 0,
    //                 maximumFractionDigits: 2
    //               }).format(parseFloat(item.finalProfitLoss || 0));
    //               return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
    //             })
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Total P/L In Rupees",
    //       dataIndex: "netWeight",
    //       sorter: (a, b) => {
    //         const exchangeRate = 85;
    //         const getTotalPLInRupees = (record) => {
    //           const details = record.products?.flatMap(product => product.details) || [];
    //           return details.reduce((sum, detail) => {
    //             const qtyUOMId = UnitsOfWeightInput.find(e => e.value === detail.qtyUOM)?.name === 'lb' ||
    //                             UnitsOfWeightInput.find(e => e.value === detail.qtyUOM)?.name === 'oz'
    //               ? UnitsOfWeightInput.find(e => e.name === 'lb').value
    //               : UnitsOfWeightInput.find(e => e.name === 'kg').value;
    //             const priceUOM = detail.priceUOM || qtyUOMId;
    //             let weight = parseFloat(detail.netWeight || 0);
      
    //             if (qtyUOMId !== priceUOM) {
    //               if (priceUOM === UnitsOfWeightInput.find(e => e.name === 'lb').value) {
    //                 weight = weight / 0.454; // kg to lb
    //               } else {
    //                 weight = weight * 0.454; // lb to kg
    //               }
    //             }
      
    //             const finalPL = parseFloat(detail.finalProfitLoss || 0);
    //             return sum + (weight * finalPL * exchangeRate);
    //           }, 0);
    //         };
    //         return getTotalPLInRupees(a) - getTotalPLInRupees(b);
    //       },
    //       sortDirections: ["ascend", "descend"],
    //       render: (text, record) => {
    //         const exchangeRate = 85;
    //         if (record.products && record.products.length > 0) {
    //           return record.products.map((product, groupIndex) =>
    //             product.details.map((item, index) => {
    //               const qtyUOMId = UnitsOfWeightInput.find(e => e.value === item.qtyUOM)?.name === 'lb' ||
    //                               UnitsOfWeightInput.find(e => e.value === item.qtyUOM)?.name === 'oz'
    //                 ? UnitsOfWeightInput.find(e => e.name === 'lb').value
    //                 : UnitsOfWeightInput.find(e => e.name === 'kg').value;
    //               const priceUOM = item.priceUOM || qtyUOMId;
    //               let weight = parseFloat(item.netWeight || 0);
      
    //               if (qtyUOMId !== priceUOM) {
    //                 if (priceUOM === UnitsOfWeightInput.find(e => e.name === 'lb').value) {
    //                   weight = weight / 0.454; // kg to lb
    //                 } else {
    //                   weight = weight * 0.454; // lb to kg
    //                 }
    //               }
      
    //               const finalPL = parseFloat(item.finalProfitLoss || 0);
    //               const totalPLInRupees = weight * finalPL * exchangeRate;
      
    //               const formattedValue = new Intl.NumberFormat("en-IN", {
    //                 minimumFractionDigits: 2,
    //                 maximumFractionDigits: 2
    //               }).format(totalPLInRupees);
      
    //               return <div key={`${groupIndex}-${index}`}>{formattedValue}</div>;
    //             })
    //           );
    //         }
    //         return null;
    //       }
    //     },
    //     {
    //       title: "Status",
    //       dataIndex: "enqStatus",
    //       render: (text) => {
    //         const enqStatus = text || "-";
    //         return <>{enqStatus}</>;
    //       },
    //       filters: enquiryStatusFilters,
    //       onFilter: (value, record) => record.enqStatus === value
    //     },
    //     {
    //       title: "Rejected Reason",
    //       dataIndex: "reasonName",
    //       sorter: (a, b) => (a.reasonName || "").localeCompare(b.reasonName || ""),
    //       sortDirections: ['descend', 'ascend'],
    //       ...getColumnSearchProps('reasonName'),
    //       render: (text, record) => (record.reasonName ? record.reasonName : "-"),
    //     },
    //     {
    //       title: "Rejected Description",
    //       dataIndex: "rejectedDescription",
    //       sorter: (a, b) => (a.rejectedDescription || "").localeCompare(b.rejectedDescription || ""),
    //       sortDirections: ['descend', 'ascend'],
    //       ...getColumnSearchProps('rejectedDescription'),
    //       render: (text, record) => (
    //         record.rejectedDescription ? (
    //           <Tooltip title={record.rejectedDescription}>
    //             {record.rejectedDescription.length > 50
    //               ? `${record.rejectedDescription.substring(0, 50)}...`
    //               : record.rejectedDescription}
    //           </Tooltip>
    //         ) : "-"
    //       ),
    //     }
    //   ];

    let rowIndex = 1


    const exportExcel = () => {
        let totalContainers = 0;
        let totalCases = 0;
        let totalNetWeight = 0;
        let totalNetAmount = 0;
        let totalPLAmount = 0;
        let totalPLAmountInInr = 0;
      
        const exchangeRate = 85;
        const exportData = [];
      
        enquiryReport.forEach((item, index) => {
          const { enquiryNumber, enqDate, sourceFrom, country, enqStatus, reasonName, rejectedDescription,buyerName,agentName,salePerson } = item;
      
          item.products.forEach((group, groupIndex) => {
            group.details.forEach((detail, detailIndex) => {
              const noOfContainers = Number(detail.noOfContainers) || 0;
              const noOfCases = Number(detail.cases) || 0;
              const netWeight = Number(detail.netShrimpWeight) || 0;
              const netAmount = Number(detail.netAmount) || 0;
              const finalProfitLoss = Number(detail.finalProfitLoss) || 0;
      
              const qtyUOMId = UnitsOfWeightInput.find(e => e.value === detail.qtyUOM)?.name === 'lb' ||
                               UnitsOfWeightInput.find(e => e.value === detail.qtyUOM)?.name === 'oz'
                ? UnitsOfWeightInput.find(e => e.name === 'lb').value
                : UnitsOfWeightInput.find(e => e.name === 'kg').value;
              const priceUOM = detail.priceUOM || qtyUOMId;
              let weight = parseFloat(detail.netWeight || 0);
      
              if (qtyUOMId !== priceUOM) {
                if (priceUOM === UnitsOfWeightInput.find(e => e.name === 'lb').value) {
                  weight = weight / 0.454;
                } else {
                  weight = weight * 0.454;
                }
              }
      
              const finalProfitLossInInr = weight * finalProfitLoss * exchangeRate;
      
              totalContainers += noOfContainers;
              totalCases += noOfCases;
              totalNetWeight += netWeight;
              totalNetAmount += netAmount;
              totalPLAmount += finalProfitLoss;
              totalPLAmountInInr += finalProfitLossInInr;
      
              exportData.push({
                'S No': groupIndex === 0 && detailIndex === 0 ? index + 1 : '',
                'Enquiry Number': enquiryNumber || '-',
                'Enquiry Date': enqDate ? moment(enqDate).format("DD-MM-YYYY") : '-',
                'Source From': sourceFrom || '-',
                'Buyer':buyerName || '-',
                'Agent': agentName || '-',
                'Sale Person': salePerson || '-',
                'Country': country || '-',
                'Order Type': detail.orderType || '-',
                'Category': detail.category || '-',
                'Product': detail.shortCode || '-',
                'Brand': detail.brandName || '-',
                'Pack Style': detail.packStyle || '-',
                'UOM': detail.uom || '-',
                'No Of Containers': noOfContainers,
                'No. Of Cases': noOfCases,
                'Net Weight': netWeight,
                'Net Amount': netAmount,
                'Total P/L Amount': finalProfitLoss,
                'Total P/L Amount In Rupees': finalProfitLossInInr,
                'EnqStatus': enqStatus || '-',
                'Status': enqStatus === "CLOSED" ? "Order Confirmed" : "Order Not Confirmed",
                'Rejected Reason': reasonName || '-',
                'Rejected Description': rejectedDescription || '-'
              });
            });
          });
        });
      
        exportData.push({
          'S No': '',
          'Enquiry Number': 'Total',
          'Enquiry Date': '',
          'Source From': '',
          'Buyer': '',
          'Agent': '',
          'Sale Person': '',
          'Country': '',
          'Order Type': '',
          'Category': '',
          'Product': '',
          'Brand': '',
          'Pack Style': '',
          'UOM': '',
          'No Of Containers': totalContainers,
          'No. Of Cases': totalCases,
          'Net Weight': totalNetWeight,
          'Net Amount': totalNetAmount,
          'Total P/L Amount': totalPLAmount,
          'Total P/L Amount In Rupees': totalPLAmountInInr,
          'EnqStatus': '',
           'Status': '',
          'Rejected Reason': '',
          'Rejected Description': ''
        });
      
        const headers = [
          'S No',
          'Enquiry Number',
          'Enquiry Date',
          'Source From',
          'Buyer',
          'Agent',
          'Sale Person',
          'Country',
          'Order Type',
          'Category',
          'Product',
          'Brand',
          'Pack Style',
          'UOM',
          'No Of Containers',
          'No. Of Cases',
          'Net Weight',
          'Net Amount',
          'Total P/L Amount',
          'Total P/L Amount In Rupees',
          'EnqStatus',
           'Status',
          'Rejected Reason',
          'Rejected Description'
        ];
      
        const worksheet = XLSX.utils.json_to_sheet(exportData, { header: headers });
        const range = XLSX.utils.decode_range(worksheet['!ref']);
      
        worksheet['!cols'] = headers.map(header => ({
          wch: Math.max(
            header.length,
            ...exportData.map(row => row[header]?.toString().length || 0)
          ) + 2
        }));
      
        for (let R = range.s.r; R <= range.e.r; ++R) {
          for (let C = range.s.c; C <= range.e.c; ++C) {
            const cellAddress = XLSX.utils.encode_cell({ r: R, c: C });
            const cell = worksheet[cellAddress];
            if (cell) {
              cell.s = {
                border: {
                  top: { style: "thin" },
                  bottom: { style: "thin" },
                  left: { style: "thin" },
                  right: { style: "thin" }
                }
              };
            }
          }
        }
      
        const mergeRanges = [];
        let currentRow = 1;
      
        enquiryReport.forEach(item => {
          const rowSpan = item.products.reduce((sum, group) => sum + group.details.length, 0);
          if (rowSpan > 1) {
            const mergeColumns = [
              'S No',
              'Enquiry Number',
              'Enquiry Date',
              'Source From',
              'Buyer',
              'Agent',
              'Sale Person',
              'Country',
              'Status',
              'Rejected Reason',
              'Rejected Description'
            ];
            mergeColumns.forEach(col => {
              const colIndex = headers.indexOf(col);
              if (colIndex !== -1) {
                mergeRanges.push({
                  s: { r: currentRow, c: colIndex },
                  e: { r: currentRow + rowSpan - 1, c: colIndex }
                });
              }
            });
          }
          currentRow += rowSpan;
        });
      
        worksheet['!merges'] = mergeRanges;
      
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Enquiry Report");
      
        const excelBuffer = XLSX.write(workbook, {
          bookType: 'xlsx',
          type: 'array',
          cellStyles: true
        });
      
        const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
        saveAs(blob, "enquiry-report.xlsx");
      };
    
    
      
      
    

  return (
    <div>
              <Card title={<span style={{ color: 'white' }}>Enquiry Management Report</span>}
                  style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
                  extra={<Button onClick={() => { exportExcel(); } }>Get Excel</Button>}>
                  <Form form={form} onFinish={getData} layout='vertical'>
                      <Row gutter={18}>
                          <Col xs={{ span: 12 }} sm={{ span: 12 }} md={{ span: 4 }} lg={{ span: 8 }} xl={{ span: 5 }}>
                              <Form.Item label="Enquiry Number" name="enquiryNumber">
                                  <Select
                                      showSearch
                                      optionFilterProp="children"
                                      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                      placeholder="Select  Enquiry Number"
                                      allowClear
                                  >
                                      {enquiryNumbers.map(dropData => {
                                          return <Option value={dropData.enquiryId}>{dropData.enquiryNumber}</Option>;
                                      })}
                                  </Select>
                              </Form.Item>
                          </Col>
                          <Col>
                              <Form.Item label="Enquiry Date" name="enquiryDate">

                                  <RangePicker />
                              </Form.Item>
                          </Col>
                        <Col span={3}>
                            <Form.Item
                                name="country"
                                label="Country"
                                rules={[
                                    {
                                        required: false,
                                    },
                                ]}
                            >
                                <Select
                                    placeholder="Select Country"
                                    allowClear
                                    showSearch
                                    optionFilterProp="children"
                                    filterOption={(input, option) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    } 
                                >
                                    {countriesData.map(countryDropData => {
                                        return <Option key={countryDropData.countryId} value={countryDropData.countryId} name={countryDropData.countryName}>{countryDropData.countryName}</Option>
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Form.Item
                                name="product"
                                label="Product"
                                rules={[
                                    {
                                        required: false,
                                    },
                                ]}
                            >
                                <Select
                                    placeholder="Select Product"
                                    allowClear
                                    showSearch
                                    optionFilterProp="children"
                                    filterOption={(input, option) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    } 
                                >
                                    {productsData.map(productDropData => {
                                        return <Option key={productDropData.skuCodeId} value={productDropData.skuCodeId} name={productDropData.shortCode}>{productDropData.shortCode}</Option>
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col xs={{ span: 12 }} sm={{ span: 12 }} md={{ span: 4 }} lg={{ span: 8 }} xl={{ span: 5 }}>
                              <Form.Item label="Buyer" name="buyerId">
                                  <Select
                                      showSearch
                                      optionFilterProp="children"
                                      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                      placeholder="Select  Buyer"
                                      allowClear
                                  >
                                      {buyerName.map(dropData => {
                                          return <Option value={dropData.buyerId}>{dropData.buyerName}</Option>;
                                      })}
                                  </Select>
                              </Form.Item>
                          </Col>
                          <Col xs={{ span: 12 }} sm={{ span: 12 }} md={{ span: 4 }} lg={{ span: 8 }} xl={{ span: 5 }}>
                              <Form.Item label="Agent" name="agentId">
                                  <Select
                                      showSearch
                                      optionFilterProp="children"
                                      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                      placeholder="Select  Agent"
                                      allowClear
                                  >
                                      {agentNames.map(dropData => {
                                          return <Option value={dropData.agentId}>{dropData.agentName}</Option>;
                                      })}
                                  </Select>
                              </Form.Item>
                          </Col>
                          <Col xs={{ span: 12 }} sm={{ span: 12 }} md={{ span: 4 }} lg={{ span: 8 }} xl={{ span: 5 }}>
                              <Form.Item label="Sale Person" name="salePersonId">
                                  <Select
                                      showSearch
                                      optionFilterProp="children"
                                      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                      placeholder="Select  Sale Person"
                                      allowClear
                                  >
                                      {salePersonName.map(dropData => {
                                          return <Option value={dropData.salePersonId}>{dropData.salePerson}</Option>;
                                      })}
                                  </Select>
                              </Form.Item>
                          </Col>
                          <Col style={{ paddingLeft: '10px', marginTop: '30px' }}>
                              <Form.Item>
                                  <Button
                                      type="primary"
                                      htmlType="submit"

                                  >
                                      Get Report
                                  </Button>
                              </Form.Item>
                          </Col>
                          <Col style={{ paddingLeft: '10px', marginTop: '30px' }}>
                              <Form.Item>
                                  <Button
                                      type="primary"
                                      onClick={onReset}
                                  >
                                      Reset
                                  </Button>
                              </Form.Item>
                          </Col>
                      </Row>
                  </Form>
                  {isVisible && (
                      <>
                     <Row gutter={16} style={{ height: '45px' }}>
    <Col span={4}>
      <Tag color="#bfbfbf" style={{ display: 'flex', color: 'black', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px' }}>
        Total Enquiries: {enquiryReport.length}
      </Tag>
    </Col>
    <Col span={4}>
      <Tag color="#51895d" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px' }}>
        Order Confirmed: {enquiryReport.filter(el => el.enqStatus === "CLOSED").length}
      </Tag>
    </Col>
    <Col span={5}>
      <Tag color="#d95c5c" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px' }}>
        Order Not Confirmed: {enquiryReport.filter(el => el.enqStatus !== "CLOSED").length}
      </Tag>
    </Col>
  </Row>
                      {/* <Row gutter={16}>
                      <Col span={5}>
                          <Tag color="#c0c46b" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px' }}>
                              Cancelled After Acceptance: {enquiryReport.filter(el => el.enqStatus === "CANCELLED AFTER ACCEPTANCE").length}
                          </Tag>
                      </Col>
                  </Row> */}
                  </>)}<br />
                  {isVisible && (
                    
                      <Table columns={Columns} dataSource={enquiryReport} pagination={{
                          pageSize: 100,
                          onChange(current, pageSize) {
                              setPage(current);
                          }
                      }} scroll={{ x: 'max-content' }}
                          summary={(pageData) => {
                              let totalContainers = 0;
                              let totalCases = 0;
                              let totalWeight = 0;
                              let totalNetAmount = 0;
                              let totalPL = 0
                              let totalPLInr = 0
                              pageData.forEach(({ products }) => {
                                if (products && products.length > 0) {
                                    products.forEach((product) => {
                                        if (product.details) {
                                            product.details.forEach((item) => {
                                                totalContainers += parseFloat(item.noOfContainers) || 0;
                                                totalCases += parseFloat(item.cases) || 0;
                                                totalWeight += parseFloat(item.caseWeight) || 0;
                                                totalNetAmount += parseFloat(item.netAmount) || 0;
                                                totalPL += parseFloat(item.finalProfitLoss) || 0;
                            
                                                const finalPL = parseFloat(item.finalProfitLoss);
                                                const netWeight = parseFloat(item.netWeight);
                                                if (!isNaN(finalPL) && !isNaN(netWeight)) {
                                                    totalPLInr += finalPL * netWeight * 85;
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                            

                              return (
                                  <Table.Summary.Row>
                                      <Table.Summary.Cell index={8} colSpan={9}>
                                          Total
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={9}>
                                          {totalContainers.toFixed(2)}
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={10}></Table.Summary.Cell>
                                      <Table.Summary.Cell index={11}></Table.Summary.Cell>
                                      <Table.Summary.Cell index={12}></Table.Summary.Cell>
                                      <Table.Summary.Cell index={13}>
                                          {totalCases.toFixed(2)}
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={12}></Table.Summary.Cell>

                                      <Table.Summary.Cell index={15}>
                                          {totalWeight.toFixed(2)}
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={16}>
                                          {totalNetAmount.toFixed(2)}
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={17}>
                                          {totalPL.toFixed(2)}
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={17}>
                                          {totalPLInr.toFixed(2)}
                                      </Table.Summary.Cell>
                                  </Table.Summary.Row>
                              );
                          } } />
                  )}


              </Card>
          </div>
  )
}

export default EnquiryCompleteManagementReport