import React, { useState, useEffect, useRef } from 'react';
import {  Divider, Popconfirm, Card, Tooltip, Switch,Input,Button,Space } from 'antd';
import Highlighter from 'react-highlight-words';
import {CaretRightOutlined , SearchOutlined, FilterOutlined} from '@ant-design/icons'
import { MonthwiseDto, MonthWiseAttendanceReport } from '@gtpl/shared-models/gtpl';
import { ColumnProps } from 'antd/lib/table';
import { FormattedMessage } from 'react-intl';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { useIntl } from 'react-intl';;
import { Table } from "ant-table-extensions";
import { CSVLink, CSVDownload } from "react-csv";
import './monthwise-report-grid.css';
import jsPDF from "jspdf";
import "jspdf-autotable";
import { format } from "date-fns";

/* eslint-disable-next-line */
export interface IMonthwiseReportGridProps  {

  // monthwiseData: MonthwiseDto;
  MonthwiseReportData: MonthWiseAttendanceReport[];
  viewMonthwiseReport: (MonthwiseReport: MonthWiseAttendanceReport, viewOnly: boolean) => void;
  // deleteMonthwiseReport: (MonthwiseReport: MonthwiseDto) => void;
}

export const MonthwiseReportGrid = (props: IMonthwiseReportGridProps)=> {
 
  
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const [page, setPage] = React.useState(1);
  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) {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  function handleReset(clearFilters) {
    clearFilters();
    setSearchText('');
  };
  
  const sampleTypeColumns: ColumnProps<any>[] = [
    {
      title:'S.No',
      dataIndex:'empId',
      width: 40,
      fixed: 'left',
      render: (text, object, index) => (page-1) * 10 +(index+1)
      
    },
    // {
    //   title: 'CostCenter Name',
    //   dataIndex: 'costCenterName',
    //   width: 110,
    //   ...getColumnSearchProps('costCenterName'),
    //   // render: (text, rowData) => (<>{rowData.costCenterName.costCenterId}</>),
    //   sorter: (a, b) => a.costCenterName.length - b.costCenterName.length,
    //   sortDirections: ['descend', 'ascend'],
    //   // fixed: 'left',
    // },
    {
      title: 'Employee Name',
      dataIndex: 'empName',
      fixed: 'left',
      width: 150,
      ...getColumnSearchProps('empName'),
      sorter: (a, b) => a.empName.length - b.empName.length,
      sortDirections: ['descend', 'ascend'],
        
    },
    {
      title: 'Designation',
      dataIndex: 'designation',
      width: 100,
      ...getColumnSearchProps('designation'),
      sorter: (a, b) => a.designation.length - b.designation.length,
      sortDirections: ['descend', 'ascend'],
      // fixed: 'left'
    },
    {
      title: 'Project Name',
      dataIndex: 'projectName',
      width: 100,
      ...getColumnSearchProps('projectName'),
      sorter: (a, b) => a.projectName.length - b.projectName.length,
      sortDirections: ['descend', 'ascend'],
      // fixed: 'left'
    },
    {
      title: 'Sub Contractor',
      dataIndex: 'subContractorName',
      width: 100,
      ...getColumnSearchProps('subContractorName'),
      sorter: (a, b) => a.subContractorName.length - b.subContractorName.length,
      sortDirections: ['descend', 'ascend'],
      render: (text, rowData) => (<>{rowData.subContractorName==null?'GTPL':rowData.subContractorName}</>)
      // fixed: 'left'
    },
    
    // {
    //   title: 'Employee Code',
    //   dataIndex: 'empCode',
    //   width: 100,
    //   render: (text, rowData) => (<>{rowData.empInfo.empCode}</>),
    //   sorter: (a, b) => a.empCode.length - b.empCode.length,
    //   sortDirections: ['descend', 'ascend'],
    //   // fixed: 'left',
    // },
    // {
    //   title: 'Day wise report',
    //   dataIndex: 'attenStatus',
    //   // fixed: 'center',
    //   children:[
    { title: '1', dataIndex: 'day1',width:35, key: '1',render: (text, rowData) => (<>{rowData.day1?rowData.day1:'N'}</>) },
    { title: '2', dataIndex: 'day2',width:35, key: '2',render: (text, rowData) => (<>{rowData.day2?rowData.day2:'N'}</>) },
    { title: '3', dataIndex: 'day3',width:35, key: '3',render: (text, rowData) => (<>{rowData.day3?rowData.day3:'N'}</>) },
    { title: '4', dataIndex: 'day4',width:35, key: '4',render: (text, rowData) => (<>{rowData.day4?rowData.day4:'N'}</>) },
    { title: '5', dataIndex: 'day5',width:35, key: '5',render: (text, rowData) => (<>{rowData.day5?rowData.day5:'N'}</>) },
    { title: '6', dataIndex: 'day6',width:35, key: '6',render: (text, rowData) => (<>{rowData.day6?rowData.day6:'N'}</>) },
    { title: '7', dataIndex: 'day7',width:35, key: '7',render: (text, rowData) => (<>{rowData.day7?rowData.day7:'N'}</>) },
    { title: '8', dataIndex: 'day8',width:35, key: '8',render: (text, rowData) => (<>{rowData.day8?rowData.day8:'N'}</>) },
    { title: '9', dataIndex: 'day9',width:35, key: '9',render: (text, rowData) => (<>{rowData.day9?rowData.day9:'N'}</>) },
    { title: '10', dataIndex: 'day10',width:35, key: '10',render: (text, rowData) => (<>{rowData.day10?rowData.day10:'N'}</>) },
    { title: '11', dataIndex: 'day11',width:35, key: '11',render: (text, rowData) => (<>{rowData.day11?rowData.day11:'N'}</>) },
    { title: '12', dataIndex: 'day12',width:35, key: '12',render: (text, rowData) => (<>{rowData.day12?rowData.day12:'N'}</>) },
    { title: '13', dataIndex: 'day13',width:35, key: '13',render: (text, rowData) => (<>{rowData.day13?rowData.day13:'N'}</>) },
    { title: '14', dataIndex: 'day14',width:35, key: '14',render: (text, rowData) => (<>{rowData.day14?rowData.day14:'N'}</>) },
    { title: '15', dataIndex: 'day15',width:35, key: '15',render: (text, rowData) => (<>{rowData.day15?rowData.day15:'N'}</>) },
    { title: '16', dataIndex: 'day16',width:35, key: '16',render: (text, rowData) => (<>{rowData.day16?rowData.day16:'N'}</>) },
    { title: '17', dataIndex: 'day17',width:35, key: '17',render: (text, rowData) => (<>{rowData.day17?rowData.day17:'N'}</>) },
    { title: '18', dataIndex: 'day18',width:35, key: '18',render: (text, rowData) => (<>{rowData.day18?rowData.day18:'N'}</>) },
    { title: '19', dataIndex: 'day19',width:35, key: '19',render: (text, rowData) => (<>{rowData.day19?rowData.day19:'N'}</>) },
    { title: '20', dataIndex: 'day20',width:35, key: '20',render: (text, rowData) => (<>{rowData.day20?rowData.day20:'N'}</>) },
    { title: '21', dataIndex: 'day21',width:35, key: '21',render: (text, rowData) => (<>{rowData.day21?rowData.day21:'N'}</>) },
    { title: '22', dataIndex: 'day22',width:35, key: '22',render: (text, rowData) => (<>{rowData.day22?rowData.day22:'N'}</>) },
    { title: '23', dataIndex: 'day23',width:35, key: '23',render: (text, rowData) => (<>{rowData.day23?rowData.day23:'N'}</>) },
    { title: '24', dataIndex: 'day24',width:35, key: '24',render: (text, rowData) => (<>{rowData.day24?rowData.day24:'N'}</>) },
    { title: '25', dataIndex: 'day25',width:35, key: '25',render: (text, rowData) => (<>{rowData.day25?rowData.day25:'N'}</>) },
    { title: '26', dataIndex: 'day26',width:35, key: '26',render: (text, rowData) => (<>{rowData.day26?rowData.day26:'N'}</>) },
    { title: '27', dataIndex: 'day27',width:35, key: '27',render: (text, rowData) => (<>{rowData.day27?rowData.day27:'N'}</>) },
    { title: '28', dataIndex: 'day28',width:35, key: '28',render: (text, rowData) => (<>{rowData.day28?rowData.day28:'N'}</>) },
    { title: '29', dataIndex: 'day29',width:35, key: '29',render: (text, rowData) => (<>{rowData.day29?rowData.day29:'N'}</>) },
    { title: '30', dataIndex: 'day30',width:35, key: '30',render: (text, rowData) => (<>{rowData.day30?rowData.day30:'N'}</>) },
    { title: '31', dataIndex: 'day31',width:35, key: '31',render: (text, rowData) => (<>{rowData.day31?rowData.day31:'N'}</>) },
    //   ]
    // },
    
    // {
    //   title: 'Worked on Sundays',
    //   dataIndex: 'PresentSundays',
    //   width: 100,
    //   // sorter: (a, b) => a.PresentSundays.length - b.PresentSundays.length,
    //   sortDirections: ['descend', 'ascend'],
    //   // fixed: 'right'
    // },
    // {
    //   title: 'Total Leaves',
    //   dataIndex: 'totalLeaves',
    //   width: 100,
    //   sorter: (a, b) => a.TotalLeaves.length - b.TotalLeaves.length,
    //   sortDirections: ['descend', 'ascend'],
    //   // fixed: 'right'
    // },
    {
      title: 'Total Present Days',
      dataIndex: 'totalPresents',
      fixed: 'right',
      width: 70,
      // sorter: (a, b) => a.totalPresents.length - b.totalPresents.length,
      sortDirections: ['descend', 'ascend'],
      render: (text, rowData) => (<>{rowData.totalPresents}</>)
      
    },
    // {
    //   title: 'Total Sundays',
    //   dataIndex: 'totalSundays',
    //   fixed: 'right',
    //   width: 100,
    //   sorter: (a, b) => a.totalSundays.length - b.totalSundays.length,
    //   sortDirections: ['descend', 'ascend'],
    //   render: (text, rowData) => (<>{rowData.totalSundays}</>)
      
    // },
    {
      title: 'Total Ot Hours',
      dataIndex: 'totalOtHours',
      fixed: 'right',
      width: 70,
      // sorter: (a, b) => a.totalOtHours.length - b.totalOtHours.length,
      sortDirections: ['descend', 'ascend'],
      // fixed: 'right'
      
    },
    {
      title: 'Total Absent Days',
      dataIndex: 'totalAbsents',
      fixed: 'right',
      width: 70,
      // sorter: (a, b) => a.totalPresents.length - b.totalPresents.length,
      // sortDirections: ['descend', 'ascend'],
      render: (text, rowData) => (<>{rowData.totalAbsents}</>)
      
    },
    {
      title: 'Total Sundays worked',
      dataIndex: 'presentSundays',
      fixed: 'right',
      width: 72,
      // sorter: (a, b) => a.totalPresents.length - b.totalPresents.length,
      // sortDirections: ['descend', 'ascend'],
      render: (text, rowData) => (<>{rowData.presentSundays}</>)
      
    },
  ] 
  const { jsPDF } = require("jspdf");
  require('jspdf-autotable');
  const generatePDF = data => {
    console.log(data);
    var doc = new jsPDF('p', 'mm', 'a1');
    const tableColumn = ["Employee Name","Designation","Project Name", "Sub Contractor", "1","2","3","4","5","6","7","8", "9","10","11","12","13","14","15","16","17","18", "19", "20",
    "21","22","23","24","25","26","27","28", "29", "30","31","Total Present Days", "Total Ot Hours", "Total Absent Days", "Total Sundays Worked"];
    const tableRows = [];
    data.forEach(attendance => {  console.log(attendance);
      const attendanceData = [
        attendance.empName,
        attendance.designation,
        attendance.projectName,
        attendance.subContractorName==null?'GTPL':attendance.subContractorName,
        attendance.day1?attendance.day1:'N',
        attendance.day2?attendance.day2:'N',
        attendance.day3?attendance.day3:'N',
        attendance.day4?attendance.day4:'N',
        attendance.day5?attendance.day5:'N',
        attendance.day6?attendance.day6:'N',
        attendance.day7?attendance.day7:'N',
        attendance.day8?attendance.day8:'N',
        attendance.day9?attendance.day9:'N',
        attendance.day10?attendance.day10:'N',
        attendance.day11?attendance.day11:'N',
        attendance.day12?attendance.day12:'N',
        attendance.day13?attendance.day13:'N',
        attendance.day14?attendance.day14:'N',
        attendance.day15?attendance.day15:'N',
        attendance.day16?attendance.day16:'N',
        attendance.day17?attendance.day17:'N',
        attendance.day18?attendance.day18:'N',
        attendance.day19?attendance.day19:'N',
        attendance.day20?attendance.day20:'N',
        attendance.day21?attendance.day21:'N',
        attendance.day22?attendance.day22:'N',
        attendance.day23?attendance.day23:'N',
        attendance.day24?attendance.day24:'N',
        attendance.day25?attendance.day25:'N',
        attendance.day26?attendance.day26:'N',
        attendance.day27?attendance.day27:'N',
        attendance.day28?attendance.day28:'N',
        attendance.day29?attendance.day29:'N',
        attendance.day30?attendance.day30:'N',
        attendance.day31?attendance.day31:'N',
        
        attendance.totalPresents,
        attendance.totalOtHours,
        attendance.totalAbsents,
        attendance.presentSundays,
      ];
      tableRows.push(attendanceData);
    });
    const selectedMonth = "Attandance Report for "+data[0].selectedMonth;
    doc.text(250, 15, selectedMonth);

    doc.autoTable(tableColumn, tableRows, {tableWidth: 'auto',
    columnStyles: {
      35: {columnWidth: 17}, 
      36: {columnWidth: 17}, 
      37: {columnWidth: 17}, 
      38: {columnWidth: 18}, 
    },
    theme: 'grid', margin:{ top:25}});
    doc.setFontSize(50);
    doc.save(`AttendanceReport.pdf`);
  };
  // const role = localStorage.getItem('role');
  const DowndloadTable = ({ data }) => ( 
    <CSVLink
        className="btn btn-primary"
        filename={"Attendance Register Report.csv"}
        data={data}
    >
        Export to CSV
    </CSVLink>
);
  return (
      <>
      <Space style={{ marginBottom: 16 }}>
        <Button onClick={() => generatePDF(props.MonthwiseReportData)}>Export to PDF</Button>
        </Space>
        {/* <Card bordered={false} style={{overflowX:'auto'}} extra={<Button onClick={() => generatePDF(props.MonthwiseReportData)}>Export to PDF</Button>} ></Card> */}
        <Space style={{ marginLeft: 16, marginBottom: 16}}>
        {((JSON.parse(localStorage.getItem('role'))==='L4')) &&
          <DowndloadTable data={props.MonthwiseReportData}/>
        }
        </Space>

        {/* <Button onClick={downloadExcel}>Export Excel Table</Button> */}
        <Table
        //  appendColumnFooterTop={true}
        
          rowKey={record => record.Id}
          columns={props.MonthwiseReportData.length>0?sampleTypeColumns:null}
          dataSource={props.MonthwiseReportData}
          pagination={{ onChange(current) {setPage(current);} }}
          scroll={{ y:500 }}
          size="small"
          bordered
          // {JSON.parse(localStorage.getItem('role')) }
          // exportable
          // exportableProps={{ /*showColumnPicker: true,*/fileName: "Attendance report" }} 
          >
        </Table>
      </>
    );
    
    
  // return (
  //   <Table
  //     rowKey={record => record.monthWiseId}
  //     columns={sampleTypeColumns}
  //     dataSource={props.MonthwiseReportData}
  //     scroll={{ x: 1300 }}
  //     size="small"
  //     bordered
  //   />
  // );
}

export default MonthwiseReportGrid;
