import React, { useState, useEffect, useRef } from 'react';
import {  Divider, Table, Popconfirm, Card, Tooltip, Switch,Input,Button, Radio, Col, } from 'antd';
import Highlighter from 'react-highlight-words';
import { EmployeeDto } from '@gtpl/shared-models/gtpl';
import { ColumnProps } from 'antd/lib/table';
import './employee-termination-grid.css';
import {RightSquareOutlined,EyeOutlined,EditOutlined,SearchOutlined} from '@ant-design/icons';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';

/* eslint-disable-next-line */
export interface EmployeeTerminationGridProps {
  EmployeeData: EmployeeDto[];
  terminateEmployee: (Employee: EmployeeDto,val:string) => void;
  terminateEmployees: (Employee: EmployeeDto[],val:string) => void;
}

export function EmployeeTerminationGrid(props: EmployeeTerminationGridProps) {
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [btnDisable, setBtnDisable] = useState<boolean>(true);
  const [selectedEmployees, setSelectedEmployees] = useState<EmployeeDto[]>([]);
  const searchInput = useRef(null);
  const [userRole,setUserRole]=useState<string>(JSON.parse(localStorage.getItem('role')));
  const options = [
    { label: 'Yes', value: true },
    { label: 'No', value: false },
  ];
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(selectedRowKeys)
      console.log(selectedRows)
      if(selectedRows.length>0){
        setBtnDisable(false);
        setSelectedEmployees(selectedRows);
      }
    },
  };
  const getColumnSearchProps = dataIndex => ({ 
    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) {
    let selectedKey = selectedKeys[0];
    if(selectedKeys[0] === "No"){
      selectedKey = false;
    }
    else if(selectedKeys[0] === "Yes"){
      selectedKey = true;
    }
    console.log(selectedKey);
    confirm();
    setSearchText(selectedKey);
    setSearchedColumn(dataIndex);
  };

  function handleReset(clearFilters) {
    clearFilters();
    setSearchText('');
  };
  const sampleTypeColumns: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      render: (text, object, index) => index+1
    
    },
    
    {
      title: 'Employee Code',
      dataIndex: 'empCode',
      ...getColumnSearchProps('empCode')
    },
    {
      title: 'Employee Name',
      dataIndex: 'empName',
      ...getColumnSearchProps('empName')
    },
    {
      title: 'Project Name',
      dataIndex: 'projectName',
      ...getColumnSearchProps('projectName')
    },
    {
      title: 'Sub Contractor',
      dataIndex: 'subContractorName',
      ...getColumnSearchProps('subContractorName'),
      render: (value,rowData) =>( <>
       {value?value:'-'}
      </>)
    },
    {
      title: 'Is Termination Approved',
      dataIndex: 'isTerminationApproved',
      // ...getColumnSearchProps('isTerminationApproved'),
      render: (text, rowData) => (<>{rowData.isTerminationApproved===true?'Yes':'No'}</>),
      filters: [
        {
          text: 'Yes',
          value: true,
        },
        {
          text: 'No',
          value: false,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => 
      {
        console.log(typeof value) // the result is string
        // === is not work
        return record.isTerminationApproved === value;
      },
    },
    {
      title: 'Is Terminated',
      dataIndex: 'isTerminated',
      // ...getColumnSearchProps('isTerminated'),
      render: (text, rowData) => (<>{rowData.isTerminated===true?'Yes':'No'}</>),
      filters: [
        {
          text: 'Yes',
          value: true,
        },
        {
          text: 'No',
          value: false,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => 
      {
        console.log(typeof value) // the result is string
        // === is not work
        return record.isTerminated === value;
      },
    },
    
    {
      title:`Terminated?`,
      dataIndex: 'Id',
      render: (text, record,index) => ( 
        <Radio.Group
          defaultValue={record.isTerminated===true?true:false}
          // disabled={record.isTerminated===true && userRole==='L4'}
          options={options}
          onChange={(e)=>props.terminateEmployee(record,e.target.value)}
          value={record.attenStatus}
          optionType="button"
          buttonStyle="solid"  
          style={{ display: 'flex' }}
          size='middle'   />
      ),
    }
  ];
  function onChange(pagination, filters, sorter, extra) {
    console.log('params', pagination, filters, sorter, extra);
  }
  const handleTermination = () => {
    console.log(selectedEmployees);
    props.terminateEmployees(selectedEmployees,"");
  };
  return (
    <><Col span={3}>
      <Button type="primary" block disabled={btnDisable} htmlType="submit" onClick={handleTermination}>
        Terminate
      </Button>
    </Col><Table
        rowSelection={{
          ...rowSelection
        }}
        rowKey={record => record.Id}
        columns={sampleTypeColumns}
        dataSource={props.EmployeeData}
        onChange={onChange}
        bordered /></>
  );
}

export default EmployeeTerminationGrid;
