import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Tag, Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react'
import Highlighter from 'react-highlight-words';
import Table, { ColumnProps } from "antd/lib/table";

import { BarcodeOutlined, DownloadOutlined, SearchOutlined, UndoOutlined } from '@ant-design/icons';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { UomEnum } from '@gtpl/shared-models/common-models';
import moment from 'moment';
import { Excel } from 'antd-table-saveas-excel';
import { ShipmentDetailRequest } from '@gtpl/shared-models/warehouse-management';
import { PlantsDropDown } from '@gtpl/shared-models/masters';
import { UnitcodeService } from '@gtpl/shared-services/masters';
import { PurchasesProductService } from '@gtpl/shared-services/finance';
import { PortOfEntryInput } from '@gtpl/shared-models/sale-management';




const shippmentDetailsReport = () => {
    const [page, setPage] = React.useState(1);
    const [pageSize, setPageSize] = useState(100);
    const [filterData, setFilterData] = useState([]);
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const services = new SaleOrderService;
    const purchaseService = new PurchasesProductService()
    const[shipment,setShipment]=useState([])
    const[brand,setBrand] = useState([])
    const[invoiceNo,setInvoiceNo] = useState([])
    const[poNumber,setPoNumber]= useState([])
    const [plantData, setPlantData] = useState<PlantsDropDown[]>([]);
    const unitsService = new UnitcodeService();
    const [unitId, setUnitId] = useState<number>(0);
    const [factoriesData, setFactoriesData] = useState([]);
    const { Option } = Select;
    const saleService = new SaleOrderService();
    const [years,setYears] = useState<any[]>([])
    const { RangePicker } = DatePicker;


    const [form] = Form.useForm();
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 100,
    });



    useEffect(()=>{
        getActiveShippmentDetails()
        getCustomerPoForShipmentDetailReport()
        getInvoiceForShipmentDetailReport()
        getBrandForShipmentDetailReport()
        getAllPlants();
        getAllFinancialYear ();
        getAllCompanyNames();
    if (Number(localStorage.getItem('unit_id')) != 5) {
      form.setFieldsValue({ unitId: Number(localStorage.getItem('unit_id')) })
  }
    },[])
 

const getActiveShippmentDetails = () =>{
    const req = new ShipmentDetailRequest()

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

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

     if (form.getFieldValue("invoiceNumber") !== undefined) {
        req.invoiceNumber = form.getFieldValue("invoiceNumber");
      } 
      if (form.getFieldValue('invoiceDate') !== undefined) {
        req.fromDate = (form.getFieldValue('invoiceDate')[0]).format('YYYY-MM-DD');
      }
      if (form.getFieldValue('invoiceDate') !== undefined) {
        req.toDate = (form.getFieldValue('invoiceDate')[1]).format('YYYY-MM-DD');
      }
      if (form.getFieldValue("financialYear") !== undefined) {
        req.financialYear = form.getFieldValue("financialYear");
      } 
      if (form.getFieldValue('companyId') !== undefined) {
        req.companyId = form.getFieldValue('companyId')
      } 
      if (Number(localStorage.getItem('unit_id')) != 5) {
        req.unitId = Number(localStorage.getItem('unit_id'));
    } else {
        req.unitId = unitId
    }
    

 services.getShipmentDetailsReport(req).then((res) =>{
    if(res.status){
        setShipment(res.data);
    }else{
        if(res.intlCode){
            AlertMessages.getErrorMessage(res.internalMessage);

        }else{
            AlertMessages.getErrorMessage(res.internalMessage);
    
        }
        setShipment([]);
    }
 }
)
.catch((err)=>{
    AlertMessages.getErrorMessage(err.message);
setShipment([]);
});
}
const getAllPlants = () => {
    unitsService.getAllMainPlants().then((res) => {
        if (res.status) {
            setPlantData(res.data);
        } else {
            setPlantData([]);
        }
    }).catch(err => {
        AlertMessages.getErrorMessage(err.message);
        setPlantData([]);
    })
}
const getAllCompanyNames = () => {
    purchaseService.getAllCompanys().then((res) => {
        if (res.status) {
            setFactoriesData(res.data)
        }
    })
}
const handleUnit = (value) => {
  setUnitId(value)
}

const getCustomerPoForShipmentDetailReport =() =>{
    services.getCustomerPoForShipmentDetailReport({ unitId: Number(localStorage.getItem('unit_id')) }).then((res) =>{
       if(res.status){
           setPoNumber(res.data);
       }else{
           if(res.intlCode){
               AlertMessages.getErrorMessage(res.internalMessage);
   
           }else{
               AlertMessages.getErrorMessage(res.internalMessage);
       
           }
           setPoNumber([]);
       }
    }
   )
   .catch((err)=>{
       AlertMessages.getErrorMessage(err.message);
       setPoNumber([]);
   });
   }
   const getAllFinancialYear  = () => {
    saleService.getAllFinancialYear().then(res => {
      if (res.status) {
        setYears(res.data);
      } else {
        if (res.intlCode) {
          setYears([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setYears([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }
   const getBrandForShipmentDetailReport =() =>{
    services.getBrandForShipmentDetailReport({ unitId: Number(localStorage.getItem('unit_id')) }).then((res) =>{
       if(res.status){
           setBrand(res.data);
       }else{
           if(res.intlCode){
               AlertMessages.getErrorMessage(res.internalMessage);
   
           }else{
               AlertMessages.getErrorMessage(res.internalMessage);
       
           }
           setBrand([]);
       }
    }
   )
   .catch((err)=>{
       AlertMessages.getErrorMessage(err.message);
       setBrand([]);
   });
   }

   const getInvoiceForShipmentDetailReport =() =>{
    services.getInvoiceForShipmentDetailReport({ unitId: Number(localStorage.getItem('unit_id')) }).then((res) =>{
       if(res.status){
           setInvoiceNo(res.data);
       }else{
           if(res.intlCode){
               AlertMessages.getErrorMessage(res.internalMessage);
   
           }else{
               AlertMessages.getErrorMessage(res.internalMessage);
       
           }
           setInvoiceNo([]);
       }
    }
   )
   .catch((err)=>{
       AlertMessages.getErrorMessage(err.message);
       setInvoiceNo([]);
   });
   }

    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 handleTableChange = (pagination) => {
        setPagination(pagination);
    };
    useEffect(() => {
        setPage(1); 
    }, [shipment]);
    const tableColumn: ColumnProps<any>[] =[
        {
            title: 'S No',
            key: 'sno',
            width: 70,
            render: (text, object, index) => (page - 1) * pageSize + (index + 1),
          },
        {
            title: "Unit(Plant Code)",
            dataIndex: "unitName",
            width:"180px",
            sorter: (a, b) => a.unitName?.localeCompare(b.unitName),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('unitName')
      
        },
        {
            title: "Processing Unit",
            dataIndex: "processingUnit",
            width:"150px",
            sorter: (a, b) => a.processingUnit?.localeCompare(b.processingUnit),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('processingUnit')
      
        },
        {
            title: "Company",
            dataIndex: "companyName",
            width:"150px",
            sorter: (a, b) => a.companyName?.localeCompare(b.companyName),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('companyName')
      
        },
        {
            title : 'PO Number',
            key: 'poNumber',
            dataIndex: 'poNumber',
            ...getColumnSearchProps('poNumber'),
            sorter: (a, b) => a.poNumber?.localeCompare(b.poNumber),
            sortDirections: ['descend', 'ascend']
        },
        {
            title : 'PO Date',
            key: 'poDate',
            width:"130px",
            dataIndex: 'poDate',
            // ...getColumnSearchProps('poDate'),
            sorter: (a, b) => a.poDate?.localeCompare(b.poDate),
            sortDirections: ['descend', 'ascend'],
            render:(index,val) =>{

                return <span>{val.poDate?moment(val.poDate).format("DD-MM-YYYY"):'-'}</span>
    
            }

            
        },
        {
            title : 'Certification',
            key: 'certificate',
            width:"90px",
            dataIndex: 'certificate',
            ...getColumnSearchProps('certificate'),
            sorter: (a, b) => a.certificate?.localeCompare(b.certificate),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },
        {
            title : 'Invoice NO',
            key: 'invoiceNum',
            dataIndex: 'invoiceNum',
            ...getColumnSearchProps('invoiceNum'),
            sorter: (a, b) => a.invoiceNum?.localeCompare(b.invoiceNum),
            sortDirections: ['descend', 'ascend']
        },
        {
            title : 'Invoice Date',
            key: 'invoiceDate',
            dataIndex: 'invoiceDate',
            // ...getColumnSearchProps('invoiceDate'),
            sorter: (a, b) => a.invoiceDate?.localeCompare(b.invoiceDate),
            sortDirections: ['descend', 'ascend'],
            render:(index,val) =>{

                return <span>{val.invoiceDate?moment(val.invoiceDate).format("DD-MM-YYYY"):'-'}</span>
    
            }
        },
        {
            title : 'Consignee Name',
            key: 'consigneeName',
            dataIndex: 'consigneeName',
            ...getColumnSearchProps('consigneeName'),
            sorter: (a, b) => a.consigneeName?.localeCompare(b.consigneeName),
            sortDirections: ['descend', 'ascend']
        },{
            title : 'No. Of M/CS',
            width:"90px",
            key: 'invoicedCases',
            dataIndex: 'invoicedCases',
            ...getColumnSearchProps('invoicedCases'),
            
            // sorter: (a, b) => a.invoicedCases-b.invoicedCases,
            // sortDirections: ['descend', 'ascend']
        },{
            title: 'Net Weight In Kgs',
            key: 'quantity_kg',
            width:"90px",
            dataIndex: 'quantityInKgs',
            ...getColumnSearchProps('quantityInKgs'),
            render: (text, record) => {
                const qty = Number(record.quantityInKgs); // Convert to a number
                return !isNaN(qty) // Check if qty is a valid number
                    ? qty % 1 === 0 // Check if qty is a whole number
                        ? qty.toFixed(0) // No decimal places
                        : qty.toFixed(3) // One decimal place
                    : '-';
            }
           
        },
        {
            title: 'Net Weight In Lbs',
            width:"90px",
            key: 'quantity_lb',
            dataIndex: 'quantityInLbs',
            ...getColumnSearchProps('quantityInLbs'),
            
            // sorter: (a, b) => a.quantityInLbs - b.quantityInLbs,
            // sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                const qty = Number(record.quantityInLbs); // Convert to a number
                return !isNaN(qty) // Check if qty is a valid number
                    ? qty % 1 === 0 // Check if qty is a whole number
                        ? qty.toFixed(0) // No decimal places
                        : qty.toFixed(3) // One decimal place
                    : '-';
            }
            
        }
        
        
        ,{
            title: 'Product Name',
            key: 'productName',
            dataIndex: 'productName',
            render: (text) => {
                if (!text) return '-';
                console.log(text,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
                const trimmedName = text?.split('-')?.slice(0, 2)?.join('-'); // Keeps only the first two parts
                console.log(trimmedName,"#########################")
                return trimmedName;
            },
            // ...getColumnSearchProps('productName'),
            // sorter: (a, b) => a.productName?.localeCompare(b.productName),
            // sortDirections: ['descend', 'ascend']
        },
        
        {
            title : 'Brand Name',
            key: 'brand',
            width:"120px",
            dataIndex: 'brand',
            ...getColumnSearchProps('brand'),
            sorter: (a, b) => a.brand?.localeCompare(b.brand),
            sortDirections: ['descend', 'ascend']
        },
        {
            title : 'Packing',
            key: 'packing',
            width:"120px",
            dataIndex: 'packing',
            ...getColumnSearchProps('packing'),
            sorter: (a, b) => a.packing?.localeCompare(b.packing),
            sortDirections: ['descend', 'ascend']
        },
        {
            title : 'Invoice Value In USD',
            width:"90px",
            key: 'invoiceUsd',
            dataIndex: 'invoiceUsd',
            ...getColumnSearchProps('invoiceUsd'),
            sorter: (a, b) => a.invoiceUsd?.localeCompare(b.invoiceUsd),
            sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                const qty = Number(record.invoiceUsd); // Convert to a number
                return !isNaN(qty) // Check if qty is a valid number
                    ? qty % 1 === 0 // Check if qty is a whole number
                        ? qty.toFixed(0) // No decimal places
                        : qty.toFixed(3) // One decimal place
                    : '-';
            }
            
        },{
            title : 'Invoice Value In INR',
            width:"90px",
            key: 'invoiceInr',
            dataIndex: 'invoiceInr',
            ...getColumnSearchProps('invoiceInr'),
            sorter: (a, b) => a.invoiceInr?.localeCompare(b.invoiceInr),
            sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                const qty = Number(record.invoiceInr); // Convert to a number
                return !isNaN(qty) // Check if qty is a valid number
                    ? qty % 1 === 0 // Check if qty is a whole number
                        ? qty.toFixed(0) // No decimal places
                        : qty.toFixed(3) // One decimal place
                    : '-';
            }
            
        },
        {
            title : 'Freight In USD',
            key: 'freight',
            dataIndex: 'freight',
            ...getColumnSearchProps('freight'),
            sorter: (a, b) => a.freight?.localeCompare(b.freight),
            sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                const qty = Number(record.freight); // Convert to a number
                return !isNaN(qty) // Check if qty is a valid number
                    ? qty % 1 === 0 // Check if qty is a whole number
                        ? qty.toFixed(0) // No decimal places
                        : qty.toFixed(3) // One decimal place
                    : '-';
            }

        },
        {
            title:"Sub Total",
            key: 'subTotal',
            dataIndex: 'subTotal',
            ...getColumnSearchProps('subTotal'),
            sorter: (a, b) => a.subTotal?.localeCompare(b.subTotal),
            sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                const invoiceInr = Number(record.invoiceInr); 
                const qty = Number(record.freight); 
                const subTotal=(invoiceInr-qty)
                return !isNaN(subTotal) 
                    ? subTotal % 1 === 0 
                        ? subTotal.toFixed(0) 
                        : subTotal.toFixed(3)
                    : '-';
            }
        },
        {title : 'Anti Dumping',
            key: 'antiDumping',
            width:"110px",
            dataIndex: 'antiDumping',
            // ...getColumnSearchProps('antiDumping'),
            // sorter: (a, b) => a.antiDumping?.localeCompare(b.antiDumping),
            // sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                if (record.country === 'USA') {
                  const invoiceUsd = parseFloat(record.invoiceUsd) || 0;
                  const freight = parseFloat(record.freight) || 0;
                  return ((invoiceUsd - freight) * 0.0135).toFixed(2);
                }
                return '0.00';
              }

        },
        {
            title : 'CVD',
            key: 'netWeightKg',
            dataIndex: 'netWeightKg',
            // ...getColumnSearchProps('netWeightKg'),
            // sorter: (a, b) => a.netWeightKg?.localeCompare(b.netWeightKg),
            // sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                if (record.country === 'USA') {
                const invoiceUsd = parseFloat(record.invoiceUsd) || 0;
                const freight = parseFloat(record.freight) || 0;
                const antiDumping = ((invoiceUsd - freight) * 0.0135);
                return ((invoiceUsd - freight - antiDumping) * 0.0436).toFixed(2);
            }
            return '0.00';
            }
        },{
            title : '$ Value',
            width:"90px",
            key: '$value',
            dataIndex: '$value',
            ...getColumnSearchProps('$value'),
            sorter: (a, b) => a.$value?.localeCompare(b.$value),
            sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                const qty = Number(record.$value); // Convert to a number
                return !isNaN(qty) // Check if qty is a valid number
                    ? qty % 1 === 0 // Check if qty is a whole number
                        ? qty.toFixed(0) // No decimal places
                        : qty.toFixed(3) // One decimal place
                    : '-';
            }

            

        },{
            title : 'Fob In USD',
            key: 'fobUsd',
            dataIndex: 'fobUsd',
            // ...getColumnSearchProps('fobUsd'),
            // sorter: (a, b) => a.fobUsd?.localeCompare(b.fobUsd),
            // sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                const invoiceUsd = parseFloat(record.invoiceUsd) || 0;
                const freight = parseFloat(record.freight) || 0;
                const antiDumping = ((invoiceUsd - freight) * 0.0135);
                const val = (invoiceUsd - freight - antiDumping)
                const qty = Number(val); // Convert to a number
                return !isNaN(qty) // Check if qty is a valid number
                    ? qty % 1 === 0 // Check if qty is a whole number
                        ? qty.toFixed(0) // No decimal places
                        : qty.toFixed(3) // One decimal place
                    : '-';
                
            }

        },
        {
            title : 'Fob In INR',
            key: 'fobInr',
            width:"100px",
            dataIndex: 'fobInr',
            // ...getColumnSearchProps('fobInr'),
            // sorter: (a, b) => a.fobInr?.localeCompare(b.fobInr),
            // sortDirections: ['descend', 'ascend'],
            render: (text, record) => {
                const invoiceUsd = parseFloat(record.invoiceUsd) || 0;
                const freight = parseFloat(record.freight) || 0;
                const antiDumping = ((invoiceUsd - freight) * 0.0135);
                const fobUsd = (invoiceUsd - freight - antiDumping)
                const value = parseFloat(record.$value) || 0;
                const val = (fobUsd * value)
                const qty = Number(val); // Convert to a number
                return !isNaN(qty) // Check if qty is a valid number
                    ? qty % 1 === 0 // Check if qty is a whole number
                        ? qty.toFixed(0) // No decimal places
                        : qty.toFixed(3) // One decimal place
                    : '-';
               
            }
        },
        // {
        //     title : 'M Fees To EIA',
        //     width:"110px",
        //     key: 'mFee',
        //     dataIndex: 'mFee',
   
        //     render: (text, record) => {
        //         const fobInr = parseFloat(record.fobInr) || 0;
        //         const val = (fobInr * 0.002)
        //         const qty = Number(val); // Convert to a number
        //         return !isNaN(qty) // Check if qty is a valid number
        //             ? qty % 1 === 0 // Check if qty is a whole number
        //                 ? qty.toFixed(0) // No decimal places
        //                 : qty.toFixed(3) // One decimal place
        //             : '-';
               
        //     }
                
            
        // },
        {
            title : 'Vessel Name',
            key: 'vesselName',
            dataIndex: 'vesselName',
            ...getColumnSearchProps('vesselName'),
            sorter: (a, b) => a.vesselName?.localeCompare(b.vesselName),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },
        {
            title : 'Container NO',
            key: 'containerNumber',
            dataIndex: 'containerNumber',
            ...getColumnSearchProps('containerNumber'),
            sorter: (a, b) => a.containerNumber?.localeCompare(b.containerNumber),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },{
            title : 'Seal No',
            key: 'lineSeal',
            dataIndex: 'lineSeal',
            ...getColumnSearchProps('lineSeal'),
            sorter: (a, b) => a.lineSeal?.localeCompare(b.lineSeal),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },{
            title : 'B/L No',
            key: 'blNum',
            dataIndex: 'blNum',
            ...getColumnSearchProps('blNum'),
            sorter: (a, b) => a.blNum?.localeCompare(b.blNum),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },{
            title : 'Liner',
            width:"90px",
            key: 'code',
            dataIndex: 'code',
            ...getColumnSearchProps('code'),
            sorter: (a, b) => a.code?.localeCompare(b.code),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },{
            title : 'Port Of Loading',
            key: 'portOfLoadingId',
            width:"90px",
            dataIndex: 'portOfLoadingId',
            ...getColumnSearchProps('portOfLoadingId'),
            sorter: (a, b) => a.portOfLoadingId-b.portOfLoadingId,        
                sortDirections: ['descend', 'ascend'],
                render: (value) => {
                    const port = PortOfEntryInput.find(item => item.value === value);
                    return port ? port.name : '-';
                }

        },{
            title : 'Port Of Destinaton',
            width:"90px",
            key: 'portOfDischarge',
            dataIndex: 'portOfDischarge',
            ...getColumnSearchProps('portOfDischarge'),
            sorter: (a, b) => a.portOfDischarge-b.portOfDischarge,        
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },{
            title : 'Country',
            key: 'country',
            width:"90px",
            dataIndex: 'country',
            ...getColumnSearchProps('country'),
            sorter: (a, b) => a.country?.localeCompare(b.country),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'
        },{
            title : 'Vehicle',
            width:"90px",
            key: 'transporter',
            dataIndex: 'transporter',
            ...getColumnSearchProps('transporter'),
            sorter: (a, b) => a.transporter?.localeCompare(b.transporter),
            sortDirections: ['descend', 'ascend'],
            render: (text) => text ? text : '-',
        },{
            title : 'CHA',
            key: 'cha',
            dataIndex: 'cha',
            ...getColumnSearchProps('cha'),
            sorter: (a, b) => a.cha?.localeCompare(b.cha),
            sortDirections: ['descend', 'ascend']
        },{
            title : 'Shipment Date As Per PO',
            key: 'actualDate',
            dataIndex: 'actualDate',
            // ...getColumnSearchProps('actualDate'),
            sorter: (a, b) => a.actualDate?.localeCompare(b.actualDate),
            sortDirections: ['descend', 'ascend'],
            render:(index,val) =>{

                return <span>{val.actualDate?moment(val.actualDate).format("DD-MM-YYYY"):'-'}</span>
    
            }

        },{
            title : 'ETD',
            key: 'etd',
            dataIndex: 'etd',
            // ...getColumnSearchProps('etd'),
            sorter: (a, b) => a.etd?.localeCompare(b.etd),
            sortDirections: ['descend', 'ascend'],
            render:(index,val) =>{

                return <span>{val.etd?moment(val.etd).format("DD-MM-YYYY"):'-'}</span>
    
            }

        },{
            title : 'ETA',
            key: 'eta',
            dataIndex: 'eta',
            // ...getColumnSearchProps('invNum'),
            sorter: (a, b) => a.invNum?.localeCompare(b.invNum),
            sortDirections: ['descend', 'ascend'],
            render:(index,val) =>{

                return <span>{val.eta?moment(val.eta).format("DD-MM-YYYY"):'-'}</span>
    
            }

        },{
            title : 'Payment Type',
            key: 'paymentTerms',
            dataIndex: 'paymentTerms',
            ...getColumnSearchProps('paymentTerms'),
            sorter: (a, b) => a.paymentTerms?.localeCompare(b.paymentTerms),
            sortDirections: ['descend', 'ascend'],
            render: (text) => (
                <Tooltip title={text || "-"}>
                  {text ? `${text.substring(0, 20)}...` : "-"}
                </Tooltip>
              ),

        },{
            title : 'Q NO',
            width:"90px",
            key: 'qNo',
            dataIndex: 'qNo',
            ...getColumnSearchProps('qNo'),
            sorter: (a, b) => a.qNo?.localeCompare(b.qNo),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },{
            title : 'SB NO',
            width:"90px",
            key: 'sbNum',
            dataIndex: 'sbNum',
            ...getColumnSearchProps('sbNum'),
            sorter: (a, b) => a.sbNum?.localeCompare(b.sbNum),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },{
            title : 'SB Date',
            key: 'sbDate',
            dataIndex: 'sbDate',
            // ...getColumnSearchProps('sbDate'),
            sorter: (a, b) => a.sbDate?.localeCompare(b.sbDate),
            sortDirections: ['descend', 'ascend'],
            render:(index,val) =>{

            return <span>{val.sbDate?moment(val.sbDate).format("DD-MM-YYYY"):'-'}</span>

        }
    },{
            title : 'E Seal NO',
            width:"90px",
            key: 'esealNum',
            dataIndex: 'esealNum',
            ...getColumnSearchProps('esealNum'),
            sorter: (a, b) => a.esealNum?.localeCompare(b.esealNum),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },
        {
            title : 'Truck No',
            width:"90px",
            key: 'truckNum',
            dataIndex: 'truckNum',
            ...getColumnSearchProps('truckNum'),
            sorter: (a, b) => a.truckNum?.localeCompare(b.truckNum),
            sortDirections: ['descend', 'ascend'],
            render :(text) => text ? text: '-'

        },
        // {
        //     title : 'Truck NO',
        //     key: 'transporter',
        //     width:"110px",
        //     dataIndex: 'transporter',
        //     ...getColumnSearchProps('transporter'),
        //     sorter: (a, b) => a.transporter?.localeCompare(b.transporter),
        //     sortDirections: ['descend', 'ascend'],
        //     render :(text) => text ? text: '-'

        // }



    ]

  let rowIndex = 1
    const excelColumn: any =[
        {
            title: 'S No',
            width: 50,
        render: (text, object, index) => {
        if (index == shipment.length) {
          return null;
        } else {
          return rowIndex++;
        }
      }

        },
        {
            title: "Unit(Plant Code)",
            dataIndex: "unitName",
            render :(text) => text ? text: '-'
      
        },  
        {
            title: "Processing Unit",
            dataIndex: "processingUnit",
            render :(text) => text ? text: '-'
      
        },
        {
            title: "Company",
            dataIndex: "companyName",
            render :(text) => text ? text: '-'
      
        }, 
        {
            title : 'P.O Number',
            key: 'poNumber',
            dataIndex: 'poNumber',
            render :(text) => text ? text: '-'

    
        },
        {
            title : 'P.O Date',
            key: 'poDate',
            dataIndex: 'poDate',
            render:(index,val) =>{

                return <span>{val.poDate?moment(val.poDate).format("DD-MM-YYYY"):'-'}</span>
    
            }

            
        },
        {
            title : 'Certification',
            key: 'certificate',
            dataIndex: 'certificate',
            render :(text) => text ? text: '-'

    
        },
        {
            title : 'Invoice NO',
            key: 'invoiceNum',
            dataIndex: 'invoiceNum',
            render :(text) => text ? text: '-'

        },
        {
            title : 'Invoice Date',
            key: 'invoiceDate',
            dataIndex: 'invoiceDate',
            render:(index,val) =>{

                return <span>{val.invoiceDate?moment(val.invoiceDate).format("DD-MM-YYYY"):'-'}</span>
    
            }
        },
        {
            title : 'Consignee Name',
            key: 'consigneeName',
            dataIndex: 'consigneeName',
            render :(text) => text ? text: '-'

    
        },{
            title : 'NO.OF M/CS',
            key: 'invoicedCases',
            dataIndex: 'invoicedCases',
            render :(text) => text ? text: '-'

        },{
            title: 'Net Weight In Kgs',
            key: 'quantity_kg',
            dataIndex: 'quantityInKgs',

             render :(text) => text ? text: '-'
            // render: (value) => (value != null ? value.toFixed(2) : '0.00')
        },
        {
            title: 'Net Weight In Lbs',
            key: 'quantity_lb',
            dataIndex: 'quantityInLbs',

             render :(text) => text ? text: '-'
            // render: (value) => (value != null ? value.toFixed(2) : '0.00')
        }
        
        
        ,{
            title : 'Product Name',
            key: 'productName',
            dataIndex: 'productName',
            render: (text) => {
                if (!text) return '-';
                const trimmedName = text?.split('-')?.slice(0, 2)?.join('-');
                return trimmedName;
            }

           
        },
        {
            title : 'Brand Name',
            key: 'brand',
            width:"130px",
            dataIndex: 'brand',
            render :(text) => text ? text: '-'

            
        },
        {
            title : 'Packing',
            key: 'packing',
            width:"130px",
            dataIndex: 'packing',
            render :(text) => text ? text: '-'
          
        },
        {
            title : 'Invoice Value In USD',
            key: 'invoiceUsd',
            dataIndex: 'invoiceUsd',
            render :(text) => text ? text: '-'

         
        },{
            title : 'Invoice Value In INR',
            key: 'invoiceInr',
            dataIndex: 'invoiceInr',
            render :(text) => text ? text: '-'

      
        },{
            title : 'Freight In USD',
            key: 'freight',
            dataIndex: 'freight',
            render :(text) => text ? text: '-'

    

        },
        {
            title:"Sub Total",
            key: 'subTotal',
            dataIndex: 'subTotal',
            render: (text, record) => {
                const invoiceInr = Number(record.invoiceInr); 
                const qty = Number(record.freight); 
                const subTotal=(invoiceInr-qty)
                return subTotal;
            }
        },
        {title : 'Anti Dumping',
            key: 'antiDumping',
            dataIndex: 'antiDumping',
  
            render: (text, record) => {
                if (record.country === 'USA') {
                    const invoiceUsd = parseFloat(record.invoiceUsd) || 0;
                    const freight = parseFloat(record.freight) || 0;
                    return ((invoiceUsd - freight) * 0.0135).toFixed(2);
                  }
                  return '0.00';
            }

        },
        {
            title : 'CVD',
            key: 'netWeightKg',
            dataIndex: 'netWeightKg',
            render: (text, record) => {
                if (record.country === 'USA') {
                    const invoiceUsd = parseFloat(record.invoiceUsd) || 0;
                    const freight = parseFloat(record.freight) || 0;
                    const antiDumping = ((invoiceUsd - freight) * 0.0135);
                    return ((invoiceUsd - freight - antiDumping) * 0.0436).toFixed(2);
                }
                return '0.00';
            }
        },{
            title : '$ Value',
            key: '$value',
            dataIndex: '$value',
            render :(text) => text ? text: '-'

    

        },{
            title : 'Fob In USD',
            key: 'fobUsd',
            dataIndex: 'fobUsd',
            render: (text, record) => {
                const invoiceUsd = parseFloat(record.invoiceUsd) || 0;
                const freight = parseFloat(record.freight) || 0;
                const antiDumping = ((invoiceUsd - freight) * 0.0135);
                return (invoiceUsd - freight - antiDumping).toFixed(2);
            }

        },
        {
            title : 'Fob In INR',
            key: 'fobInr',
            dataIndex: 'fobInr',
            render: (text, record) => {
                const invoiceUsd = parseFloat(record.invoiceUsd) || 0;
                const freight = parseFloat(record.freight) || 0;
                const antiDumping = ((invoiceUsd - freight) * 0.0135);
                const value = parseFloat(record.$value) || 0;
                const fobUsd=invoiceUsd-freight-antiDumping
                return (fobUsd * value).toFixed(2);
            }
        },
        // {
        //     title : 'M Fees To EIA',
        //     key: 'mFee',
        //     width:"90px",
        //     dataIndex: 'mFee',

        //     render: (text, record) => {
        //         const fobInr = parseFloat(record.fobInr) || 0;
        //         return (fobInr * 0.002).toFixed(2);
        //     }
            
        // },
        {
            title : 'Vessel Name',
            key: 'vesselName',
            dataIndex: 'vesselName',
    
            render :(text) => text ? text: '-'

        },
        {
            title : 'Container NO',
            key: 'containerNumber',
            dataIndex: 'containerNumber',
            render :(text) => text ? text: '-'

        },{
            title : 'Seal No',
            key: 'lineSeal',
            dataIndex: 'lineSeal',
            render :(text) => text ? text: '-'
            
        },{
            title : 'B/L No',
            width:"90px",
            key: 'blNum',
            dataIndex: 'blNum',
            render :(text) => text ? text: '-'

        },{
            title : 'Liner',
            key: 'code',
            dataIndex: 'code',
            render :(text) => text ? text: '-'

        },{
            title : 'Port Of Loading',
            key: 'portOfLoadingId',
            dataIndex: 'portOfLoadingId',
            render: (value) => {
                const port = PortOfEntryInput.find(item => item.value === value);
                return port ? port.name : '-';
            }


        },{
            title : 'Port Of Destinaton',
            key: 'portOfDischarge',
            dataIndex: 'portOfDischarge',
            render :(text) => text ? text: '-'

        },{
            title : 'Country',
            key: 'country',
            dataIndex: 'country',
            render :(text) => text ? text: '-'
        },{
            title : 'Vehicle',
            key: 'transporter',
            dataIndex: 'transporter',
            render: (text) => text ? text : '-',
        },{
            title : 'CHA',
            key: 'cha',
            dataIndex: 'cha',
            render :(text) => text ? text: '-'


        },{
            title : 'Shipment Date As Per PO',
            key: 'actualDate',
            dataIndex: 'actualDate',
            render:(index,val) =>{

                return <span>{val.actualDate?moment(val.actualDate).format("DD-MM-YYYY"):'-'}</span>
    
            }

        },{
            title : 'ETD',
            key: 'etd',
            dataIndex: 'etd',
            render:(index,val) =>{

                return <span>{val.etd?moment(val.etd).format("DD-MM-YYYY"):'-'}</span>
    
            }

        },{
            title : 'ETA',
            key: 'eta',
            dataIndex: 'eta',
            render:(index,val) =>{

                return <span>{val.eta?moment(val.eta).format("DD-MM-YYYY"):'-'}</span>
    
            }

        },{
            title : 'Payment Type',
            key: 'paymentTerms',
            dataIndex: 'paymentTerms',
            render :(text) => text ? text: '-'

        },{
            title : 'Q NO',
            key: 'qNo',
            dataIndex: 'qNo',
            render :(text) => text ? text: '-'

        },{
            title : 'SB NO',
            key: 'sbNum',
            dataIndex: 'sbNum',
            render :(text) => text ? text: '-'

        },{
            title : 'SB Date',
            key: 'sbDate',
            dataIndex: 'sbDate',
            render:(index,val) =>{

            return <span>{val.sbDate?moment(val.sbDate).format("DD-MM-YYYY"):'-'}</span>

        }
    },{
            title : 'E Seal NO',
            key: 'esealNum',
            dataIndex: 'esealNum',
            render :(text) => text ? text: '-'

        },
        {
            title : 'Truck No',
            key: 'truckNum',
            dataIndex: 'truckNum',
            render :(text) => text ? text: '-'

        },
        // {
        //     title : 'Truck NO',
        //     key: 'truckNum',
        //     dataIndex: 'truckNum',
        //     render :(text) => text ? text: '-'

        // }



    ]

    const exportExcel = () => {
        const excel = new Excel();
    
        let totalCartons = 0;
        let totalWeight = 0;
        let totalNetAmount = 0;
    
        // Processed data without modifying original values
        const processedData = shipment.map((record) => {
            // Accumulate totals
            totalCartons += parseFloat(record.invoicedCases) || 0;
            totalWeight += parseFloat(record.quantityInKgs) || 0;
            totalNetAmount += parseFloat(record.invoiceInr) || 0;
    
            return { ...record }; // Keep original values
        });
    
        // Append total row
        processedData.push({
            sNo: '', 
            unitName: '',
            companyName: '',
            poNumber: '',
            certificate: '',
            invoiceNum: '',
            invoiceDate: '',
            consigneeName: 'Total',
            cases: totalCartons.toFixed(2), // Correct sum
            quantityInKgs: totalWeight.toFixed(2), // Correct sum
            quantityInLbs: '',
            productName: '',
            brand: '',
            netWeight: totalCartons.toFixed(2), 
            packing: '',
            invoiceUsd: '',
            invoiceInr: totalNetAmount.toFixed(2), // Correct sum
            freight: '', 
        });
    
        excel
            .addSheet('Shipment Details Report')
            .addColumns(excelColumn)
            .addDataSource(processedData, { str2num: true })
            .saveAs('Shipment-Details-Report.xlsx');
    };
    

      const onReset = () => {
        form.resetFields();
        getActiveShippmentDetails()
        
    }

  return (
    <div>
        <Card   size="small" title={<span style={{ color: 'white' }} >Shipment Details Report</span>} 
        style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        extra={
            <div>
              <Button icon={<DownloadOutlined />} onClick={() => { exportExcel(); }} style={{ marginRight: 30 }}>
                GET EXCEL
              </Button>
            </div>
          }>

<      Form layout={"vertical"}  form = {form} >
                <Row gutter={[24, 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: false, 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="companyId" label="Company" >
        
            
                    <Select
                        placeholder="Select Company"
                        showSearch
                        optionFilterProp="children"
                        filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        allowClear
                        dropdownMatchSelectWidth={false}

                    >
                        {factoriesData.map(dropData => {
                            console.log(factoriesData,'factoriesDatafactoriesDatafactoriesData')
                            return <Option value={dropData.companyId}>{dropData.company}</Option>
                        })}
                    </Select>
                </Form.Item>
                            </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item name="saleOrderId"
                            label="Customer PO"
                            rules=
                            {[{ required: false, message: ' Select ' },]}>
                            <Select showSearch placeholder="Select Customer PO"
                                optionFilterProp="children"
                                allowClear
                            >
                                <Option key={0} value={null}>Select Customer PO</Option>
                                {poNumber.map((data) => {
                                    return <Option key={data.sale_order_id} value={data.sale_order_id}> {data.poNumber}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col  xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item
                            label="Brand Name"
                            name='masterBrandId'
                            rules={[{ required: false }]}
                        >
                            <Select
                                showSearch
                                placeholder="Select Brand Name"
                                optionFilterProp="children"
                                allowClear
                                // onSearch={onSearch}
                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}

                            >
                                <Option key={0} value={null}>Select Brand Name</Option>
                                {brand.map(branddropData => {
                                    return <Option key={branddropData.master_brand_id} value={branddropData.master_brand_id}>{branddropData.brand}</Option>
                                })}
                                |
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col  xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item
                            label="Invoice Number"
                            name='invoiceNumber'
                            rules={[{ required: false }]}
                        >
                            <Select
                                showSearch
                                placeholder="Select Invoice Number"
                                optionFilterProp="children"
                                allowClear
                                // onSearch={onSearch}
                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}

                            >
                                <Option key={0} value={null}>Select Brand Name</Option>
                                {invoiceNo.map(branddropData => {
                                    return <Option key={branddropData.invoiceNum} value={branddropData.invoiceNum}>{branddropData.invoiceNum}</Option>
                                })}
                                |
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
            <Form.Item label="Invoice Date" name="invoiceDate" 
             >
              <RangePicker />
            </Form.Item>
          </Col>
                    <Col  xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                <Form.Item name="financialYear" label="Financial Year">
                                                                        <Select
                                                                          showSearch
                                                                          placeholder="Select Financial Year"
                                                                          optionFilterProp="children"
                                                                          filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                                          allowClear
                                                                        >
                                                                          {years.filter(year => year.financialYear !== null).map((y: any) => (
                                                                            <Select.Option key={y.financialYear} value={y.financialYear}>
                                                                              {y.financialYear}
                                                                            </Select.Option>
                                                                          ))}
                                                                        </Select>
                                                                      </Form.Item>
                                                                    </Col>
                

                        <Col  style={{marginTop:'25px'}}>
                        <Button type="primary" style={{ marginRight: '4px' }} onClick={getActiveShippmentDetails}>
                            Get Report
                        </Button>
                        <Button style={{ marginLeft: '5px' }} type="primary" htmlType="reset" onClick={onReset}> Reset </Button>
                    </Col>
                </Row>
            </Form>
            {shipment.length > 0 ? <>

            <Row gutter={16} style={{height:'45px'}}>
            <Col span={5}>
              <Tag color="#92d8b4" style={{ display: 'flex', color: 'black', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px' }}>
                Total No.Of Shipment Orders : {shipment.length}
              </Tag></Col>
              <Col span={3}>
              <Tag color="#e2bfcb" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px',color: 'black' }}>
              No.Of PO's : {shipment.filter(item => item.poNumber).length}
              </Tag></Col>
              <Col span={4}>
              <Tag color="#f7d186" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px',color: 'black' }}>
             No.Of Countries : {[...new Set(shipment.map(item => item.country))].length}
              </Tag></Col>
              </Row>
        <Table
                columns={tableColumn}
                dataSource={shipment}
                scroll={{ x:"max-content" }}
                pagination={{
                      current: page,
                      pageSize: pageSize,
                      onChange: (current, size) => {
                        setPage(current);
                        setPageSize(size); 
                      }
                    }}
                onChange={handleTableChange}
                summary={(pageData) => {
                    let totalCartons = 0;
                    let totalWeight = 0;
                    let totalNetAmount = 0;
                  
                    pageData.forEach(({ invoicedCases,quantityInKgs, invoiceInr }) => {
                        totalCartons += parseFloat(invoicedCases) || 0;
                        totalWeight += parseFloat(quantityInKgs) || 0;
                        totalNetAmount += (parseFloat(invoiceInr) || 0) 
                      });
                  
                    return (
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={7} colSpan={9}>
                          Total
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={8}>
                          {totalCartons.toFixed(2)}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={9}> {totalWeight.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}>
                         
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={14}>
                         
                         </Table.Summary.Cell>
                        <Table.Summary.Cell index={15}>
                          {totalNetAmount.toFixed(2)}
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                    );
                  }}
                />
           </> : ' '}

        </Card>

    </div>
  )
}

export default shippmentDetailsReport