/* eslint-disable react/jsx-no-useless-fragment */
import { Button, Card, Col, DatePicker, Form, Input, message, Modal, Row, Select, Table, Tooltip, Typography } from "antd";
import { useEffect, useRef, useState } from "react";
import React from "react";
import { SearchOutlined,UndoOutlined,DownloadOutlined} from "@ant-design/icons";
import Highlighter from "react-highlight-words";
import moment from "moment";
import { ProdlogService } from "@gtpl/shared-services/production";
import { BillNumberRequest } from "@gtpl/shared-models/production-management";
import { Excel } from "antd-table-saveas-excel";
import { OperationTypeDropDownEnum, OperationTypeEnum } from "@gtpl/shared-models/common-models";
import { UnitcodeService } from "@gtpl/shared-services/masters";
import { PlantsDropDown } from "@gtpl/shared-models/masters";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";




export const  BeheadingBillGrid = () => {

    const searchInput = useRef(null);
    const [billInfoData, setBillInfoData] = useState<any>([]);
    const [billTotalData, setBillTotalData] = useState<any>([]);

    const [billNoData, setBillNoData] = useState<any>([]);
    const [contractorData, setContractorData] = useState<any>([]);


    const [page, setPage] = React.useState(1);
    const [pageSize, setPageSize] = useState(1);
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const [showFilter, setShowFilter] = useState<boolean>(false);
    const [operation, setOperation] = useState('');
     const unitsService = new UnitcodeService();
    const [plantData, setPlantData] = useState<PlantsDropDown[]>([]);
     const [unitId, setUnitId] = useState<number>(0);


    

    const [form] = Form.useForm();
    const service = new ProdlogService()
    const { Option } = Select;
    
    const { Text } = Typography;
    const { RangePicker } = DatePicker;




    useEffect(() => {
          getAllPlants()
           if (Number(localStorage.getItem('unit_id')) != 5) {
      form.setFieldsValue({ unitId: Number(localStorage.getItem('unit_id')) })
  }
    }, [])
    

    const handleUnit = (value) => {
  setUnitId(value)
}


     const getAllPlants = () => {
        unitsService.getAllMainPlants().then((res) => {
            if (res.status) {
                setPlantData(res.data);
            } else {
                setPlantData([]);
            }
        }).catch(err => {
            AlertMessages.getErrorMessage(err.message);
            setPlantData([]);
        })
    }

    const getBillInfoByBillNumber = () => {
        const req = new BillNumberRequest(undefined,undefined); 

        if (form.getFieldValue("billNo") !== undefined) {
            req.billNumber = form.getFieldValue("billNo");
        }

        if (form.getFieldValue("contractorId") !== undefined) {
            req.contractorId = form.getFieldValue("contractorId");
         }

         if (form.getFieldValue("operation") !== undefined) {
            req.operation = form.getFieldValue("operation");
        }
        if (form.getFieldValue('date') !== undefined) {
          req.fromDate = (form.getFieldValue('date')[0]).format('YYYY-MM-DD');
        }
        if (form.getFieldValue('date') !== undefined) {
          req.toDate = (form.getFieldValue('date')[1]).format('YYYY-MM-DD');
        }

        if (form.getFieldValue("unitId") !== undefined) {
            req.unitId = form.getFieldValue("unitId");
         }

        service.getBillInfoByBillNumber(req).then(res => {
        if(res.status){
            setBillInfoData(res.data)
            setBillTotalData(res.data1)
            setShowFilter(true)
            

        }
        else{
            setBillInfoData([]);
            setBillTotalData([])

            message.error(res.internalMessage);
        }
        }).catch((err) => {
            console.log(err.message);
          })
    }

    const handleChange = (value) => {   
      getDistinctBillNumber(value);
      getDistinctContractorName(value); 
      setOperation(value)    
  };


    const getDistinctBillNumber = (value) => {
      console.log(value,"dist")
      
      const req = new BillNumberRequest(undefined,value,undefined); 

        service.getDistinctBillNumber(req).then(res => {
        if(res.status){
            setBillNoData(res.data)
        }
        else{
            setBillNoData([]);
            // message.error(res.internalMessage);
        }
        }).catch((err) => {
            console.log(err.message);
          })
    }

    const getDistinctContractorName = (value) => {
      const req = new BillNumberRequest(undefined,value,undefined); 
        service.getDistinctContractorName(req).then(res => {
        if(res.status){
            setContractorData(res.data)
        }
        else{
            setContractorData([]);
            // message.error(res.internalMessage);
        }
        }).catch((err) => {
            console.log(err.message);
          })
    }

    const onReset = () => {
        form.resetFields()
         setBillInfoData([])

    }

    const handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };
    const 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 size="small" style={{ width: 90 }}
                    onClick={() => {
                        handleReset(clearFilters)
                        setSearchedColumn(dataIndex);
                        confirm({ closeDropdown: true });
                    }}>
                    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 columns: any = [
        {
            title: "S.No",
            key: "sno",
            width: 50,
            render: (text, object, index) => (page - 1) * pageSize + (index + 1),
            fixed: 'left'
        },
        {
          title: 'Operation',
          dataIndex: 'operation',
          width: 120,
          sorter: (a, b) => {
              const operationA = a.operation || '';  // Handle null/undefined by treating them as empty strings
              const operationB = b.operation || '';
              return operationA.localeCompare(operationB);
            },
            sortDirections: ["ascend", "descend"],
          // ...getColumnSearchProps('operation'),
          render: (text, record) => {
              return record.operation ? record.operation : '-'
          },
      },
        {
            title: 'Bill NO',
            dataIndex: 'billNo',
            width: 100,
            sorter: (a, b) => {
                const billNoA = a.billNo || '';  // Handle null/undefined by treating them as empty strings
                const billNoB = b.billNo || '';
                return billNoA.localeCompare(billNoB);
              },
              sortDirections: ["ascend", "descend"],
            // ...getColumnSearchProps('billNo'),
            render: (text, record) => {
                return record.billNo ? record.billNo : '-'
            },
        },
        {
            title: 'Date',
            dataIndex: 'date',
            width: 90,
            sorter: (a, b) => {
                const dateA = a.date || '';  // Handle null/undefined by treating them as empty strings
                const dateB = b.date || '';
                return dateA.localeCompare(dateB);
              },
              sortDirections: ["ascend", "descend"],
            render: (text, record) => {
                return (record.date ? (moment(record.date).format('DD-MM-YYYY')) : '-')
            },
        },
        {
            title: 'Source Code',
            dataIndex: 'lotNumber',
            width: 110,
            sorter: (a, b) => {
                const lotNumberA = a.lotNumber || '';  // Handle null/undefined by treating them as empty strings
                const lotNumberB = b.lotNumber || '';
                return lotNumberA.localeCompare(lotNumberB);
              },
              sortDirections: ["ascend", "descend"],
            ...getColumnSearchProps('lotNumber')
        },
        {
            title: 'Contractor',
            dataIndex: 'contractorName',
            align: 'center',
            width: 120,
            sorter: (a, b) => {
                const contractorNameA = a.contractorName || '';  // Handle null/undefined by treating them as empty strings
                const contractorNameB = b.contractorName || '';
                return contractorNameA.localeCompare(contractorNameB);
              },
              sortDirections: ["ascend", "descend"],
            render: (text, record) => {
              return record.contractorName ? record.contractorName : '-'
          },
        },
        {
            title: 'Grade',
            dataIndex: 'HONcount',
            align: 'center',
            width: 90,
            sorter: (a, b) => a.HONcount.localeCompare(b.HONcount),
            sortDirections: ["ascend", "descend"],
            render: (text, record) => {
              return record.HONcount ? record.HONcoun : '-'
          },
          ...getColumnSearchProps('HONcount')

        },
        {
            title: 'Variety',
            dataIndex: 'product',
            align: 'center',
            width: 90,
            sorter: (a, b) => {
              const productA = a.product || '';  // Handle null/undefined by treating them as empty strings
              const productB = b.product || '';
              return productA.localeCompare(productB);
            },
            sortDirections: ["ascend", "descend"],
            render: (text, record) => {
              return record.product ? record.product : '-';  // Display '-' if no product value
            },
          },
          
        {
            title: 'Rate',
            dataIndex: 'unitPrice',
            align: 'center',
            width: 90,
            sorter: (a, b) => {
                const unitPriceA = a.unitPrice || '';  // Handle null/undefined by treating them as empty strings
                const unitPriceB = b.unitPrice || '';
                return unitPriceA.localeCompare(unitPriceB);
              },
              sortDirections: ["ascend", "descend"],
            render: (text, record) => {
              return record.unitPrice ? record.unitPrice: '-'
          },
        },
       {
              title: 'Quantity',
              dataIndex: 'opQty',
              align: 'center',
              width: 120,
              sorter: (a, b) => {
                // Convert quantities to numbers for proper sorting, and handle cases where opQty or ipQty are null/undefined
                const opQtyA = a.opQty ? Number(a.opQty) : 0;
                const opQtyB = b.opQty ? Number(b.opQty) : 0;
                return opQtyA - opQtyB;
              },
              sortDirections: ["ascend", "descend"],
              render: (text, record) => {
                let qtyToRender;

                // Check operation type and assign the appropriate quantity
                if (record.operation === "DEHEADING" || record.operation === "GRADING") {
                  qtyToRender = record.opQty === "0.000" ? 0 : (record.opQty || '-');
                } else if (record.operation === "VALUE ADDITION" || record.operation === "GRN") {
                  qtyToRender = record.ipQty === "0.000" ? 0 : (record.ipQty || '-');
                } else if (record.operation === "SOAKING") {
                  qtyToRender = record.inQty === "0.000" ? 0 : (record.inQty || '-');
                } else {
                  // Default case
                  qtyToRender = '-';
                }

                return qtyToRender;
              },
            },

          
        {
            title: 'Amount',
            dataIndex: 'amount',
            align: 'center',
            width: 120,
            sorter: (a, b) => {
                const amountA = a.amount || '';  // Handle null/undefined by treating them as empty strings
                const amountB = b.amount || '';
                return amountA.localeCompare(amountB);
              },
              sortDirections: ["ascend", "descend"],
            render: (text, record) => {
              return record.amount ? record.amount : '-'
          },

        },
        {
          title: 'No of Workers',
          dataIndex: 'noOfWorkers',
          align: 'center',
          width: 90,
          sorter: (a, b) => {
              const noOfWorkersA = a.noOfWorkers || '';  // Handle null/undefined by treating them as empty strings
              const noOfWorkersB = b.noOfWorkers || '';
              return noOfWorkersA.localeCompare(noOfWorkersB);
            },
            sortDirections: ["ascend", "descend"],
          render: (text, record) => {
            return record.noOfWorkers ? record.noOfWorkers : '-'
        },

      },
      

    ]

    console.log(operation ,"poiu")

  

   { operation === "VALUE ADDITION" && (
      columns.push(
      {
        title: 'Peeling Price Based On',
        dataIndex: 'peelingPriceBasedOn',
        align: 'center',
        width: 130,
        sorter: (a, b) => {
            const peelingPriceBasedOnA = a.peelingPriceBasedOn || '';  // Handle null/undefined by treating them as empty strings
            const peelingPriceBasedOnB = b.peelingPriceBasedOn || '';
            return peelingPriceBasedOnA.localeCompare(peelingPriceBasedOnB);
          },
          sortDirections: ["ascend", "descend"],
        render: (text, record) => {
          return record.peelingPriceBasedOn ? record.peelingPriceBasedOn : '-'
      },

    },
    {
      title: 'Output Quantity',
      dataIndex: 'outputQty',
      width: 130,
      render: (text, record) => {
        return record.outputQty ? Number(record.outputQty) : '-'
    },

  }
  )

  )}

    // const handleExport = (e: any) => {
    //     e.preventDefault();


    //     const currentDate = new Date()
    //         .toISOString()
    //         .slice(0, 10)
    //         .split("-")
    //         .join("/");

    //     let rowIndex = 1;
    //     let exportingColumns: any[] = []
    //     exportingColumns.push(
    //         {
    //             title: "S.No",
    //             // dataIndex: "sno", 
    //             width: 50,
    //             render: (text, object, index) => {
    //                 if (index == billInfoData.length) {
    //                     return null;
    //                 } else {
    //                     return rowIndex++;
    //                 }
    //             }
    //         },
    //         {
    //             title: 'Bill NO',
    //             dataIndex: 'billNo',
    //             render: (text, record) => {
    //                 return record.billNo ? record.billNo : '-'
    //             },
    //         },
    //         {
    //             title: 'Date',
    //             dataIndex: 'date',
    //             render: (text, record) => {
    //                 return (record.date ? (moment(record.date).format('DD-MM-YYYY')) : '-')
    //             },
    //         },
    //         {
    //             title: 'Source Code',
    //             dataIndex: 'lotNumber',
    //         },
    //         {
    //             title: 'Contractor',
    //             dataIndex: 'contractorName',
    //             render: (text, record) => {
    //               return record.contractorName ? record.contractorName : '-'
    //           },
    //         },
    //         {
    //             title: 'Grade',
    //             dataIndex: 'HONcount',
    //             render: (text, record) => {
    //               return record.HONcount ? record.HONcoun : '-'
    //           },
    //           ...getColumnSearchProps('HONcount')
    
    //         },
    //         {
    //             title: 'Variety',
    //             dataIndex: 'product',
    //             render: (text, record) => {
    //               return record.product ? record.product : '-';  // Display '-' if no product value
    //             },
    //           },
              
    //         {
    //             title: 'Rate',
    //             dataIndex: 'unitPrice',
    //             align: 'center',
    //             render: (text, record) => {
    //               return record.unitPrice ? record.unitPrice: '-'
    //           },
    //         },
    //         {
    //             title: 'Quantity',
    //             dataIndex: 'opQty',
    //             render: (text, record) => {
    //               return record.opQty ? record.opQty : '-';
    //             },
    //           },
              
    //         {
    //             title: 'Amount',
    //             dataIndex: 'amount',
    //             render: (text, record) => {
    //               return record.amount ? record.amount : '-'
    //           },
    //         }
           
    //     )

    //     const excel = new Excel();
    //     excel.addSheet("Sheet1");
    //     excel.addColumns(exportingColumns);
    //     excel.addDataSource(billInfoData);
    //     excel.saveAs(`Deheading-Bill-info-${currentDate}.xlsx`);
    // }
  //   const handleExport = (e: any) => {
  //     e.preventDefault();
  
  //     const currentDate = new Date()
  //         .toISOString()
  //         .slice(0, 10)
  //         .split("-")
  //         .join("/");
  
  //     let rowIndex = 1;
  //     let exportingColumns: any[] = []
  //     exportingColumns.push(
  //         {
  //             title: "S.No",
  //             width: 50,
  //             render: (text, object, index) => {
  //                 if (index == billInfoData.length) {
  //                     return null;
  //                 } else {
  //                     return rowIndex++;
  //                 }
  //             }
  //         },
  //         {
  //           title: 'Operation',
  //           dataIndex: 'operation',
  //           render: (text, record) => {
  //               return record.operation ? record.operation : '-'
  //           },
  //       },
  //         {
  //             title: 'Bill NO',
  //             dataIndex: 'billNo',
  //             render: (text, record) => {
  //                 return record.billNo ? record.billNo : '-'
  //             },
  //         },
  //         {
  //             title: 'Date',
  //             dataIndex: 'date',
  //             render: (text, record) => {
  //                 return (record.date ? (moment(record.date).format('DD-MM-YYYY')) : '-')
  //             },
  //         },
  //         {
  //             title: 'Source Code',
  //             dataIndex: 'lotNumber',
  //         },
  //         {
  //             title: 'Contractor',
  //             dataIndex: 'contractorName',
  //             render: (text, record) => {
  //                 return record.contractorName ? record.contractorName : '-'
  //             },
  //         },
  //         {
  //             title: 'Grade',
  //             dataIndex: 'HONcount',
  //             render: (text, record) => {
  //                 return record.HONcount ? record.HONcount : '-'
  //             },
  //             ...getColumnSearchProps('HONcount')
  //         },
  //         {
  //             title: 'Variety',
  //             dataIndex: 'product',
  //             render: (text, record) => {
  //                 return record.product ? record.product : '-';
  //             },
  //         },
  //         {
  //             title: 'Rate',
  //             dataIndex: 'unitPrice',
  //             align: 'center',
  //             render: (text, record) => {
  //                 return record.unitPrice ? record.unitPrice : '-'
  //             },
  //         },
  //         {
  //           title: 'Quantity',
  //           dataIndex: 'quantity',
  //           key:"quantity",
  //           render: (text, record) => {
  //             if (record.billNo === 'Total') {
  //               // Display the total quantity in the summary row
  //               return record.quantity;
  //             }
        
  //             let qtyToRender;
  //             if (record.operation === "DEHEADING" || record.operation === "GRADING") {
  //               qtyToRender = record.opQty === "0.000" ? 0 : (record.opQty || '-');
  //             } else if (record.operation === "VALUE ADDITION" || record.operation === "GRN") {
  //               qtyToRender = record.ipQty === "0.000" ? 0 : (record.ipQty || '-');
  //             } else if (record.operation === "SOAKING") {
  //               qtyToRender = record.inQty === "0.000" ? 0 : (record.ipQty || '-');
  //             } else {
  //               qtyToRender = '-';
  //             }
  //             return qtyToRender;
  //           },
  //       },
  //         {
  //             title: 'Amount',
  //             dataIndex: 'amount',
  //             render: (text, record) => {
  //                 return record.amount ? record.amount : '-'
  //             },
  //         }
  //     );

  //     const totalQuantity = billInfoData.reduce((acc, record) => {
  //       let qtyToRender = 0;
      
  //       // Check operation type and assign the appropriate quantity for total calculation
  //       if (record.operation === "DEHEADING" || record.operation === "GRADING") {
  //         qtyToRender = record.opQty === "0.000" ? 0 : (Number(record.opQty) || 0);
  //       } else if (record.operation === "VALUE ADDITION" || record.operation === "GRN") {
  //         qtyToRender = record.ipQty === "0.000" ? 0 : (Number(record.ipQty) || 0);
  //       } else if (record.operation === "SOAKING") {
  //         qtyToRender = record.ipQty === "0.000" ? 0 : (Number(record.ipQty) || 0);
  //       }
      
  //       return acc + qtyToRender;
  //     }, 0);

  //     const totalAmount = billInfoData.reduce((acc, record) => acc + (Number(record.amount) || 0), 0);

  
      
  //     const summaryRow = {
  //       billNo: 'Total',
  //       // Ensure the right quantity field is shown in the summary row, depending on the operation type logic
  //       operation: '', // Leaving operation empty as it's a summary
  //       opQty: totalQuantity, // Keep this as it is used in the calculation
  //       amount: totalAmount,
  //       quantity: totalQuantity // Create a new key for the total quantity to match the column in Excel
  //   };
  
     
  //     const billInfoDataWithSummary = [...billInfoData, summaryRow];
  
  //     const excel = new Excel();
  //     excel.addSheet("Sheet1");
  //     excel.addColumns(exportingColumns);
  //     excel.addDataSource(billInfoDataWithSummary);
  //     excel.saveAs(`Deheading-Bill-info-${currentDate}.xlsx`);
  // };

  const handleExport = (e: any) => {
    e.preventDefault();

    const currentDate = new Date()
        .toISOString()
        .slice(0, 10)
        .split("-")
        .join("/");

    let rowIndex = 1;
    let exportingColumns: any[] = []
    exportingColumns.push(
        {
            title: "S.No",
            width: 50,
            render: (text, object, index) => {
                if (index == billInfoData.length) {
                    return null;
                } else {
                    return rowIndex++;
                }
            }
        },
        {
          title: 'Operation',
          dataIndex: 'operation',
          render: (text, record) => {
              return record.billNo === 'Total' ? '' : (record.operation || '-');
          },
        },
        {
            title: 'Bill NO',
            dataIndex: 'billNo',
            render: (text, record) => {
                return record.billNo === 'Total' ? '' : (record.billNo || '-');
            },
        },
        {
            title: 'Date',
            dataIndex: 'date',
            render: (text, record) => {
                return record.billNo === 'Total' ? '' : (record.date ? (moment(record.date).format('DD-MM-YYYY')) : '-');
            },
        },
        {
            title: 'Source Code',
            dataIndex: 'lotNumber',
        },
        {
            title: 'Contractor',
            dataIndex: 'contractorName',
            render: (text, record) => {
                return record.billNo === 'Total' ? '' : (record.contractorName || '-');
            },
        },
        {
            title: 'Grade',
            dataIndex: 'HONcount',
            render: (text, record) => {
                return record.HONcount  ? record.HONcount :"-" 
            },
        },
        {
            title: 'Variety',
            dataIndex: 'product',
            render: (text, record) => {
                return record.billNo === 'Total' ? '' : (record.product || '-');
            },
        },
        {
            title: 'Rate',
            dataIndex: 'unitPrice',
            align: 'center',
            render: (text, record) => {
                return record.billNo === 'Total' ? '' : (record.unitPrice || '-');
            },
        },
        {
          title: 'Quantity',
          dataIndex: 'quantity',
          key: "quantity",
          render: (text, record) => {
            if (record.billNo === 'Total') {
              return record.quantity;
            }

            let qtyToRender;

            if (record.operation === "DEHEADING" || record.operation === "GRADING") {
              qtyToRender = record.opQty === "0.000" ? 0 : (record.opQty || '-');
            } else if (record.operation === "VALUE ADDITION" || record.operation === "GRN") {
              qtyToRender = record.ipQty === "0.000" ? 0 : (record.ipQty || '-');
            } else if (record.operation === "SOAKING") {
              qtyToRender = record.inQty === "0.000" ? 0 : (record.ipQty || '-');
            } else {
              qtyToRender = '-';
            }
            return qtyToRender;
          },
        },
        {
            title: 'Amount',
            dataIndex: 'amount',
            render: (text, record) => {
                return record.billNo === 'Total' ? '' : (record.amount || '-');
            },
        },
        {
          title: 'No of Workers',
          dataIndex: 'noOfWorkers',
          render: (text, record) => {
            return record.noOfWorkers ? record.noOfWorkers : '-'
        },

      },

    );

    { operation === "VALUE ADDITION" && (
      exportingColumns.push(
      {
        title: 'Peeling Price Based On',
        dataIndex: 'peelingPriceBasedOn',
        width: 130,
        render: (text, record) => {
          return record.peelingPriceBasedOn ? Number(record.peelingPriceBasedOn) : '-'
      },

    },
    {
      title: 'Output Quantity',
      dataIndex: 'outputQty',
      width: 130,
      render: (text, record) => {
        return record.outputQty ? Number(record.outputQty) : '-'
    },

  }
  )

  )}


    const totalQuantity = billInfoData.reduce((acc, record) => {
        let qtyToRender = 0;

        if (record.operation === "DEHEADING" || record.operation === "GRADING") {
            qtyToRender = record.opQty === "0.000" ? 0 : (Number(record.opQty) || 0);
        } else if (record.operation === "VALUE ADDITION" || record.operation === "GRN") {
            qtyToRender = record.ipQty === "0.000" ? 0 : (Number(record.ipQty) || 0);
        } else if (record.operation === "SOAKING") {
            qtyToRender = record.ipQty === "0.000" ? 0 : (Number(record.ipQty) || 0);
        }

        return acc + qtyToRender;
    }, 0);

    const totalAmount = billInfoData.reduce((acc, record) => acc + (Number(record.amount) || 0), 0);
    const totalOutputQty = billInfoData.reduce((acc, record) => acc + (Number(record.outputQty) || 0), 0);


    const summaryRow = {
        billNo: 'Total',
        operation: '',
        opQty: totalQuantity,
        amount: totalAmount,
        quantity: totalQuantity,
        noOfWorkers:"",
        peelingPriceBasedOn:"",
        outputQty:totalOutputQty


    };

    const billInfoDataWithSummary = [...billInfoData, summaryRow];

    const excel = new Excel();
    excel.addSheet("Contractor-wise-Bill");
    excel.addColumns(exportingColumns);
    excel.addDataSource(billInfoDataWithSummary);
    excel.saveAs(`Contractor-Wise-Bill-info-${currentDate}.xlsx`);
};

  

    return (
        <>
          <Card title={<span style={{ color: 'white' }}>Contractor Wise Bill Info</span>}
      style={{ textAlign: 'center' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }} extra={billInfoData.length > 0 ? <Button
        onClick={handleExport}
        icon={<DownloadOutlined />}>Get Excel</Button> : null}>
          <Form
            onFinish={getBillInfoByBillNumber}
            form={form}
            layout='vertical'
          >
            <Row gutter={24}>
              <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
            <Form.Item
                name="unitId"
                label="Unit"
                rules={[
                    {
                        required: true, message: 'Select Unit',
                    },
                ]}
            >
                <Select
                    showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    placeholder="Select Unit"
                    allowClear
                    style={{ width: '100%' }}
                    onChange={handleUnit}
                    disabled={Number(localStorage.getItem('unit_id')) != 5 ? true : false}
                >
                    {plantData.map(dropData => {
                        return <Option value={dropData.plantId}>{dropData.plantCode}</Option>
                    })}
                </Select>
            </Form.Item>
        </Col>
            <Col
                xs={{ span: 24 }}
                sm={{ span: 24 }}
                md={{ span: 4 }}
                lg={{ span: 4 }}
                xl={{ span: 4 }}
              >
                <Form.Item name="operation" label="Operation" rules={[
                {
                  required: true,
                  message: 'Please Select Operation'
                }]}>
                <Select
                    showSearch
                    placeholder="Select Operation"
                    optionFilterProp="children"
                    allowClear
                    onChange={handleChange}
                    >
                    {Object.keys(OperationTypeDropDownEnum).map((inc: any) => {
                        const operation = OperationTypeDropDownEnum[inc]; // Get the actual value from the enum
                        return (
                        <Option key={operation} value={operation}>
                            {operation}
                        </Option>
                        );
                    })}
                    </Select>

                </Form.Item>
              </Col>

              <Col
                  xs={{ span: 24 }}
                  sm={{ span: 24 }}
                  md={{ span: 5 }}
                  lg={{ span: 5 }}
                  xl={{ span: 5 }}
                >
                  <Form.Item name="date"
                label="Date"
                rules={[
                  {
                    required: true,
                    message: 'Please Select Date'
                  }]}
                     >
                <RangePicker  allowClear />
              </Form.Item>
                </Col>
        {showFilter && (
              <>
                <Col
                  xs={{ span: 24 }}
                  sm={{ span: 24 }}
                  md={{ span: 4 }}
                  lg={{ span: 4 }}
                  xl={{ span: 3 }}
                >
                  <Form.Item name="billNo" label="Bill No">
                    <Select
                      showSearch
                      placeholder="Select Bill No"
                      optionFilterProp="children"
                      allowClear
                    >
                      {billNoData.map((inc: any) => (
                        <Option key={inc.bill_no} value={inc.bill_no}>
                          {inc.bill_no}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col
                  xs={{ span: 24 }}
                  sm={{ span: 24 }}
                  md={{ span: 4 }}
                  lg={{ span: 4 }}
                  xl={{ span: 3 }}
                >
                  <Form.Item name="contractorId" label="Contractor">
                    <Select
                      showSearch
                      placeholder="Select Contractor"
                      optionFilterProp="children"
                      allowClear
                    >
                      {contractorData.map((inc: any) => (
                        <Option key={inc.contractorId} value={inc.contractorId}>
                          {inc.contractorName}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                {/* <Col
                  xs={{ span: 24 }}
                  sm={{ span: 24 }}
                  md={{ span: 5 }}
                  lg={{ span: 5 }}
                  xl={{ span: 5 }}
                >
                  <Form.Item name="date"
                label="Date"
                     >
                <RangePicker  allowClear />
              </Form.Item>
                </Col> */}

                
              </>
            )}


               <Row>
              <Col
                xs={{ span: 24 }}
                sm={{ span: 24 }}
                md={{ span: 5 }}
                lg={{ span: 5 }}
                xl={{ span: 4 }}
                style={{marginTop:28,marginLeft:30}}
              >
                <Form.Item>
                  <Button
                    htmlType="submit"
                    icon={<SearchOutlined />}
                    type="primary"
                    // onClick={getPdfFileInfo}
                  >
                    Search
                  </Button>
                </Form.Item>
              </Col>
              <Col style={{ marginLeft: 70,marginTop:28}}>
                <Form.Item>
                  <Button
                    htmlType="reset"
                    onClick={onReset}
                    danger
                    icon={<UndoOutlined />}
                  >
                    Reset
                  </Button>
                </Form.Item>

              </Col>
            </Row>
            </Row>
            {/* <Table
              columns={columns}
              dataSource={billInfoData}
              bordered
              className="custom-table-wrapper"
              pagination={{
                pageSize: 50,
                onChange(current, pageSize) {
                  setPage(current);
                  setPageSize(pageSize);
                },
              }}
              scroll={{ x: 'max-content', y: 450 }}
          
            >

            </Table> */}
     {(billInfoData.length) ? <>
      <Table
  columns={columns}
  dataSource={billInfoData}
  bordered
  pagination={{
    pageSize: 100,
    onChange(current, pageSize) {
      setPage(current);
      setPageSize(pageSize);
    },
  }}
  scroll={{ x: 1500, y: 450 }}
  summary={() =>
    operation === "VALUE ADDITION" ? (
      <Table.Summary fixed>
        <Table.Summary.Row>
          <Table.Summary.Cell index={1} colSpan={9}>
            <strong>Total</strong>
          </Table.Summary.Cell>
          <Table.Summary.Cell index={6} align="center">
            <strong>{billTotalData[0]?.opQty}</strong>
          </Table.Summary.Cell>
          <Table.Summary.Cell index={7} align="center">
            <strong>{billTotalData[0]?.amount}</strong>
          </Table.Summary.Cell>
          <Table.Summary.Cell index={8} align="center"></Table.Summary.Cell>
          <Table.Summary.Cell index={9} align="center"></Table.Summary.Cell>
          <Table.Summary.Cell index={10} align="center">
            <strong>{billTotalData[0]?.meatBasedOpQty}</strong>
          </Table.Summary.Cell>
        </Table.Summary.Row>
      </Table.Summary>
    ) : (
      <Table.Summary fixed>
        <Table.Summary.Row>
          <Table.Summary.Cell index={5} colSpan={9}>
            <strong>Total</strong>
          </Table.Summary.Cell>
          <Table.Summary.Cell index={6} align="center">
            <strong>{billTotalData[0]?.opQty}</strong>
          </Table.Summary.Cell>
          <Table.Summary.Cell index={7} align="center">
            <strong>{billTotalData[0]?.amount}</strong>
          </Table.Summary.Cell>
        </Table.Summary.Row>
      </Table.Summary>
    )
  }
/>

    </> : <></>}

            </Form>
          </Card>
        </>
      );
      
}
export default BeheadingBillGrid