
import React, { useContext, useEffect, useRef, useState } from 'react';
import { ColumnProps } from 'antd/lib/table';
import { CheckCircleOutlined,FileExcelFilled, EditOutlined, RightSquareOutlined, SearchOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Divider, Row, Col, Table, Drawer, Popconfirm, Switch, Tag, Input, Button, Card, Form, Tooltip } 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 {  RmPriceListDto } from '@gtpl/shared-models/masters';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import {  RmPriceListService } from '@gtpl/shared-services/masters';
import { RmCountPriceListDto } from '@gtpl/shared-models/raw-material-procurement';
import { RmCountPriceListService } from '@gtpl/shared-services/raw-material-procurement';

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

export function RmCountPriceListGrid(
  props: RmCountPriceListGridProps
) {
  const [page, setPage] = React.useState(1);
  const searchInput = useRef(null);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [rmPriceListData, setRmPriceListData] = useState<RmCountPriceListDto[]>([]);
  const services = new RmCountPriceListService();
  const [data,setData] = useState<any[]>([])


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



  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 getInfo=()=>{
  services.getRmCountPriceListInfo().then(res=>{
    if(res.status){
      setData(res.data)
    }
  })
 }
  // const updateRmCountPriceList = (Data: RmCountPriceListDto) => {
  //   services.update(Data).then(res => {
  //     console.log(res);
  //     if (res.status) {
  //       AlertMessages.getSuccessMessage('Updated Successfully');
  //       getAll();
  //       setDrawerVisible(false);
  //     } else {
  //       if (res.intlCode) {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //       } else {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //       }
  //     }
  //   }).catch(err => {
  //     AlertMessages.getErrorMessage(err.message);
  //   })
  // }


  // const deleteRmCountPriceList = (Data: RmCountPriceListDto) => {
  //   Data.isActive = Data.isActive ? false : true;
  //   services.activatedeActivate(Data).then(res => {
  //     console.log(res);
  //     if (res.status) {
  //       getAll();
  //       AlertMessages.getSuccessMessage('Success');
  //     } else {
  //       if (res.intlCode) {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //       } else {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //       }
  //     }
  //   }).catch(err => {
  //     AlertMessages.getErrorMessage(err.message);
  //   })
  // }

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

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

  // const addRowData = (index) => {
  //   const newRowData = new RmCountPriceListDto(0,0,0,true,'',new Date(),'',1,new Date(),'');
  //   const newTable = [...rmPriceListData];
  //   newTable.splice(index+1, 0, newRowData);
  //   setRmPriceListData(newTable);
  // }

  const columnsSkelton: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'Effective From',
      dataIndex: 'effectiveFromDate',
      render: (value, record) => {
        return moment(record.effectiveFromDate).format('DD-MM-YYYY');
    },
      sorter: (a, b) => a.effectiveFromDate.localeCompare(b.effectiveFromDate),
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'Effective To',
      dataIndex: 'effectiveToDate',
      render: (value, record) => {
        return record.effectiveToDate ? moment(record.effectiveToDate).format('DD-MM-YYYY') : '-';
      },
      sorter: (a, b) => {
        const dateA = a.effectiveToDate ? new Date(a.effectiveToDate) : new Date(0); 
        const dateB = b.effectiveToDate ? new Date(b.effectiveToDate) : new Date(0);
        return dateA.getTime() - dateB.getTime();
      },
      sortDirections: ['descend', 'ascend'],
    },
    
  //   {
  //     // title:'Destination',
  //     title:<div style={{textAlign:"center"}}>Min Count</div>,
  //     dataIndex: 'minValue',
  //     sorter: (a, b) => a.minValue.localeCompare(b.minValue),
  //     sortDirections: ["ascend", "descend"],
  //     render: (text) => text ? text : "-",
  //     ...getColumnSearchProps('minValue') 
  // },
 
   
    {
      title: 'Company',
      dataIndex: 'company',
      //  responsive: ['lg'],
      sorter: (a, b) => a.company.localeCompare(b.company),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('company')
    },

  {
    title: 'Count',
    dataIndex: 'count',
    sorter: (a, b) => {
      if (a.count && b.count) {
        const countA = parseInt(a.count);
        const countB = parseInt(b.count);
        return countA - countB;
      }
      return 0;
    },
    sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('count')
  },

   {
      title: 'Price',
      dataIndex: 'price',
      // responsive: ['lg'],
      // sorter: (a, b) => a.price?.localeCompare(b.price),
      // sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('price')
    },
      
  {
    title: 'Type',
    dataIndex: 'type',
    sorter: (a, b) => a.type?.localeCompare(b.type),
    sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('type')
  },  
  // {
  //   title: 'Company',
  //   dataIndex: 'company',
  //   sorter: (a, b) => a.company?.localeCompare(b.company),
  //   sortDirections: ['descend', 'ascend'],
  //   ...getColumnSearchProps('company')
  // },
  ];
  const exceldata = [
    { title: 'S No', dataIndex: 'sNo', render: (text, object, index) => { 
        if(index == data.length) { 
          return null;
        } else { 
          return index+1
        } 
      },
      width: 60, 
     
    }, 

    // { title: 'Min Value', dataIndex: 'minValue',width: 100,render:(text:any,record:any) => {return record.minValue ? record.minValue : '-'} },  
    // { title: 'Max Value', dataIndex: 'maxValue',width: 100,render:(text:any,record:any) => {return record.maxValue ? record.maxValue : '-'} },
    { title: 'Count', dataIndex: 'count',width: 500,render:(text:any,record:any) => {return record.count ? record.count : '-'} },     
    { title: 'Price', dataIndex: 'price',width: 100,render:(text:any,record:any) => {return record.price ? record.price : '-'} },
    { title: 'Company', dataIndex: 'company',width: 100,render:(text:any,record:any) => {return record.company ? record.company : '-'} },
    { title: 'Type', dataIndex: 'type',width: 100,render:(text:any,record:any) => {return record.type ? record.type : '-'} },
  ]
  const onChange = (pagination, filters, sorter, extra) => {
    console.log('params', pagination, filters, sorter, extra);
  }

  const exportExcel = () => {
    const excel = new Excel();
    excel
      .addSheet('Peeling Excel')
      .addColumns(exceldata)
      .addDataSource(data, { str2num: false })
      .saveAs('Rm count PriceList.xlsx');
  }

  
  return (
    <Card title={<span style={{ color: 'white' }}>Rm Count PriceList</span>}
      style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }} 
      extra={<Link to="/rm-count-pricelist-form"  ><span style={{ color: 'white' }} ><Button className='panel_button' >Upload File </Button> </span></Link>} >
      <br></br>
      <Row justify={'end'}>
            <Button
                type="default"
                style={{ color: "green" }}
                onClick={exportExcel}
                icon={<FileExcelFilled />}
            >
                Download Excel
            </Button>
            </Row>
      <Table
        // rowKey={record => record.rmPriceListId}
        columns={columnsSkelton}
        dataSource={data}
        pagination={{
          onChange(current) {
            setPage(current);
          }
        }}
        onChange={onChange}
        // scroll={{ x: true }}
        bordered />
      
    </Card>
  );
}

export default RmCountPriceListGrid;


