import React, { useEffect, useRef, useState } from 'react';
import {SaleOrderService} from '@gtpl/shared-services/sale-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import Highlighter from 'react-highlight-words';
import './procurement-dashboard.css';
import { Divider, Table, Popconfirm, Card, Tooltip, Switch, Input, Button, Tag, Row, Col, Drawer, Tabs } from 'antd';
import { Link, Redirect, Route } from 'react-router-dom';
import { RmBomDto } from '@gtpl/shared-models/sale-management';
import { ColumnProps } from 'antd/lib/table';
import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons';
import { RmBomData } from 'libs/shared-models/sale-management/src/lib/bom/rmBomData';
import { RMFiltersRequest } from '@gtpl/shared-models/raw-material-procurement';


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

export function ProcurementDashboard(
  props: ProcurementDashboardProps
) {
  const [page, setPage] = React.useState(1);
  const { TabPane } = Tabs;
  const saleService = new SaleOrderService;
  const [bomData,setBomData] = useState<RmBomData>(null)
  const [searchText, setSearchText] = useState(''); 
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);


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

  // useEffect(()=>{
  //   console.log(bomData);
  // },[bomData])

  const getRmBomData = () => {
    saleService.getRmBomData(new RMFiltersRequest(0,0,'')).then(res => {
      if (res.status) {
        setBomData(res.data);
      } else {
        if (res.intlCode) {
          setBomData(null);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setBomData(null);
      AlertMessages.getErrorMessage(err.message);
    })
  }

  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(),100);   }
    },
    render: text =>
      text ?(
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text.toString()}
        />
        // searchText
      ) :text
      )
      : null
     
  });

  

  /* used for column filter
  * @param dataIndex column data index
  */
 
  const columnsSkelton: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      responsive: ['sm'],

      width: '70px',
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'Product',
      dataIndex: 'productName',
      key:'productName',
      sorter: (a, b) => a.productName-b.productName,
      sortDirections: ['descend', 'ascend'],
      render: (value, record: RmBomDto, index) => {
        return (record.productName) ? record.productName: '';
      },
      ...getColumnSearchProps('productName'),
    },
    
    {
      title: 'Country',
      dataIndex: 'countryName',
      sorter: (a, b) => a.countryName - b.countryName,
      sortDirections: ['descend', 'ascend'],
      render: (value, record: RmBomDto, index) => {
        return (record.countryName) ? record.countryName : '';
      },
      ...getColumnSearchProps('countryName'),
    },
    {
      title: 'Certification',
      dataIndex: 'certification',
      sorter: (a, b) => a.certification-b.certification,
      render: (value, record: RmBomDto, index) => {
        return (record.certification) ? record.certification : '';
      },
      ...getColumnSearchProps('certification'),
    },
    {
      title: 'Rating',
      dataIndex: 'rating',
      sorter: (a, b) => a.rating-b.rating,
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('rating'),
      
    },
    {
      title: 'Count',
      dataIndex: 'count',
      sorter: (a, b) => a.count-b.count,
      sortDirections: ['descend', 'ascend'],
      render: (value, record: RmBomDto, index) => {
        return record.count;
      },
      ...getColumnSearchProps('count'),
    },
    {
      title: 'Required quantity',
      dataIndex: 'requiredQuantity',
      sorter: (a, b) => a.requiredQuantity - b.requiredQuantity,
      sortDirections: ['descend', 'ascend'],
      render: (value, record: RmBomDto, index) => {
        return <div>{`${record.requiredQuantity}`}</div>
      }
    },
    {
      title: 'Indent Quantity',
      dataIndex: 'indentQuantity',
      sortDirections: ['descend', 'ascend'],
      render: (value, record: RmBomDto, index) => {
        return <div>{`${record.indentQuantity}`}</div>
      }
    },

    
  ];

   /**
   * 
   * @param pagination 
   * @param filters 
   * @param sorter 
   * @param extra 
   */
    const onChange = (pagination, filters, sorter, extra) => {
      console.log('params', pagination, filters, sorter, extra);
    }

  return (

    <Card title={<span style={{color:'white'}}>Requisition Info</span>}
style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }}  >
        <br></br>
        <br></br>
      {/* <Row gutter={40}>
        <Col>
          <Card title={'Total GRN: ' + grnData.length} style={{ textAlign: 'left', width: 200, height: 41, backgroundColor: '#bfbfbf' }}></Card>
        </Col>
        </Row> */}
      <Row gutter={40}>
 <br></br>
  
      </Row>
      <br></br>
      <Tabs type={'card'} tabPosition={'top'}>
      <TabPane 
      // tab="Open Orders"
       key="1"
       tab={<span style={{ color: "green" }}>{"0-7 Days: " + (bomData?bomData.zeroToSevenDays:0)}</span>}
       style={{ color: "#363636" }}
       >
      <Table
        rowKey={record => record.bomId}
        columns={columnsSkelton}
        // dataSource={bomData?.zeroToSevenDays}
        pagination={{
          onChange(current) {
            setPage(current);
          }
        }}
        onChange={onChange}
        bordered
      scroll={{ x:true }}
      />
      {/* } */}
      </TabPane>
      <TabPane 
      // tab="Open Orders"
       key="2"
       tab={<span style={{ color: "#096dd9" }}>{"8-15 Days: " + (bomData?.sevenToFourteenDays)}</span>}
       style={{ color: "#363636"}}
       >
      <Table
        rowKey={record => record.bomId}
        columns={columnsSkelton}
        // dataSource={bomData?.sevenToFourteenDays}
        pagination={{
          onChange(current) {
            setPage(current);
          }
        }}
        onChange={onChange}
        bordered
      scroll={{ x:500 }}
      />
      {/* } */}
      </TabPane>
      <TabPane 
      // tab="Open Orders"
       key="3"
       tab={<span style={{ color: "#096dd9" }}>{"16-30 Days: " + (bomData?.fifteenToThirtyDays)}</span>}
       style={{ color: "#363636"}}
       >
      <Table
        rowKey={record => record.bomId}
        columns={columnsSkelton}
        // dataSource={bomData?.fifteenToThirtyDays}
        pagination={{
          onChange(current) {
            setPage(current);
          }
        }}
        onChange={onChange}
        bordered
      scroll={{ x:500 }}
      />
      {/* } */}
      </TabPane>
      <TabPane 
      // tab="Open Orders"
       key="4"
       tab={<span style={{ color: "red" }}>{" Above 30 Days: " + (bomData?.aboveThirtyDays)}</span>}
       style={{ color: "#363636"}}
       >
      <Table
        rowKey={record => record.bomId}
        columns={columnsSkelton}
        // dataSource={bomData?.aboveThirtyDays}
        pagination={{
          onChange(current) {
            setPage(current);
          }
        }}
        onChange={onChange}
        bordered
      scroll={{ x:true }}
      />
      {/* } */}
      </TabPane>
      </Tabs>


      <br></br>
      <Row gutter={40}>
        
      </Row>
      <br />
      <br />
      <br />

    </Card>
  );
}


<style>
  
  </style>

export default ProcurementDashboard;

