import { Link, useHistory } from "react-router-dom";
import React, { useState, useEffect, useRef } from 'react';
import { Divider, Form, Input, Button, Select, Card, Row, Col, Tooltip, Switch, Popconfirm, Drawer } from 'antd';
import Highlighter from 'react-highlight-words';
import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import './device-grid.css';
import Table, { ColumnProps } from "antd/lib/table";
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { DevicesServices } from '@gtpl/shared-services/canteen-management';
import { DevicesDto } from "@gtpl/shared-models/canteen-management";

/* eslint-disable-next-line */
export interface DeviceGridProps { viewDevices: (model: DevicesDto, viewOnly: boolean) => void; }

export function DeviceGrid(
  props: DeviceGridProps
) {
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [drawerVisible, setDrawerVisible] = useState(false);
  const searchInput = useRef(null);
  const [page, setPage] = React.useState(1);
  const service = new DevicesServices();
  const [deviceData, setDeviceData] = useState<any[]>([]);
  const [selectedDeviceData, setSelectedDeviceData] = useState<any>(undefined);

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

  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

  });

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

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

  const closeDrawer = () => {
    setDrawerVisible(false);
  }

  const getAllDevices = () => {
    service.getAllDevices().then(res => {
      if (res.status) {
        setDeviceData(res.data);
      } else {
        AlertMessages.getErrorMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setDeviceData([]);
    })
  }

  const deleteDevice = (values: DevicesDto) => {
    service.deleteDevices(values).then(res => {
      if (res.status) {
        // setDeviceData(res.data);
        getAllDevices()
      } else {
        AlertMessages.getErrorMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      // setDeviceData([]);
    })
  }
  console.log(deviceData)
  const columnsSkelton: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'Device Code',
      dataIndex: 'deviceCode',
      sorter: (a, b) => a.deviceCode.localeCompare(b.deviceCode),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('deviceCode')
    },
    {
      title: 'Device Name',
      dataIndex: 'deviceName',
      sorter: (a, b) => a.deviceName.localeCompare(b.deviceName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('deviceName')
    },
    // {
    //   title: 'Description',
    //   dataIndex: 'description',
    //   sorter: (a, b) => a.description.localeCompare(b.description),
    //   sortDirections: ['descend', 'ascend'],
    //   ...getColumnSearchProps('description')
    // },
    {
      title: `Action`,
      dataIndex: 'action',
      width: '170px',
      render: (text, rowData) => (
        <span>
          {/* <Tooltip placement="top" title={"view"}>
            <EyeOutlined  className={'viewSampleTypeIcon'} type="eye" onClick={() => {
            }}
              style={{ color: "#1890ff", fontSize: '24px' }} />
          </Tooltip> */}
          {/* <Divider type="vertical" />
          <Divider type="vertical" /> */}
          <Popconfirm onConfirm={e => { deleteDevice(rowData); }}
            title={'Are you sure to Delete device ?'}

          >
            <Tooltip placement="top" title={"Delete"}>
              <DeleteOutlined className={'deleteSampleTypeIcon'} type="delete" onClick={() => { }} style={{ color: "#ff0000", fontSize: '24px' }} />
            </Tooltip>
          </Popconfirm>
        </span>
      )
    }
  ];
  const onChange = (pagination, filters, sorter, extra) => {
    console.log('params', pagination, filters, sorter, extra);
  }
  return (
    <Card title={<span style={{ color: 'white' }}>Device</span>}
      style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
      extra={<Link to='/device-form' ><span style={{ color: 'white' }} ><Button className='panel_button' >Create </Button> </span></Link>} >
      <Card >
        <Table
          rowKey={record => record.freebiesId}
          columns={columnsSkelton}
          dataSource={deviceData}
          pagination={{
            onChange(current) {
              setPage(current);
            }
          }}
          scroll={{ x: true }}
          onChange={onChange}
          bordered />
      </Card>
    </Card>
  );
}

export default DeviceGrid;
