import { ExpensesLogisticsUpdateDto } from '@gtpl/shared-models/common-models';
import { ContainerRegisterService } from '@gtpl/shared-services/logistics';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Drawer, Tooltip, message,Input } from 'antd';
import Table, { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom';
import { EditOutlined,SearchOutlined } from '@ant-design/icons';
import ExpensesLogisticsForm from './expenses-form';
import moment from 'moment';
import Highlighter from 'react-highlight-words';



const ExpensesLogisticsView = () => {
const [expensesLogisticsView, setExpensesLogisticsView] = useState([]);
const containerRegisterService=new ContainerRegisterService()
const [drawerVisible, setDrawerVisible] = useState(false);
const [selectedExpensesLogisticsData, setSelectedExpensesLogisticsData] = useState<any>(undefined);
const [updateCount, setUpdateCount] = useState(0);
const [searchText, setSearchText] = useState('');
const [searchedColumn, setSearchedColumn] = useState('');
const searchInput = useRef(null);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState<number>(null);

useEffect(()=>{
    getData()
},[])


const updateExpensesLogistics = (data: any) => {
  const expensesLogisticsDto = new ExpensesLogisticsUpdateDto(
    data.expensesLogisticsId,
    data.fdaDueDate,
    data.remarks,
    data.createdUser,
    localStorage.getItem("createdUser") || "unknown",
    data.isActive
  );

  containerRegisterService.updateExpensesLogistics(expensesLogisticsDto).then(res => {
    if (res.status) {
      message.success('Data Updated Successfully');
      setDrawerVisible(false);
      getData();
    } else {
      message.error(res.internalMessage);
    }
  }).catch(err => {
    message.error(err.message);
  });
};


  const closeDrawer = () => {
    setDrawerVisible(false);
  }
  
  const openFormWithData = (viewData: ExpensesLogisticsUpdateDto) => {
    setDrawerVisible(true);
    setSelectedExpensesLogisticsData(viewData);

    // if (viewData.fdaDueDate) {
    //     const matches = viewData.fdaDueDate.match(/R(\d+)$/);
    //     if (matches) {
    //         setUpdateCount(parseInt(matches[1], 10));
    //     } else {
    //         setUpdateCount(0);
    //     }
    // } else {
    //     setUpdateCount(0);
    // }
};


    const getData = () => {
        containerRegisterService.getExpensesDetailsOfLogistics().then(res => {
            if (res.status) {
                setExpensesLogisticsView(res.data);
            } else {
              setExpensesLogisticsView([])
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        })
    };

    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 Columns : ColumnProps<any>[] = [
        {
            title: 'S No',
            key: 'sno',
            width: '70px',
            // responsive: ['sm'],
            render: (text, object, index) => (page - 1) * pageSize + (index + 1)
          },
          {
            title: "PO Number",
            dataIndex: "poNumber",
            sorter: (a, b) => a.poNumber?.localeCompare(b.poNumber),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('poNumber'),
          },
        {
            title:'CHA Bill',
            dataIndex:'chaBill',
            ...getColumnSearchProps('chaBill'),
            sorter: (a, b) => a.chaBill - b.chaBill,
            sortDirections: ['descend', 'ascend'],

        },
        {
            title:'Ocean Frieght',
            dataIndex:'oceanFrieght',
            ...getColumnSearchProps('oceanFrieght'),
            sorter: (a, b) => a.oceanFrieght - b.oceanFrieght,
            sortDirections: ['descend', 'ascend'],

        },
        {
            title:'Domestic Frieght',
            dataIndex:'domesticFrieght',
            ...getColumnSearchProps('domesticFrieght'),
            sorter: (a, b) => a.domesticFrieght - b.domesticFrieght,
            sortDirections: ['descend', 'ascend'],

        },
        {
          title: "Sales Comisssion",
          dataIndex: "salesComission",
          ...getColumnSearchProps('salesComission'),
          sorter: (a, b) => a.salesComission - b.salesComission,
          sortDirections: ['descend', 'ascend'],

      },
      {
          title: "Anti Dumping duty",
          dataIndex: "antiDumpingDuty",
          ...getColumnSearchProps('antiDumpingDuty'),
          sorter: (a, b) => a.antiDumpingDuty - b.antiDumpingDuty,
          sortDirections: ['descend', 'ascend'],

      },
        
        {
          title: "CVD",
          dataIndex: "cvd",
          ...getColumnSearchProps('cvd'),
          sorter: (a, b) => a.cvd - b.cvd,
          sortDirections: ['descend', 'ascend'],

        },
        {
            title: "Clearing & Forwarding",
            dataIndex: "clearingForwarding",
            ...getColumnSearchProps('clearingForwarding'),
            sorter: (a, b) => a.clearingForwarding - b.clearingForwarding,
            sortDirections: ['descend', 'ascend'],

          },
          {
            title: "DDP Transport",
            dataIndex: "ddpTransport",
            ...getColumnSearchProps('ddpTransport'),
            sorter: (a, b) => a.ddpTransport - b.ddpTransport,
            sortDirections: ['descend', 'ascend'],

          },
          {
            title: "Marine Insurance",
            dataIndex: "marineInsurance",
            ...getColumnSearchProps('marineInsurance'),
            sorter: (a, b) => a.marineInsurance - b.marineInsurance,
            sortDirections: ['descend', 'ascend'],

          },
          {
            title: "AMC",
            dataIndex: "amc",
            ...getColumnSearchProps('amc'),
            sorter: (a, b) => a.amc - b.amc,
            sortDirections: ['descend', 'ascend'],

          },
          {
            title: "Duty Drawback",
            dataIndex: "dutyDrawback",
            ...getColumnSearchProps('dutyDrawback'),
            sorter: (a, b) => a.dutyDrawback - b.dutyDrawback,
            sortDirections: ['descend', 'ascend'],

          },
          {
            title: "RODTEP Amount",
            dataIndex: "rodtepAmount",
            ...getColumnSearchProps('rodtepAmount'),
            sorter: (a, b) => a.rodtepAmount - b.rodtepAmount,
            sortDirections: ['descend', 'ascend'],

          },
          {
            title: "FDA/Due Date",
            dataIndex: "fdaDueDate",
            ...getColumnSearchProps('fdaDueDate'),

            render: (value, record) => {
                const dateTimeRegex = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/;
                const dateSuffixRegex = /\d{4}-\d{2}-\d{2} R\d+/;
        
                if (dateSuffixRegex.test(record.fdaDueDate)) {
                    return record.fdaDueDate;
                } else if (dateTimeRegex.test(record.fdaDueDate)) {
                    return moment(record.fdaDueDate.split(' ')[0]).format('DD-MM-YYYY');
                } else {
                    return moment(record.fdaDueDate).format('DD-MM-YYYY');
                }
            },
            sorter: (a, b) => moment(a.fdaDueDate).unix() - moment(b.fdaDueDate).unix(),
            sortDirections: ['descend', 'ascend'],
            // ...getColumnSearchProps('fdaDueDate')

        },
          {
            title: "Remarks",
            dataIndex: "remarks",
            sorter: (a, b) => a.remarks?.localeCompare(b.remarks),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('remarks'),
          },
          {
            title: `Action`,
            dataIndex: 'action',
            width: 100,
            // fixed: "right",
            render: (text, rowData) => (
              <span>
                <Tooltip placement="top" title='Edit'>
                  <EditOutlined className={'editSamplTypeIcon'} type="edit"
                    onClick={() => {
                        openFormWithData(rowData);
                    }}
                    style={{ color: '#1890ff', fontSize: '14px' }}
                  />
                </Tooltip>
              </span>
            )
          },
    ]

  return (
    <div>
        <Card title={<span style={{ color: 'white' }}>Expenses View</span>}  style={{ textAlign: "center" }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
             extra={
                <Link to="/expenses-logistics">
                    <Button 
                        type="primary" 
                        style={{ background: "white", color: "#3C085C" }}
                    >
                        Create
                    </Button>
                </Link>
            }>
           <div style={{ maxHeight: '100%', overflowY: 'auto' }}> 
    <Table 
      columns={Columns} 
      dataSource={expensesLogisticsView} 
      pagination={{
        onChange(current, pageSize) {
          setPage(current);
          setPageSize(pageSize)
        }
      }}
    />
  </div> 
            <Drawer bodyStyle={{ paddingBottom: 80 }}  style={{fontWeight: "bold"}} title='Update' width={window.innerWidth > 768 ? '65%' : '85%'}
                onClose={closeDrawer} visible={drawerVisible} closable={true} >
        <Card headStyle={{ textAlign: 'center', fontWeight: 500, fontSize: 16 }} size='small'>
            
          <ExpensesLogisticsForm
                          setDrawerVisible={setDrawerVisible}
                          getExpensesDetailsOfLogistics={getData}
                          key={Date.now()}
                          updateExpensesLogistics={updateExpensesLogistics}
                          isUpdate={true}
                          expensesLogisticsData={selectedExpensesLogisticsData}
                          closeForm={closeDrawer} saleOrderId={0} />
        </Card>
      </Drawer>
        </Card>
       
    </div>
  )
}

export default ExpensesLogisticsView