import React, { useContext, useEffect, useRef, useState } from 'react';
import { ColumnProps } from 'antd/lib/table';
import { SearchOutlined, UndoOutlined, FileExcelFilled } from '@ant-design/icons';
import { Row, Col, Table,Input, Button, Card, Form,message, Select } from 'antd';
import { Link } from 'react-router-dom';
import {Excel} from 'antd-table-saveas-excel'
import Highlighter from 'react-highlight-words';
import moment from 'moment';
import { DeheadingFilterReq, DeheadingPeelingRequest } from '@gtpl/shared-models/masters';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { DeheadingRatesService } from 'libs/shared-services/masters/src/lib/deheading-rates.service';


const DeheadingRatesGrid = () => {

const searchInput = useRef(null);
const {Option} = Select
const [page, setPage] = React.useState(1);
const service = new DeheadingRatesService()
const [data,setData] = useState<any[]>([])
const [searchText, setSearchText] = useState('');
const [searchedColumn, setSearchedColumn] = useState('');

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


const getAllDegeadingRatesData=() =>{
  service.getAllDegeadingRatesData().then(res=>{
    if(res.status){
      setData(res.data)
      message.success(res.internalMessage,1)
    }else{
      setData([])
      message.error(res.internalMessage,2)
    }
  })
  
}


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
    
      });

      
  function handleSearch(selectedKeys, confirm, dataIndex) {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  function handleReset(clearFilters) {
    clearFilters();
    setSearchText('');
  };

  const columnSkeltion:ColumnProps<any>[] =[
    {
        title: 'S No',
        key: 'sno',
        width: '70px',
        responsive: ['sm'],
        render: (text, object, index) => (page - 1) * 10 + (index + 1)
      },
      {
        title: 'Contractor Name',
        dataIndex: 'conractorName',
        // responsive: ['lg'],
        sorter: (a, b) => a.conractorName?.localeCompare(b.conractorName),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('conractorName'),
        render: (text: string) => text || '-'
    },
    {
        title: 'Count',
        dataIndex: 'count',
        // responsive: ['lg'],
        sorter: (a, b) => a.count?.localeCompare(b.count),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('count'),
        render: (text: string) => text || '-'
    },
    {
        title: 'rate',
        dataIndex: 'rate',
        // responsive: ['lg'],
        sorter: (a, b) => a.rate?.localeCompare(b.rate),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('rate'),
        render: (text: string) => text || '-'
    },
    {
        title: 'bill Type',
        dataIndex: 'billType',
        // responsive: ['lg'],
        // sorter: (a, b) => a.rate?.localeCompare(b.rate),
        // sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('billType'),
        render: (text: string) => text || '-'
    },
  ];

  const exceldata = [
    { title: 'S No', dataIndex: 'sNo', render: (text, object, index) => { 
        if(index == data.length) { 
          return null;
        } else { 
          return index+1
        } 
      },
      width: 60, 
    },
    { title: 'CONTRACTOR NAME', dataIndex: 'conractorName',width: 500,render:(text:any,record:any) => {return record.conractorName ? record.conractorName : '-'} },     
    { title: 'COUNT', dataIndex: 'count',width: 100,render:(text:any,record:any) => {return record.count ? record.count : '-'} },
    { title: 'RATE', dataIndex: 'rate',width: 100,render:(text:any,record:any) => {return record.rate ? record.rate : '-'} },
    { title: 'BILLTYPE', dataIndex: 'billType',width: 100,render:(text:any,record:any) => {return record.billType ? record.billType : '-'} },

  ]
  const onChange = (pagination, filters, sorter, extra) => {
    console.log('params', pagination, filters, sorter, extra);
  }

  const exportExcel = () => {
    const excel = new Excel();
    excel
      .addSheet('Deheading Rates Excel')
      .addColumns(exceldata)
      .addDataSource(data, { str2num: false })
      .saveAs('deheading Rates.xlsx');
  }

 
  return (
    <Card 
    title={<span style={{ color: 'white' }}>Deheading Rates</span>}
    style={{ textAlign: 'center' }} 
    headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    extra={
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
        <Link to="/deheading-rates">
          <Button className='panel_button'>Upload File</Button>
        </Link>
        <Button
          type="default"
          style={{ color: 'green' }}
          onClick={exportExcel}
          icon={<FileExcelFilled />}
        >
          Download Excel
        </Button>
      </div>
    }
  >
    <Table
      columns={columnSkeltion}
      dataSource={data}
      pagination={{
        onChange(current) {
          setPage(current);
        }
      }}
      onChange={onChange}
      bordered
    />
  </Card>
    
  )
}

export default DeheadingRatesGrid