import { HrmsEmployeeDetailsDto, HrmsEmployeeRequest } from "@gtpl/shared-models/masters";
import { HrmsEmpDetService } from "@gtpl/shared-services/masters";
import { Button, Card, Col, Form, Input, Row, Select } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import Table, { ColumnProps } from "antd/lib/table";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import moment from "moment";
import { Excel } from "antd-table-saveas-excel";

export interface EmployeeReportProps {
  viewReport: (Report: HrmsEmployeeDetailsDto, viewOnly: boolean) => void;
}

export function EmployeeReport(
  props: EmployeeReportProps
) {
  const [page, setPage] = React.useState(1); 
  const searchInput = useRef(null);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [disable, setDisable] = useState<boolean>(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const { Option } = Select;
  const [empData, setEmpData] = useState<HrmsEmployeeDetailsDto[]>([]);
  const [reportData, setReportData] = useState<any[]>([]);
  const service = new HrmsEmpDetService()

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

  useEffect(() => {
    getAllActiveEmployees();
    // getActiveEmployeesById();
  }, []);

  const getAllActiveEmployees = () => {
    service.getAllActiveEmployees().then((res) => {
      if (res.status) {
        console.log(res.data)
        setEmpData(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
        setEmpData([]);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setEmpData([]);
    })
  }

  // const getActiveEmployeesById = (onReset?: boolean) => {
  //   setDisable(true);
  //   setLoading(true);
  //   let employeeId = form.getFieldValue('employeeId');
  //   const req = new HrmsEmployeeRequest(employeeId);
  //   service.getActiveEmployeesById(req).then(res => {
  //     setDisable(false)
  //     if (res.status) {
  //       setReportData(res.data)
  //       setLoading(false);
  //       AlertMessages.getSuccessMessage(res.internalMessage);
  //     } else {
  //       if (res.intlCode) {
  //         setLoading(false);
  //         setDisable(false);
  //         setReportData([]);
  //       } else {
  //         setLoading(false);
  //       }
  //     }
  //   }).catch(err => {
  //     setReportData([]);
  //     AlertMessages.getErrorMessage(err.message);
  //   })
  // }


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

  const columns: ColumnProps<any>[] = [
    {
      title: 'S No',
      dataIndex: 'sNo',
      width: '70px',
      fixed: 'left',
      align: 'center',
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },

    {
      title: 'Employee Type',
      dataIndex: 'employeeType',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.employeeType?.localeCompare(b.employeeType),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('employeeType'),
      
    },

    {
      title: 'Employee Code',
      dataIndex: 'employeeCode',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.employeeCode?.localeCompare(b.employeeCode),
      sortDirections: ['descend', 'ascend'],
      
    },
    {
      title: 'Employee Name',
      dataIndex: 'employeeName',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.employeeName?.localeCompare(b.employeeName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('employeeName'),
      
    },
    {
      title: 'Date Of Joining',
      dataIndex: 'dateOfJoining',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.dateOfJoining?.localeCompare(b.dateOfJoining),
      sortDirections: ['descend', 'ascend'], 
      render: (value, record) => {
        return <span>
          {record.dateOfJoining ? moment(record.dateOfJoining).format('YYYY-MM-DD') : '-'}
        </span>
    },
  },

    {
      title: 'Department',
      dataIndex: 'department',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.department?.localeCompare(b.department),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('department'),
      
    },
    {
      title: 'Designation',
      dataIndex: 'designation',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.designation?.localeCompare(b.designation),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('designation'),
      
    },
    {
      title: 'Designation',
      dataIndex: 'designation',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.designation?.localeCompare(b.designation),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('designation'),
      
    },
    {
      title: 'Status',
      dataIndex: 'status',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.status?.localeCompare(b.status),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('status'),
      
    },
    {
      title: 'Experience',
      dataIndex: 'experience',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.experience?.localeCompare(b.experience),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('experience'),
      
    },

    {
      title: 'Employee Role',
      dataIndex: 'employeeRole',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.employeeRole?.localeCompare(b.employeeRole),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('employeeRole'),
      
    },
    {
      title: 'Employee Status',
      dataIndex: 'employeeStatus',
      width: '150px',
      fixed: 'left',
      align: 'center',
      sorter: (a, b) => a.employeeStatus?.localeCompare(b.employeeStatus),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('employeeStatus'),
      
    },

  ];
  
  const exportedData = [];
  console.log(exportedData)
  const excelData = empData
  let i=1;
  const data = [
    {title: 'S No', dataIndex: 'sNo',render: (text, object, index) => { return i++; }},
    {title: 'Employee Code', dataIndex: 'employeeCode'},
    {title: 'Employee Name', dataIndex: 'employeeName'},
    {title: 'Date Of Joining', dataIndex: 'dateOfJoining',render:(text,record)=>{return moment(record.date).format('YYYY-MM-DD')}},
    {title: 'Department', dataIndex: 'department'},
    {title: 'Designation', dataIndex: 'designation'},
    {title: 'Status', dataIndex: 'status'},
    {title: 'Experience', dataIndex: 'experience'},
    {title: 'Employee Role', dataIndex: 'employeeRole'},
    {title: 'Employee Status', dataIndex: 'employeestatus'},
  ];

  const exportExcel = () => {
    const excel = new Excel();
    excel
      .addSheet('employee')
      .addColumns(data)
      .addDataSource(reportData, { str2num: true })
      .saveAs('Employee-Report.xlsx');
  }

  const onReset = () => {
    form.resetFields();
    setEmpData([]);
  }

  return(

    <Card
    title={<span style={{ color: 'white' }}>Employee Report</span>}extra={<Button onClick={() => { exportExcel(); }}>Get Excel</Button>}
    style={{ textAlign: 'center' }}
    headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
  >

  <Form layout={"vertical"} form={form} >
  <Row gutter={[24, 24]}>
  <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
            <Form.Item
              name="employeeCode"
              label="Employee Name"
              rules={[
                {
                  required: false,
                  message: "Enter valid Employee Name"
                },
                // {

                //   pattern: /^[^-\s\\0-9\[\]()*!@#$^&_\-+/%=`~{}:";'<>,.?|][a-zA-Z ]*$/,
                //   message: `Should contain only alphabets.`
                // }
              ]}>
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Employee Name"
                // onChange={}
                allowClear
                style={{ width: '100%' }}
              >
                {empData?.map(dropData => {
                  return <Option key={dropData.employeeId} value={dropData.employeeCode}>{dropData.employeeName}</Option>;
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col style={{ padding: '20px', marginTop: '30px' }}>
            <Button type="primary" style={{ marginRight: '4px' }} disabled={disable} onClick={() => getAllActiveEmployees()}>
              Get Report
            </Button>
            <Button style={{ marginLeft: '5px' }} type="primary" htmlType="submit" onClick={onReset}> Reset </Button>
          </Col>
</Row>
</Form>
<Table
        columns={columns}
        dataSource={empData}
        scroll={{ x: 1500, y: 500 }}
        bordered
        pagination={{
          onChange(current) {
            setPage(current);
          }
        }}
        onChange={onChange}
      />
  </Card>
  );
}

export default EmployeeReport;
