import React, { useEffect, useRef, useState } from 'react';
import { Card, Form, Input, Row, Col, Button, Table } from 'antd';
import { Link, useHistory } from 'react-router-dom';
import {  OcaenFreightRateRequest } from '@gtpl/shared-models/masters';
import {  OcaenFreightRateService } from '@gtpl/shared-services/masters';
import { Excel } from 'antd-table-saveas-excel';
import {CheckCircleOutlined,CloseCircleOutlined,RightSquareOutlined,EyeOutlined,EditOutlined,SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { FileExcelFilled } from "@ant-design/icons";
import { ColumnProps } from 'antd/lib/table';
import moment from 'moment';

/* eslint-disable-next-line */

export function OcaenFreightRatesView(
) {
    const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState<number>(100);
  const service = new OcaenFreightRateService()
  const [data,setData] = useState<OcaenFreightRateRequest[]>([])
  const [searchText, setSearchText] = useState("");
const [searchedColumn, setSearchedColumn] = useState("");
const searchInput = useRef(null);

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

  const getInfo = () => {
      service.getAllOceanFreightRates().then(res => {
          if(res.status){
              setData(res.data)
          }
      })
  }

  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 :ColumnProps<any>[] = [
      {
          title: 'S No',
          key: 'sno',
          align:"center",
          // width:"60px",
          responsive: ['sm'],
          render: (text, object, index) => (page - 1) * pageSize + (index + 1) + (pageSize * (page - 1))
      },
      {
        // title:'Destination',
        title:<div style={{textAlign:"center"}}>Date</div>,
        dataIndex:'updatedAt',
        sorter: (a, b) => a.updatedAt.localeCompare(b.updatedAt),
        sortDirections: ["ascend", "descend"],
        render: (value, record) => {
          return moment(record.updatedAt).format('DD-MM-YYYY');
      },
    },
      {
          // title:'Destination',
          title:<div style={{textAlign:"center"}}>Destination</div>,
          dataIndex:'destination',
          sorter: (a, b) => a.destination.localeCompare(b.destination),
          sortDirections: ["ascend", "descend"],
          render: (text,val) => val.destination ? val.destination : "-",

          ...getColumnSearchProps('destination') 
      },
     
      {
        // title:'Destination',
        title:<div style={{textAlign:"center"}}>Country</div>,
        dataIndex:'country',
        sorter: (a, b) => a.country.localeCompare(b.country),
        sortDirections: ["ascend", "descend"],
        render: (text,val) => val.country ? val.country : "-",
        ...getColumnSearchProps('country') ,
      
    },  {
        // title:'Destination',
        title:<div style={{textAlign:"center"}}>Liner</div>,
        dataIndex:'liner',
        sorter: (a, b) => a.liner.localeCompare(b.liner),
        sortDirections: ["ascend", "descend"],
        render: (text,val) => val.liner ? val.liner : "-",
        ...getColumnSearchProps('liner') ,
      
    },  {
        // title:'Destination',
        title:<div style={{textAlign:"center"}}>Basic Price</div>,
        dataIndex:'basicPrice',
        align:'right',
        render: (text,val) => val.basicPrice ? val.basicPrice : "-",
    },  {
        // title:'Destination',
        title:<div style={{textAlign:"center"}}>Other Charge</div>,
        dataIndex:'otherCharge',
        align:'right',
        render: (text,val) => val.otherCharge ? val.otherCharge : "-",
    },
    
    {
      title:<div style={{textAlign:"center"}}>Total</div>,
      align:'right',
      dataIndex:'total',
  },
  ]

  let i = 1;
  let rowIndex = 1;
  const exceldata = [
    { title: 'S No', dataIndex: 'sNo', render: (text, object, index) => { 
         return index+1
      },
      width: 60, 
     
    },
    { title: 'Destination', dataIndex: 'destination',width: 100,render:(text:any,record:any) => {return record.destination ? record.destination : '-'} },  
    { title: 'Country', dataIndex: 'country',width: 100,render:(text:any,record:any) => {return record.country ? record.country : '-'} },  
    { title: 'Liner', dataIndex: 'liner',width: 500,render:(text:any,record:any) => {return record.liner ? record.liner : '-'} },     
    { title: 'BasicPrice', dataIndex: 'basicPrice',width: 100,render:(text:any,record:any) => {return record.basicPrice ? record.basicPrice : '-'} },  
    { title: 'OtherCharge', dataIndex: 'otherCharge',width: 100,render:(text:any,record:any) => {return record.otherCharge ? record.otherCharge : '-'} },
    { title: 'Total', dataIndex: 'total',width: 100,render:(text:any,record:any) => {return record.total ? record.total : '-'} },

]




  const exportExcel = () => {
      const excel = new Excel();
      excel
        .addSheet('Ocean Freight Rates Excel')
        .addColumns(exceldata)
        .addDataSource(data, { str2num: false })
        .saveAs('Ocean Freight Rates.xlsx');
    }
  return(
      <Card title={<span style={{color:'white'}}>Ocean Freight Rates</span>} 
      size='small'
        style={{color:'white',textAlign:'center'}} 
        headStyle={{ backgroundColor: "#69c0ff", border: 0 }}
       extra={<Link to='/ocaen-freight-rates-excel-upload' >
      <span style={{color:'white'}} ><Button className="panel_button" >New</Button> </span>
      </Link>}
      >
          <Row justify={'end'}>
          <Button
              type="default"
              style={{ color: "green",padding:5 }}
              onClick={exportExcel}
              icon={<FileExcelFilled />}
          >
              Download Excel
          </Button>
          </Row>
          <Table className="custom-table-wrapper" columns={columns} dataSource={data} size='small'
          pagination={{
              pageSize: 100, 
              onChange(current, pageSize) {
                  setPage(current);
                  setPageSize(pageSize);
              }
          }}
          />
      </Card>
  ) 
}

export default OcaenFreightRatesView;
