import { SearchOutlined, UndoOutlined } from "@ant-design/icons"
import { Button, Card, Checkbox, Col, DatePicker, Descriptions, Divider, Form, Input, message, Modal, Row, Select, Space, Table } from "antd"
import { ColumnsType } from "antd/es/table"
import { useEffect, useRef, useState } from "react"
import Highlighter from 'react-highlight-words';
import React from "react"
import { PayslipGenerationReq } from "libs/shared-models/hrms/src/lib/payroll-process/payslip-generation-req"
import { EmailModel, PayrollTypeEnum } from "@gtpl/shared-models/hrms"
import { PayrollProcessServices } from "@gtpl/shared-services/hrms"
import logo from 'apps/ui/masters-ui/src/app/BMRpayslip.jpg'
import moment from "moment";
import { numberToWords } from "amount-to-words";

const { Option } = Select

// export const getCssFromComponent = (fromDoc, toDoc) => {
//     Array.from(fromDoc.styleSheets).forEach((styleSheet: any) => {
//         if (styleSheet.cssRules) {
//             // true for inline styles
//             const newStyleElement = toDoc.createElement("style");
//             Array.from(styleSheet.cssRules).forEach((cssRule: any) => {
//                 newStyleElement.appendChild(toDoc.createTextNode(cssRule.cssText));
//             });
//             toDoc.head.appendChild(newStyleElement);
//         }
//     });
// };

export const getCssFromComponent = (fromDoc: Document, toDoc: Document) => {
    Array.from(fromDoc.styleSheets).forEach((styleSheet: CSSStyleSheet) => {
      try {
        if (styleSheet?.cssRules) { // true for inline styles and same-origin stylesheets
          const newStyleElement = toDoc.createElement("style");
          Array.from(styleSheet.cssRules).forEach((cssRule: CSSRule) => {
            newStyleElement.appendChild(toDoc.createTextNode(cssRule.cssText));
          });
          toDoc.head.appendChild(newStyleElement);
        }
      } catch (e) {
        console.warn("Could not access stylesheet rules for", styleSheet.href, e);
      }
    });
  };

enum EmployeeMode {
    InHouse = 'In-House',
    NMR = 'NMR',
}



export const PayslipGeneration = () => {
    const [form] = Form.useForm()
    const [employeeData, setEmployeeData] = useState<any[]>([])
    const service = new PayrollProcessServices()
    const [data, setData] = useState<any[]>([])
    const [mailData, setMailData] = useState<any[]>([])
    const [modalOpen, setModalOpen] = useState<boolean>(false)
    const [month, setMonth] = useState<string>()
    const [empDetails, setEmpDetails] = useState<any[]>([])
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [page, setPage] = useState<number>(1);
    const [year, setYear] = useState<string>()
    const searchInput = useRef(null);
    const [searchedColumn, setSearchedColumn] = useState('');
    const [searchText, setSearchText] = useState('');
    const monthNames = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
    const [selectedEmployeeMode, setSelectedEmployeeMode] = useState<string | null>(null);
    const [employeeMode, setEmployeeMode] = useState<any>();
    const [employeeTypeDisabled, setEmployeeTypeDisabled] = useState<boolean>(false);
    const [dept, setDept] = useState<any[]>([])
    const [ yearData, setYearData ] = useState<any[]>([])
    const [ monthData, setMonthData ] = useState<any[]>([])
    const [ typeData, setTypeData ] = useState<any[]>([])

    const onGenerate = () => {
        // const month = Number(String(form.getFieldValue('year')) + String(form.getFieldValue('month')))
        const month = (form.getFieldValue('month')).format('YYYYMM');
        const year = (form.getFieldValue('month')).format('YYYY');
        const cate = form.getFieldValue('employeeType')
        const req = new PayslipGenerationReq(selectedRowKeys, month, cate, year)
        service.getPayrollLogByEmployeeId(req).then(res => {
            if (res.status) {
                const payrollMonthYear = res.data[0]?.payroll_month
                const payrollMonth = Number(String(payrollMonthYear).slice(-2))
                const d = payrollMonth - 1;
                let name = monthNames[d];
                let year = String(payrollMonthYear).substring(0, 4)
                setYear(year)
                setMonth(name)
                setData(res.data)
                setModalOpen(true)
            }
        })

    }

    const generateEmail = () => {
        // const month = Number(String(form.getFieldValue('year')) + String(form.getFieldValue('month')))
        const month = (form.getFieldValue('month')).format('YYYYMM');
        const year = (form.getFieldValue('month')).format('YYYY');
        const cate = form.getFieldValue('employeeType')
        setMonthData(month)
        setYearData(year)
        setTypeData(cate)
        const req = new PayslipGenerationReq(selectedRowKeys, month, cate, year)
        service.getPayrollLogByEmployeeId(req).then(res => {
            if (res.status) {
                setMailData(res.data)
            }
        })

    }

    useEffect(() => {
        if (mailData.length > 0) {
            sendMailForApprovalUser();
        }
    }, [mailData]);

    const handlePrint = () => {
        const invoiceContent = document.getElementById("print");
        if (invoiceContent) {
            const devContent = invoiceContent.innerHTML;
            const printWindow = window.open("", "PRINT", "height=900,width=1600");

            printWindow.document.write(`
                <html>
                    <head>
                        <style>
                            @page {
                                size: legal;
                                margin: 20;
                            }
                            body {
                                margin: 0;
                                transform: scale(1);
                                transform-origin: top center;
                                width:100%;
                            }
                            /* Additional styles for your content */
                        </style>
                    </head>
                    <body>${devContent}</body>
                </html>
            `);

            getCssFromComponent(document, printWindow.document);

            printWindow.document.close();
            setTimeout(function () {
                printWindow.print();
                printWindow.close();
            }, 1000); // Add a delay to ensure all content is loaded
        }
    };



    const onSubmit = (val) => {
        const month = (form.getFieldValue('month')).format('YYYYMM');
        const year = (form.getFieldValue('month')).format('YYYY');
        const req = new PayslipGenerationReq()
        // req.month = Number(String(val.year) + String(val.month))
        req.month = month
        req.year = year
        req.employeeType = val.employeeType
        req.employeeCategory = val.employeeCategory
        service.getEmployeeDataAgainstYearMonth(req).then(res => {
            if (res.status) {
                setEmpDetails(res.data)
            }
        })
    }



    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)
                    setSearchedColumn(dataIndex);
                    confirm({ closeDropdown: true });
                }} 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('');
        setSelectedRowKeys([])
    };


    const columns: any = [
        {
            title: 'S No',
            key: 'sno',
            width: '70px',
            responsive: ['sm'],
            render: (text, object, index) => (page - 1) * 10 + (index + 1)
        },
        {
            key: 'Employee Code',
            title: 'Employee Code',
            dataIndex: 'employeeCode',
            ...getColumnSearchProps('employeeCode')
        },
        {
            key: 'Employee ',
            title: 'Employee Name',
            dataIndex: 'employeeName',
            ...getColumnSearchProps('employeeName')

        },
        {
            key: 'Employee t',
            title: 'Department',
            dataIndex: 'department',
            onFilter: (value, record) => {
                return record.department.includes(value);
            },
            filterDropdown: employeeMode === 'Regular' ? ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown" style={{ flexDirection: 'row', marginLeft: 10 }}>
                    {
                        dept.map(e => (
                            <React.Fragment key={e.department}>
                                <Checkbox
                                    checked={selectedKeys?.includes(e.department)}
                                    onChange={() => setSelectedKeys(selectedKeys?.includes(e.department) ? [] : [e.department])}
                                >
                                    <span style={{ color: 'green' }}>{e.department}</span>
                                </Checkbox><br />
                            </React.Fragment>
                        ))
                    }

                    <div className="custom-filter-dropdown-btns">
                        <Button onClick={() => {
                            clearFilters()
                            confirm()
                        }} className="custom-reset-button">
                            Reset
                        </Button>
                        <Button type="primary" style={{ margin: 10 }} onClick={() => confirm()} className="custom-ok-button">
                            OK
                        </Button>
                    </div>
                </div>
            ) : undefined,
            filterMultiple: true,
        },
        {
            key: 'Employee d',
            title: 'Designation',
            dataIndex: 'designation',
            ...getColumnSearchProps('designation')

        }
    ]

    // const rowSelection = {
    //     onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
    //       console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    //     },
    // }

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    const onReset = () => {
        form.resetFields()
        setData([])
        setEmpDetails([])
        setSelectedRowKeys([])
    }

    const handleEmployeeModeChange = (value) => {
        if (value === 'NMR') {
            form.setFieldsValue({ empType: null });
            setSelectedEmployeeMode(null);
            setEmployeeMode(null);
            setEmployeeTypeDisabled(true);
        } else {

            form.setFieldsValue({ empType: 'All' });
            setSelectedEmployeeMode(value);
            setEmployeeMode(value);
            setEmployeeTypeDisabled(false);
        }
    };

    const totalAmount = (data) => {
        let totalOFRows: any = []

        const earnings = [
            parseFloat(data.basic) || 0,
            parseFloat(data.hraAmount) || 0,
            parseFloat(data.eduAmount) || 0,
            parseFloat(data.medicalAmount) || 0,
            parseFloat(data.splAmount) || 0,
            parseFloat(data.conveyanceAmount) || 0,
            parseFloat(data.petrolAmount) || 0,
            parseFloat(data.shoeAmount) || 0,
            parseFloat(data.washingAmount) || 0,
            parseFloat(data.uniformAmount) || 0,
            parseFloat(data.helperAmount) || 0,
            parseFloat(data.productionAmount) || 0,
            parseFloat(data.taAmount) || 0,
            parseFloat(data.bonusAmount) || 0,
        ];
    
        const totalEarnings = earnings.reduce((acc, curr) => acc + curr, 0);

        totalOFRows.push(totalEarnings.toFixed(2).toLocaleString());
        
        return totalOFRows
    };

    const totalGross = (data) => {
        let totalOFRows: any = []

        const earnings = [
            parseFloat(data.calBasic) || 0,
            parseFloat(data.calHra) || 0,
            parseFloat(data.calEdu) || 0,
            parseFloat(data.calMedical) || 0,
            parseFloat(data.calSpl) || 0,
            parseFloat(data.calConveyance) || 0,
            parseFloat(data.calPetrol) || 0,
            parseFloat(data.calShoe) || 0,
            parseFloat(data.calWashing) || 0,
            parseFloat(data.calHelper) || 0,
            parseFloat(data.calProduction) || 0,
            parseFloat(data.calTa) || 0,
            parseFloat(data.calBonus) || 0,
        ];
    
        const totalEarnings = earnings.reduce((acc, curr) => acc + curr, 0);
        
        totalOFRows.push(totalEarnings.toFixed(2).toLocaleString());

        return totalOFRows
    };

    const totalDeduction = (data) => {
        let totalRows: any = []
        const deductions = [
            parseFloat(data.epfAmount) || 0,
            parseFloat(data.esicAmount) || 0,
            parseFloat(data.messAmount) || 0,
            parseFloat(data.professionalTax) || 0,
            parseFloat(data.othersAmount) || 0,
            parseFloat(data.tds) || 0,
        ];
    
        const totalDeductions = deductions.reduce((acc, curr) => acc + curr, 0);

        totalRows.push(totalDeductions.toFixed(2).toLocaleString());
        
        return totalRows
    };

    const calculateNetAmount = (data) => {
        const totalEarnings = totalAmount(data);
        const totalDeductions = totalDeduction(data);
        const netAmountFromEarnings = totalEarnings - totalDeductions;
        
        return netAmountFromEarnings.toFixed(2).toLocaleString();
    };
    
    const calculateNetGross = (data) => {
        const totalGrossAmount = totalGross(data);
        const totalDeductions = totalDeduction(data);
        const netAmountFromGross = totalGrossAmount - totalDeductions;

        const roundedNetAmount = Number(Math.round(netAmountFromGross));
        console.log(numberToWords(roundedNetAmount),'........................')
        return roundedNetAmount;
    };
    
    
    const renderEarningsRow = (data) => {
        const earningsRows = [];

        if (parseFloat(data.basic) > 0) {
            earningsRows.push(
                <tr key="basic">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Basic Salary</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.basic}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calBasic}</td>
                </tr>
            );
        }
        if (parseFloat(data.hraAmount) > 0) {
            earningsRows.push(
                <tr key="hra">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>House Rent Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.hraAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calHra}</td>
                </tr>
            );
        }

        if (parseFloat(data.eduAmount) > 0) {
            earningsRows.push(
                <tr key="edu">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Education Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.eduAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calEdu}</td>
                </tr>
            );
        }

        if (parseFloat(data.medicalAmount) > 0) {
            earningsRows.push(
                <tr key="medical">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Medical Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.medicalAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calMedical}</td>
                </tr>
            );
        }
        if (parseFloat(data.splAmount) > 0) {
            earningsRows.push(
                <tr key="spl">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Special Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.splAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calSpl}</td>
                </tr>
            );
        }
        if (parseFloat(data.conveyanceAmount) > 0) {
            earningsRows.push(
                <tr key="conveyanceAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Conveyance Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.conveyanceAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calConveyance}</td>
                </tr>
            );
        }
        if (parseFloat(data.petrolAmount) > 0) {
            earningsRows.push(
                <tr key="petrolAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Petrol Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.petrolAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calPetrol}</td>
                </tr>
            );
        }
        if (parseFloat(data.shoeAmount) > 0) {
            earningsRows.push(
                <tr key="shoeAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Shoe Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.shoeAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calShoe}</td>
                </tr>
            );
        }
        if (parseFloat(data.washingAmount) > 0) {
            earningsRows.push(
                <tr key="washingAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Washing Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.washingAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calWashing}</td>
                </tr>
            );
        }
        if (parseFloat(data.uniformAmount) > 0) {
            earningsRows.push(
                <tr key="uniformAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Uniform Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.uniformAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calUniform}</td>
                </tr>
            );
        }
        if (parseFloat(data.helperAmount) > 0) {
            earningsRows.push(
                <tr key="helperAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Helper Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.helperAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calHelper}</td>
                </tr>
            );
        }
        if (parseFloat(data.productionAmount) > 0) {
            earningsRows.push(
                <tr key="productionAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Production Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.productionAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calProduction}</td>
                </tr>
            );
        }
        if (parseFloat(data.taAmount) > 0) {
            earningsRows.push(
                <tr key="taAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>TA Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.taAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calTa}</td>
                </tr>
            );
        }
        if (parseFloat(data.bonusAmount) > 0) {
            earningsRows.push(
                <tr key="bonusAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>Bonus Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.bonusAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black' }} colSpan={1}>{data.calBonus}</td>
                </tr>
            );
        }
        return earningsRows;
    };
    const renderDeductionsRow = (data) => {
        const deductionsRows = [];

        if (parseFloat(data.epfAmount) > 0) {
            deductionsRows.push(
                <tr key="epfAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>EPF </td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.epfAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.epfAmount}</td>
                </tr>
            );
        }
        if (parseFloat(data.esicAmount) > 0) {
            deductionsRows.push(
                <tr key="ESIC">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>ESIC Allowance</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.esicAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.esicAmount}</td>
                </tr>
            );
        }

        if (parseFloat(data.messAmount) > 0) {
            deductionsRows.push(
                <tr key="mess">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>Mess Deduction</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.messAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.messAmount}</td>
                </tr>
            );
        }

        if (parseFloat(data.professionalTax) > 0) {
            deductionsRows.push(
                <tr key="professionalTax">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>Professional Tax</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.professionalTax}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.professionalTax}</td>
                </tr>
            );
        }
        if (parseFloat(data.othersAmount) > 0) {
            deductionsRows.push(
                <tr key="othersAmount">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>Other Deduction</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.othersAmount}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.othersAmount}</td>
                </tr>
            );
        }
        if (parseFloat(data.tds) > 0) {
            deductionsRows.push(
                <tr key="tds">
                    <td style={{ textAlign: 'left', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>TDS</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.tds}</td>
                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{data.tds}</td>
                </tr>
            );
        }
        return deductionsRows;
    };

    const getMonthName = (monthData) => {
        // Extract the last two digits from monthData
        const monthIndex = parseInt(monthData.slice(-2), 10) - 1;
        
        // Ensure the index is within the valid range
        if (monthIndex >= 0 && monthIndex < monthNames.length) {
            return monthNames[monthIndex];
        } else {
            return "Invalid Month"; // Handle invalid month data
        }
    };

    let mailerSent = false;

    async function sendMailForApprovalUser() {
        const monthName = getMonthName(monthData);
        const promises = mailData.map(async (item) => {
            console.log('mapping',item)
            const employeeDetails = new EmailModel();
            employeeDetails.employeeCode = item.employeeCode;
            employeeDetails.to = item.emailId;
            employeeDetails.html = `
                <html>
                <head>
                  <meta charset="UTF-8" />
                  <style>
                    #acceptDcLink {
                          display: inline-block;
                          padding: 10px 20px;
                          background-color: #28a745;
                          color: #fff;
                          text-decoration: none;
                          border-radius: 5px;
                          margin-top: 10px;
                          transition: background-color 0.3s ease, color 0.3s ease;
                          cursor: pointer;
                      }
              
                      #acceptDcLink.accepted {
                          background-color: #6c757d;
                          cursor: not-allowed;
                      }
              
                      #acceptDcLink:hover {
                          background-color: #218838;
                          color: #fff;
                      }
                  </style>
                </head>
                <body>
                  <p>Dear ${item.employeeName},</p>
                  <p>We are pleased to inform you that your payslip for the month of ${monthName}, ${yearData} is now available.</p>
                  <p>To view and download your payslip, please click on the link below:</p>
                  <a
                  href={"${window.location.origin}/#/payslip-print/${typeData}/${monthData}/${yearData}/${item.employeeId}"}
                  style="
                  display: inline-block;
                  padding: 10px 20px;
                  background-color: #007bff;
                  color: #fff;
                  text-decoration: none;
                  border-radius: 5px;
                  "
                  >View Your Payslip</a>
                  
                  <p>If you have any concerns regarding your payslip, feel free to reach out to the HR department at [HR Contact Email/Phone Number].</p>
                </body>
              </html>
            `;
            employeeDetails.subject = `Your Payslip for ${monthName}, ${yearData}`;
            return service.sendPaySlipMail(employeeDetails);
        });
    
        try {
            const results = await Promise.all(promises);
            results.forEach((res, index) => {
                if (res.status === 201) {
                    if (res.data.status) {
                        message.success(`Mail sent successfully to ${mailData[index]?.emailId}`);
                    } else {
                        message.warning(`Mail sent but with issues to ${mailData[index]?.emailId}`);
                    }
                } else {
                    message.error(`Failed to send mail to ${mailData[index]?.emailId}`);
                }
            });
        } catch (error) {
            message.error('Failed to send some emails');
        }
    }
    

    return (
        <Card title={<span style={{ color: 'white', fontSize: 18 }}>Payslip Generation</span>}
            style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#45c8f6', border: 0, paddingTop: "1%", paddingBottom: "1%" }}>
            <Form form={form} layout="vertical" onFinish={onSubmit}>
                <Row gutter={24}>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 8 }} lg={{ span: 6 }} xl={{ span: 4 }}>
                        <Form.Item label='Employee Type' name='employeeType' rules={[{ required: true, message: 'Employee Type is required' }]}>
                            <Select allowClear showSearch optionFilterProp="children" placeholder='Select Employee Type'>
                                {Object.values(PayrollTypeEnum).map(e => {
                                    return (
                                        <Option kye={e} value={e}>{e}</Option>
                                    )
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                        <Form.Item name='month' label='Payroll Month'rules={[{ required: true, message: 'Month is required' }]}>
                            <DatePicker picker='month' style={{ width: '100%' }} />
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 8 }} lg={{ span: 6 }} xl={{ span: 5 }}>
                        <Form.Item
                            name="employeeCategory"
                            label="Employee Category"
                        >
                            <Select
                                showSearch
                                placeholder="Select Employee Category"
                                onChange={handleEmployeeModeChange}
                                allowClear
                            >

                                <option value={EmployeeMode.NMR}>NMR</option>
                                <option value={EmployeeMode.InHouse}>In-House</option>

                            </Select>
                        </Form.Item>
                    </Col>

                    <Col span={2}>
                        <Form.Item>
                            <Button htmlType="submit" type="primary" style={{ marginTop: '23px' }}>Submit</Button>
                        </Form.Item>
                    </Col>
                    <Col span={1}>
                        <Form.Item>
                            <Button onClick={onReset} danger icon={<UndoOutlined />} style={{ marginTop: '23px' }}>Reset</Button>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            {empDetails.length > 0 ? (<>
                <Row justify={'end'}>
                    <Space>
                        <Button onClick={generateEmail} type='primary' disabled={selectedRowKeys.length > 0 ? false : true}>Trigger Mail</Button>
                        <Button onClick={onGenerate} type='primary' disabled={selectedRowKeys.length > 0 ? false : true}>Print</Button>
                    </Space>
                </Row>
                <Table rowKey={record => record.employeeId} columns={columns} dataSource={empDetails} rowSelection={rowSelection} pagination={false} />
                <br />
            </>) : (<></>)}
            <Modal visible={modalOpen} width={'80%'} footer={[]} onCancel={() => setModalOpen(false)}>
                <Button style={{ marginLeft: '95%' }} type='primary' onClick={handlePrint}>Print</Button>
                <br /><br />
                <div id='print'>
                    {data.map(e => {
                        const indexRecord = empDetails.find(rec => {
                            return (rec.employeeId === e.employeeId)
                        })
                        const index = indexRecord.index

                        return (
                            <div>

                                <div style={{ marginTop: '1%' }}>
                                    {/* <b style={{ fontSize: '20px', marginLeft: '90%' }}>S.NO :-{index}</b> */}
                                    <Row style={{ border: '2px solid black' }} >
                                        <Col span={7}> <div className="logo" >
                                            <img src={logo} width={100} height={70} style={{ marginBottom: '10px', marginLeft: '20px' }}></img>
                                        </div></Col>
                                        <Col span={13} style={{ marginTop: '1%' }}>
                                            <b style={{ textAlign: 'center', fontSize: '15px' }}>BMR Industries Private Limited</b><br /><b style={{ fontSize: '13px', marginLeft: '15%' }}>PAYSLIP FOR THE MONTH OF {month}-{year}</b>
                                        </Col>
                                    </Row>

                                    <Row gutter={24}>
                                        <Col span={11}>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '130px' }}>Employee Name </b>}><b style={{ color: 'black', fontSize: '15px' }}>{e?.employeeName}</b>
                                                </Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '130px' }}>Employee No </b>}><b style={{ color: 'black', fontSize: '15px' }}>{e?.employeeCode}</b></Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '130px' }}>Function </b>}><b style={{ color: 'black', fontSize: '15px' }}>{e?.department}</b></Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '130px' }}>Designation </b>}><b style={{ color: 'black', fontSize: '15px' }}>{e?.designation}</b></Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '130px' }}>Location</b>}><b style={{ color: 'black', fontSize: '15px' }}>Damavaram</b></Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '130px' }}
                                                >Bank</b>}><b style={{ color: 'black', fontSize: '15px' }}>{`${e?.bank ?? ''} ${e?.bankAcNo ?? ''} ${e?.ifsc ?? ''}`}</b>
                                                </Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '130px' }}>Date Of Join</b>}><b style={{ color: 'black', fontSize: '15px' }}>{e?.doj ? moment(e.doj).format('YYYY-MM-DD') : 'N/A'}</b></Descriptions.Item>
                                            </Descriptions>
                                        </Col>
                                        <Col span={12}>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '190px' }}>Tax Regime </b>}><b style={{ color: 'black', fontSize: '15px' }}>Regular Tax Regime</b></Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '190px' }}>Income Tax Number(PAN)</b>}><b style={{ color: 'black', fontSize: '15px' }}>{e?.pan}</b></Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '190px' }}>Universal Account No </b>}><b style={{ color: 'black', fontSize: '15px' }}>{e?.uan}</b></Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '190px' }}>PF Account No </b>}><b style={{ color: 'black', fontSize: '15px' }}>{e?.pfNo}</b></Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item label={<b style={{ color: 'black', fontSize: '15px', width: '190px' }}>ESI Number</b>}><b style={{ color: 'black', fontSize: '15px' }}>{e?.esi ? e.esi : ''}</b></Descriptions.Item>
                                            </Descriptions>
                                            <Descriptions>
                                                <Descriptions.Item
                                                    label={<b style={{ color: 'black', fontSize: '15px', width: '190px' }}>PR Account No (PRAN)</b>}
                                                >
                                                    <b style={{ color: 'black', fontSize: '15px', width: '190px' }}>
                                                        {''}
                                                    </b>
                                                </Descriptions.Item>
                                            </Descriptions>
                                        </Col>
                                    </Row>
                                    <div>
                                        <table style={{ borderCollapse: 'collapse', borderBlockColor: 'black', width: '100%' }}>
                                            <thead>
                                                <tr>
                                                    <th style={{ textAlign: 'center', fontSize: '15px', border: '1px solid black', width: "153px" }} colSpan={2}>Attendance</th>
                                                    <th style={{ textAlign: 'center', fontSize: '15px', border: '1px solid black' }} colSpan={1}>Value</th>
                                                    <th colSpan={3} rowSpan={2}></th>
                                                </tr>
                                                <tr>
                                                    <td style={{ textAlign: 'left', fontSize: '15px', border: '1px solid black', paddingLeft: '10px', color: 'black' }} colSpan={2}>Attendance</td>
                                                    <td style={{ textAlign: 'right', fontSize: '15px', border: '1px solid black', paddingRight: '10px', color: 'black' }} colSpan={1}>
                                                        {Math.round(e?.attendance)} Days
                                                    </td>
                                                </tr>

                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td style={{ verticalAlign: 'top', border: '1px solid black' }} colSpan={3}>
                                                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                                            <tr>
                                                                <th style={{ textAlign: 'center', fontSize: '15px', borderBottom: '1px solid black', borderRight: '1px solid black' }} colSpan={1}>Earnings</th>
                                                                <th style={{ textAlign: 'center', fontSize: '15px', borderBottom: '1px solid black', borderRight: '1px solid black' }} colSpan={1}>Amount</th>
                                                                <th style={{ textAlign: 'center', fontSize: '15px', borderBottom: '1px solid black', borderRight: '1px solid black' }} colSpan={1}>Gross Salary</th>
                                                            </tr>
                                                            {renderEarningsRow(e)}
                                                        </table>
                                                    </td>
                                                    <td style={{ verticalAlign: 'top', border: '1px solid black' }} colSpan={3}>
                                                        {/* Deductions Section */}
                                                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                                            <tr>
                                                                <th style={{ textAlign: 'center', fontSize: '15px', borderBottom: '1px solid black', borderRight: '1px solid black' }} colSpan={2}>Deduction</th>
                                                                <th style={{ textAlign: 'center', fontSize: '15px', borderBottom: '1px solid black', borderRight: '1px solid black' }} colSpan={1}>Amount</th>
                                                                
                                                            </tr>
                                                            {renderDeductionsRow(e)}
                                                        </table>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td style={{ verticalAlign: 'top', }} colSpan={3}>
                                                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                                            <tr>
                                                                <th style={{ textAlign: 'left', fontSize: '15px', borderLeft: '1px solid black', borderBottom: '1px solid black', width: '58%' }} colSpan={1}>Total Earnings</th>
                                                                <th style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black', width: '81px' }} colSpan={1}>{totalAmount(e)}</th>
                                                                <th style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{totalGross(e)}</th>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                    <td style={{ verticalAlign: 'top', }} colSpan={3}>
                                                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                                            <tr>
                                                                <th style={{ textAlign: 'left', fontSize: '15px', borderLeft: '1px solid black', borderBottom: '1px solid black', width: '41%' }} colSpan={2}>Total Deductions</th>
                                                                <th style={{ textAlign: 'right', fontSize: '15px', border: '1px solid black', width: '38px',borderRight: '1px solid black', borderBottom: '1px solid black' }} colSpan={1}>{totalDeduction(e)}</th>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td style={{ textAlign: 'left', fontSize: '15px', borderLeft: '1px solid black', borderBottom: '1px solid black', fontWeight:'bold' }} colSpan={5}>Net Amount ({numberToWords(calculateNetGross(e))})</td>
                                                    <td style={{ textAlign: 'right', fontSize: '15px', borderRight: '1px solid black', borderBottom: '1px solid black', fontWeight:'bold' }} colSpan={1}>₹ {calculateNetGross(e).toLocaleString()}</td>
                                                </tr>

                                            </tbody>
                                        </table>

                                    </div>

                                </div>

                            </div>
                        )
                    })}
                </div>
            </Modal>
        </Card >
    )

}

export default PayslipGeneration