// import React, { useState, useEffect, useRef } from 'react';
// import { Divider, Popconfirm, Card, Tooltip, Switch, Input, Button, Tag, Row, Col, Drawer, Space, Tabs, Form, DatePicker, Select, Spin, Modal } from 'antd';
// import Highlighter from 'react-highlight-words';
// import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
// import { SearchOutlined } from '@ant-design/icons';
// import Table, { ColumnProps } from 'antd/lib/table';
// import { ContainerReportModel } from '@gtpl/shared-models/logistics';
// import {ContainerRegisterGrid} from '@gtpl/pages/logistics/logistics-components/container-register-grid';
// import { ContainerRegisterService } from '@gtpl/shared-services/logistics';

// const Option = Select;


// /* eslint-disable-next-line */
// export interface logisticsLifeCycleProps { }

// export function LogisticLifeCycle(
//   props: logisticsLifeCycleProps
// ) {
//   const containerService = new ContainerRegisterService();
//   const [form] = Form.useForm();
//   const [page, setPage] = React.useState(1);
//   const searchInput = useRef(null);
//   const [containerData, setContainerData] = useState<any[]>([]);
//   useEffect(() => {
//     getAlllogisticslifecycledata();
//   }, []);
// const allstatus = ['NOT READY','READY TO BOOK','BOOKED','LOADING','LOADED AND SEALED','SHIPPED','OPEN','NOT RECEIVED','DRAFT RECEIVED','OBL RECEIVED','RECEIVED AND SHARED'];
//   let result=[];
//   allstatus.forEach(status =>{
//     const item = containerData.find(item => item.STATUS == status);
//     if (item) {
//       result.push(item);
//     }else{
//     result.push({STATUS: status,kakinada:0,unitone:0,unittwo:0,total:0});

//     }
//   })

//   const getAlllogisticslifecycledata= () => {
//     containerService.getLogisticsLifeCycleData().then(res => {
//       if (res.status) {setContainerData(res.data);
//       } else {
//         if (res.intlCode) {
//           setContainerData([]);
//             AlertMessages.getErrorMessage(res.internalMessage);
//         } else {
//          AlertMessages.getErrorMessage(res.internalMessage);
//         }
//       }
//     }).catch(err => {
//       AlertMessages.getErrorMessage(err.message);
//       setContainerData([]);
//     })
//   }
//   const columnsSkelton: ColumnProps<any>[] = [
//     {
//         title: '#',
//         key: 'sno',
//         width: '40px',
//         responsive: ['sm'],
//         render: (text, object, index) => (page - 1) * 10 + (index + 1)
//     },
//     {
//         title: 'Status',
//         dataIndex: 'STATUS',
//        width:'150px',
 
//     },
//     {
//       title: 'Kakinada',
//       dataIndex: 'kakinada',
//       width: '90px',
//       align:'right',

//   },
//   {
//     title: 'Unitone',
//     dataIndex: 'unitone',
//     width: '90px',
//     align:'right',

// },
// {
//   title: 'Unittwo',
//   dataIndex: 'unittwo',
//   width: '90px',
//   align:'right',

// },
// {
//   title: 'Total',
//   dataIndex: 'total',
//   width: '90px',
//   align:'right',
//  render:(value,record) =>{
//   const unit1 : number=Number(record?.unitone)
//   const unit2 : number=Number(record.unittwo)
//   const kkd : number =Number(record.kakinada)
//   const total =unit1+unit2+kkd;
//   return total;
//  }
// },
//  {
//   title: 'Total plant count',
//   dataIndex: 'total',
//   width: '120px',
//   align:'right',

// },
// ];
//   return (
//     <>
//       <Card title={<span style={{ color: 'black' }}>Logistics Life cycle</span>}
//         style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#white', border: 0 }}></Card>
//   <Table
//             // rowKey={record => record.downtimeTrackingId}
//             columns={columnsSkelton}
//             dataSource={result}
//             size='small'
//             pagination={false}
//             scroll={{ y:400 }}
//             bordered />
//          </>

//   );
// }



// export default LogisticLifeCycle;


import React, { useState, useEffect, useRef } from 'react';
import { Card, Button, Table, Input } from 'antd';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Excel } from 'antd-table-saveas-excel';
import { ContainerRegisterService } from '@gtpl/shared-services/logistics';
import type { ColumnProps } from 'antd/lib/table';
import { BarcodeOutlined, DownloadOutlined, SearchOutlined, UndoOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';



/* eslint-disable-next-line */
export interface logisticsLifeCycleProps {}

export function LogisticLifeCycle(props: logisticsLifeCycleProps) {
  const containerService = new ContainerRegisterService();
  const [page, setPage] = React.useState(1);
  const [containerData, setContainerData] = useState<any[]>([]);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);

  useEffect(() => {
    getAllLogisticsLifeCycleData();
  }, []);

  const allStatus = [
    'NOT READY', 'READY TO BOOK', 'BOOKED', 'LOADING', 'LOADED AND SEALED',
    'SHIPPED', 'OPEN', 'NOT RECEIVED', 'DRAFT RECEIVED', 'OBL RECEIVED', 'RECEIVED AND SHARED'
  ];

  let result = [];
  allStatus.forEach((status) => {
    const item = containerData.find((item) => item.STATUS === status);
    if (item) {
      result.push(item);
    } else {
      result.push({ STATUS: status, BMRINDUSTRIESIND: 0, SNOWWORLD: 0, BMRINDUSTRIESEXP: 0, total: 0 });
    }
  });

  const getAllLogisticsLifeCycleData = () => {
    containerService.getLogisticsLifeCycleData()
      .then((res) => {
        if (res.status) {
          setContainerData(res.data);
        } else {
          setContainerData([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setContainerData([]);
      });
  };

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  const getColumnSearchProps = (dataIndex) => ({
    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 type="primary" onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <SearchOutlined 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(), 100);
      }
    },
    render: text =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (
        text
      ),
  });

  const excelColumns = [
    { title: 'Status', dataIndex: 'STATUS', render: (text) => text !== null && text !== undefined ? text : 0 },
    { title: 'BMRINDUSTRIES-IND', dataIndex: 'BMRINDUSTRIESIND', render: (text) => text !== null && text !== undefined ? text : 0 },
    { title: 'SNOWWORLD', dataIndex: 'SNOWWORLD', render: (text) => text !== null && text !== undefined ? text : 0 },
    { title: 'BMRINDUSTRIES-EXP', dataIndex: 'BMRINDUSTRIESEXP', render: (text) => text !== null && text !== undefined ? text : 0 },
    {
      title: 'Total', 
      dataIndex: '', 
      render: (value, record) => {
        const BMRINDUSTRIESIND = Number(record?.BMRINDUSTRIESIND ?? 0);
        const SNOWWORLD = Number(record?.SNOWWORLD ?? 0);
        const BMRINDUSTRIESEXP = Number(record?.BMRINDUSTRIESEXP ?? 0);
        const total = BMRINDUSTRIESIND + SNOWWORLD + BMRINDUSTRIESEXP;
        // Explicitly return 0 if total is 0
        return (<>
        {total}</>)
      }
    },
    { title: 'Total plant count', dataIndex: 'total' }
  ];
  

  const columnsSkelton: ColumnProps<any>[] = [
    {
      title: '#',
      key: 'sno',
      width: '40px',
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'Status',
      dataIndex: 'STATUS',
      width: '150px',
      ...getColumnSearchProps('STATUS'),
      sorter: (a, b) => a.STATUS?.localeCompare(b.STATUS),
      sortDirections: ['descend', 'ascend'],

    },
    {
      title: 'BMRINDUSTRIES-IND',
      dataIndex: 'BMRINDUSTRIESIND',
      width: '130px',
      align: 'right'
    },
    {
      title: 'SNOWWORLD',
      dataIndex: 'SNOWWORLD',
      width: '90px',
      align: 'right'
    },
    {
      title: 'BMRINDUSTRIES-EXP',
      dataIndex: 'BMRINDUSTRIESEXP',
      width: '130px',
      align: 'right'
    },
    {
      title: 'Total',
      dataIndex: 'total',
      width: '90px',
      align: 'right',
      render: (value, record) => {
        const unit1: number = Number(record?.BMRINDUSTRIESIND ? record?.BMRINDUSTRIESIND : 0);
        const unit2: number = Number(record.SNOWWORLD ? record.SNOWWORLD : 0);
        const kkd: number = Number(record.BMRINDUSTRIESEXP ? record.BMRINDUSTRIESEXP : 0);
        const total = unit1 + unit2 + kkd;
        return total;
      }
    },
    {
      title: 'Total plant count',
      dataIndex: 'total',
      width: '120px',
      align: 'right'
    }
  ];

  const exportExcel = () => {
    const excel = new Excel();
    excel
      .addSheet('Container Report')
      .addColumns(excelColumns)
      .addDataSource(result, { str2num: true })
      .saveAs('Container-Report.xlsx');
  };

  return (
    <>
      <Card
        title={<span style={{ color: 'white' }}>Logistics Life Cycle</span>}
        style={{ textAlign: 'center' }}
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        extra={<Button icon={<DownloadOutlined />} onClick={() => { exportExcel(); }} style={{ marginRight: 30 }}>Get Excel</Button>}
      ></Card>
      <Table
        columns={columnsSkelton}
        dataSource={result}
        size="small"
        pagination={false}
        scroll={{ y: 400 }}
        bordered
      />
    </>
  );
}

export default LogisticLifeCycle;

