import { Button, Card, Col, DatePicker, Form, message, Row, Select, Table, TableColumnsType } from 'antd';
import React, { Children, useEffect, useState } from 'react';
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import moment from 'moment';
import dayjs from "dayjs";
import { PayrollProcessServices } from "@gtpl/shared-services/hrms";
import { PayRollRequest } from '@gtpl/shared-models/hrms';

import './pages-payroll-reports.css';
import { Excel } from 'antd-table-saveas-excel';

import './pages-payroll-reports.css';
import { IExcelColumn } from 'antd-table-saveas-excel/app';

/* eslint-disable-next-line */


export function PayrollInHouseReports() {
  const [page, setPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [form] = Form.useForm();
  const [data, setData] = useState<any[]>([]);
  const { Option } = Select;
  const [employeeName, setEmployeeName] = useState<any[]>([]);
  const service = new PayrollProcessServices()
  const [designationMapping, setDesignationMapping]= useState<any[]>([]);
  

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

  const getAllInHouseEmployeeNamePayrollLogs = () => {
    service.getAllInHouseEmployeeNamePayrollLogs().then((res) => {
      if (res.status) {
        setEmployeeName(res.data);
        const designationMap = res.data.map(emp => ({
          designation: emp.designation,
          designation_name: emp.designation_name
        }));
        setDesignationMapping(designationMap);
      }
    });
  };

  console.log(employeeName)

  console.log(designationMapping)


  const getPayrollAllData = () => {
    const PayrollMonth = form.getFieldValue('PayrollMonth');
    const department = form.getFieldValue('department');
    const employeeName = form.getFieldValue('employeeName');
    const req = new PayRollRequest(null, dayjs(PayrollMonth).startOf('month').format('YYYYMM'), department, employeeName);

    service.getPayrollAllData(req).then((res) => {
      const dataWithDeptName = res.data.map(item => ({
        ...item,
        designation_name: designationMapping.find(designation => designation.designation === item.designation)?.designation_name || '-'
      }));
      setData(dataWithDeptName);
      AlertMessages.getSuccessMessage("Data Retrived Sucessfully")
    })
      .catch((error) => {
        AlertMessages.getErrorMessage('Error fetching data: ' + error.message);
      });
  };

  console.log(data)

  const onReset = () => {
    form.resetFields();
    setData(null)
  };

  const columns: TableColumnsType<any> = [
    {
      title: 'S No',
      key: 'sNo',
      responsive: ['sm'],
      width: 70,
      fixed: "left",
      render: (text, object, index) => (page - 1) * pageSize + (index + 1),
    },

    {
      title: 'Employee Names',
      dataIndex: 'employeeName',
      render: (text: any, record: any) => {
        return record.employeeName ? record.employeeName : '-';
      },

    },
    {
      title: 'Employee Number',
      dataIndex: 'employeeCode',
      render: (text: any, record: any) => {
        return record.employeeCode ? record.employeeCode : '-';
      },

    },
    {
      title: 'Designation',
      dataIndex: 'designation',
      render: (text: any, record: any) => {
        return record.designation_name ? record.designation_name : '-';
      },
    },

    {
      title: 'Actual',
      children:[
        {
          title: 'Basic',
          dataIndex: 'basic',
          align:"right",
          render: (text: any, record: any) => {
            return record.basic ? record.basic : '-';
          },
        },
        {
          title: ' Medical & Tea ',
          dataIndex: 'medicalAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.medicalAmount ? record.medicalAmount : '-';
          },
        },
        {
          title: 'Uniform ',
          dataIndex: 'uniformAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.uniformAmount ? record.uniformAmount : '-';
          },
        },
        {
          title: 'Production',
          dataIndex: 'productionAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.productionAmount ? record.productionAmount : '-';
          },
        },
        {
          title: 'TA',
          dataIndex: 'taAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.taAmount ? record.taAmount : '-';
          },
        },
        {
          title: ' Bonus ',
          dataIndex: 'bonusAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.bonusAmount ? record.bonusAmount : '-';
          },
        },
        {
          title: '  Gross  ',
          dataIndex: 'gross',
          align:"right",
          render: (text: any, record: any) => {
            return record.gross ? record.gross : '-';
          },
        },
      ]
    },
    
    {
      title: 'Actual Incentive per Hour',
      dataIndex: 'incentiveAmountPerHr',
      align:"right",
      render: (text: any, record: any) => {
        return record.incentiveAmountPerHr ? record.incentiveAmountPerHr : '-';
      },
    },
    {
      title: 'Factory Working Days',
      dataIndex: 'factoryWorkingDays',
      align:"right",
      render: (text: any, record: any) => {
        return record.factoryWorkingDays ? record.factoryWorkingDays : '-';
      },
    },
    {
      title: ' Muster ',
      dataIndex: 'attendance',
      align:"right",
      render: (text: any, record: any) => {
        return record.attendance ? record.attendance : '-';
      },
    },
    {
      title: 'Incentive Hours',
      dataIndex: 'totalIncentiveHr',
      align:"right",
      render: (text: any, record: any) => {
        return record.totalIncentiveHr ? record.totalIncentiveHr : '-';
      },
    },

    {
      title:'Calculated',
      children:[
        {
          title: 'Basic Salary',
          dataIndex: 'calBasic',
          align:"right",
          render: (text: any, record: any) => {
            return record.calBasic ? record.calBasic : '-';
          },
        },
        {
          title: ' Medical & Tea ',
          dataIndex: 'calMedical',
          align:"right",
          render: (text: any, record: any) => {
            return record.calMedical ? record.calMedical : '-';
          },
        },
        {
          title: 'Uniform Allowance',
          dataIndex: 'calUniform',
          align:"right",
          render: (text: any, record: any) => {
            return record.calUniform ? record.calUniform : '-';
          },
        },
        {
          title: 'Production',
          dataIndex: 'calProduction',
          align:"right",
          render: (text: any, record: any) => {
            return record.calProduction ? record.calProduction : '-';
          },
        },
        {
          title: 'TA',
          dataIndex: 'calTa',
          align:"right",
          render: (text: any, record: any) => {
            return record.calTa ? record.calTa : '-';
          },
        },
        {
          title: 'Bonus',
          dataIndex: 'calBonus',
          align:"right",
          render: (text: any, record: any) => {
            return record.calBonus ? record.calBonus : '-';
          },
        },
        {
          title: 'Gross',
          dataIndex: 'calGross',
          align:"right",
          render: (text: any, record: any) => {
            return record.calGross ? record.calGross : '-';
          },
        },
      ]
    },

    {
      title: ' Incentive Amount ',
      dataIndex: 'incentiveAmount',
      align:"right",
      render: (text: any, record: any) => {
        return record.incentiveAmount ? record.incentiveAmount : '-';
      },
    },
    {
      title: 'Total Amount Payable',
      dataIndex: 'totalEarnings',
      align:"right",
      render: (text: any, record: any) => {
        return record.totalEarnings ? record.totalEarnings : '-';
      },
    },
    {
      title: ' Canteen ',
      dataIndex: 'messAmount',
      align:"right",
      render: (text: any, record: any) => {
        return record.messAmount ? record.messAmount : '-';
      },
    },

    {
      title: ' Others ',
      dataIndex: 'othersAmount',
      align:"right",
      render: (text: any, record: any) => {
        return record.othersAmount ? record.othersAmount : '-';
      },
    },
    {
      title: 'Total Deduction',
      dataIndex: 'totalDeductions',
      align:"right",
      render: (text: any, record: any) => {
        return record.totalDeductions ? record.totalDeductions : '-';
      },
    },

    {
      title: ' Net Payable ',
      dataIndex: 'netSalary',
      align:"right",
      render: (text: any, record: any) => {
        return record.netSalary ? record.netSalary : '-';
      },
    },
    {
      title: ' Bank ',
      dataIndex: 'bank',
      render: (text: any, record: any) => {
        return record.bank ? record.bank : '-';
      },
    },
  ]

  const exceldata: IExcelColumn[] =  [
    {
      title: 'S No',
      dataIndex: 'sNo',
      render: (text, object, index) => (page - 1) * pageSize + (index + 1),
    },

    {
      title: 'Employee Names',
      dataIndex: 'employeeName',
      render: (text: any, record: any) => {
        return record.employeeName ? record.employeeName : '-';
      },

    },
    {
      title: 'Employee Number',
      dataIndex: 'employeeCode',
      render: (text: any, record: any) => {
        return record.employeeCode ? record.employeeCode : '-';
      },

    },
    {
      title: 'Designation',
      dataIndex: 'designation',
      render: (text: any, record: any) => {
        return record.designation_name ? record.designation_name : '-';
      },
    },

    {
      title: 'Actual',
      dataIndex:'',
      children:[
        {
          title: 'Basic',
          dataIndex: 'basic',
          align:"right",
          render: (text: any, record: any) => {
            return record.basic ? record.basic : '-';
          },
        },
        {
          title: ' Medical & Tea ',
          dataIndex: 'medicalAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.medicalAmount ? record.medicalAmount : '-';
          },
        },
        {
          title: 'Uniform ',
          dataIndex: 'uniformAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.uniformAmount ? record.uniformAmount : '-';
          },
        },
        {
          title: 'Production',
          dataIndex: 'productionAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.productionAmount ? record.productionAmount : '-';
          },
        },
        {
          title: 'TA',
          dataIndex: 'taAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.taAmount ? record.taAmount : '-';
          },
        },
        {
          title: ' Bonus ',
          dataIndex: 'bonusAmount',
          align:"right",
          render: (text: any, record: any) => {
            return record.bonusAmount ? record.bonusAmount : '-';
          },
        },
        {
          title: '  Gross  ',
          dataIndex: 'gross',
          align:"right",
          render: (text: any, record: any) => {
            return record.gross ? record.gross : '-';
          },
        },
      ]
    },
    
    {
      title: 'Actual Incentive per Hour',
      dataIndex: 'incentiveAmountPerHr',
      align:"right",
      render: (text: any, record: any) => {
        return record.incentiveAmountPerHr ? record.incentiveAmountPerHr : '-';
      },
    },
    {
      title: 'Factory Working Days',
      dataIndex: 'factoryWorkingDays',
      align:"right",
      render: (text: any, record: any) => {
        return record.factoryWorkingDays ? record.factoryWorkingDays : '-';
      },
    },
    {
      title: ' Muster ',
      dataIndex: 'attendance',
      align:"right",
      render: (text: any, record: any) => {
        return record.attendance ? record.attendance : '-';
      },
    },
    {
      title: 'Incentive Hours',
      dataIndex: 'totalIncentiveHr',
      align:"right",
      render: (text: any, record: any) => {
        return record.totalIncentiveHr ? record.totalIncentiveHr : '-';
      },
    },

    {
      title:'Calculated',
      dataIndex:'',
      children:[
        {
          title: 'Basic Salary',
          dataIndex: 'calBasic',
          align:"right",
          render: (text: any, record: any) => {
            return record.calBasic ? record.calBasic : '-';
          },
        },
        {
          title: ' Medical & Tea ',
          dataIndex: 'calMedical',
          align:"right",
          render: (text: any, record: any) => {
            return record.calMedical ? record.calMedical : '-';
          },
        },
        {
          title: 'Uniform Allowance',
          dataIndex: 'calUniform',
          align:"right",
          render: (text: any, record: any) => {
            return record.calUniform ? record.calUniform : '-';
          },
        },
        {
          title: 'Production',
          dataIndex: 'calProduction',
          align:"right",
          render: (text: any, record: any) => {
            return record.calProduction ? record.calProduction : '-';
          },
        },
        {
          title: 'TA',
          dataIndex: 'calTa',
          align:"right",
          render: (text: any, record: any) => {
            return record.calTa ? record.calTa : '-';
          },
        },
        {
          title: 'Bonus',
          dataIndex: 'calBonus',
          align:"right",
          render: (text: any, record: any) => {
            return record.calBonus ? record.calBonus : '-';
          },
        },
        {
          title: 'Gross',
          dataIndex: 'calGross',
          align:"right",
          render: (text: any, record: any) => {
            return record.calGross ? record.calGross : '-';
          },
        },
      ]
    },

    {
      title: ' Incentive Amount ',
      dataIndex: 'incentiveAmount',
      align:"right",
      render: (text: any, record: any) => {
        return record.incentiveAmount ? record.incentiveAmount : '-';
      },
    },
    {
      title: 'Total Amount Payable',
      dataIndex: 'totalEarnings',
      align:"right",
      render: (text: any, record: any) => {
        return record.totalEarnings ? record.totalEarnings : '-';
      },
    },
    {
      title: ' Canteen ',
      dataIndex: 'messAmount',
      align:"right",
      render: (text: any, record: any) => {
        return record.messAmount ? record.messAmount : '-';
      },
    },

    {
      title: ' Others ',
      dataIndex: 'othersAmount',
      align:"right",
      render: (text: any, record: any) => {
        return record.othersAmount ? record.othersAmount : '-';
      },
    },
    {
      title: 'Total Deduction',
      dataIndex: 'totalDeductions',
      align:"right",
      render: (text: any, record: any) => {
        return record.totalDeductions ? record.totalDeductions : '-';
      },
    },

    {
      title: ' Net Payable ',
      dataIndex: 'netSalary',
      align:"right",
      render: (text: any, record: any) => {
        return record.netSalary ? record.netSalary : '-';
      },
    },
    {
      title: ' Bank',
      dataIndex: 'bank',
      render: (text: any, record: any) => {
        return record.bank ? record.bank : '-';
      },
    },
  ]
  const exportExcel = () => {
    const excel = new Excel();
    excel
      .addSheet('In-House Report Excel')
      .addColumns(exceldata)
      .addDataSource(data, { str2num: true })
      .saveAs('Inhouse-Report-hrs.xlsx');
  };


  return (
    <Card
      title={<span style={{ color: 'white' }}>In House Report</span>}
      extra={<Button onClick={exportExcel}>Get Excel</Button>}
      style={{ textAlign: 'center' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    >
      <Form form={form} layout="vertical" onFinish={getPayrollAllData}>
        <Row gutter={24}>
          <Col xs={24} sm={24} md={6} lg={6} xl={6}>
            <Form.Item label="Payroll Month" name="PayrollMonth" rules={[{ required: true, message: 'Please Select Month' }]}>
              <DatePicker style={{ width: '100%' }} picker="month" placeholder='Select Month' />
            </Form.Item>
          </Col>

          <Col xs={24} sm={24} md={6} lg={6} xl={6}>
            <Form.Item label="Department" name="department" rules={[{ required: false, message: 'Please Select Department' }]}>
              <Select placeholder="Select Department">
                {employeeName.map((index) => {
                  return (
                    <Option key={index.id} value={index.department}>
                      {index.dept_name}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={24} md={6} lg={6} xl={6}>
            <Form.Item label="Employee Name" name="employeeName" rules={[{ required: false, message: 'Please Select Employee' }]}>
              <Select placeholder="Select Employee Name">
                {employeeName.map((index) => {
                  return (
                    <Option value={index.employee_name}>
                      {index.employee_name}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={24} md={6} lg={6} xl={3}>
            <Form.Item>
              <Button type="primary" htmlType="submit" style={{marginTop:"30px"}}>
                Submit
              </Button>
            </Form.Item>
          </Col>

          <Col xs={24} sm={24} md={6} lg={6} xl={1}>
            <Form.Item>
              <Button type="primary" htmlType="reset" onClick={onReset} style={{marginTop:"30px"}}>
                Reset
              </Button>
            </Form.Item>
          </Col>
        </Row>
        <Table
          className="custom-table-wrapper"
          scroll={{ x: 3000, y: 1100 }}
          columns={columns}
          dataSource={data}
          size="small"
          pagination={{
            pageSize: 10,
            onChange(current, pageSize) {
              setPage(current);
              setPageSize(pageSize);
            },
          }}
        />
      </Form>
    </Card>
  );
}

export default PayrollInHouseReports;