import { AttendanceMonthRequest, MonthAttnDataModel, PayRollMonthDto, PayRollRequest, ShiftAttendanceRequest } from "@gtpl/shared-models/hrms";
import { Input, Button, Space, Form, Row, Col, Select, Card, DatePicker, message, Popconfirm, Checkbox, Modal } from "antd";
import Table, { ColumnProps } from "antd/lib/table";
import React, { useState, useRef, useEffect } from "react";
import { SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { Excel } from 'antd-table-saveas-excel'
import { IExcelColumn } from 'antd-table-saveas-excel/app';
import { AttendanceService, PayrollProcessServices } from "@gtpl/shared-services/hrms";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
// import { Excel } from 'antd-table-saveas-excel';
import { DepartmentDto, HrmsEmployeeDetailsDto, HrmsEmployeeRequest, PlantsDropDown } from "@gtpl/shared-models/masters";
import { DepartmentService, HrmsEmpDetService, UnitcodeService } from '@gtpl/shared-services/masters';
import moment from "moment";

/* eslint-disable-next-line */

export const generatedPayGrid = () => {


    const service = new PayrollProcessServices;
    const employeeService = new HrmsEmpDetService();
    const [reportData, setReportData] = useState<any[]>([]);
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const [page, setPage] = React.useState(1);
    const [pageSize, setPageSize] = useState<number>(1);
    const [rowData, setRowData] = useState([]);
    const [freezeStatus, setFreezeStatus] = useState<number>();
    const [employeeData, setEmployeeData] = useState<HrmsEmployeeDetailsDto[]>([]);
    const [form] = Form.useForm();
    const [isModalOpen1, setIsModalOpen1] = useState(false);
    const { Option } = Select;
    const { RangePicker } = DatePicker;
    useEffect(() => {
        // getAllActiveEmployees();
    }, []);




    // const getAttendanceData = () => {
    //     // const req = new ShiftAttendanceRequest(selectedFromDate, selectedToDate, '', form.getFieldValue('employeeId'));
    //     service.getAllPayrollLogs().then(res => {
    //         setReportData([]);
    //         if (res.status) {
    //             setReportData(res.data);
    //             setFiltersData(res.data);
    //         } else {
    //             setReportData([]);
    //             setFiltersData([]);
    //             AlertMessages.getErrorMessage(res.internalMessage);
    //             return false;
    //         }
    //     }).catch(err => {
    //         setReportData([]);
    //         setFiltersData([]);
    //         AlertMessages.getErrorMessage(err.message);
    //     })
    // }



    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);
    };

    const onReset = () => {
        form.resetFields();
        setReportData([]);
    }
    const onFocus = () => {
        console.log('focus');
    }

    const onSearch = (val) => {
        console.log('search:', val);
    }

    const onBlur = () => {
        console.log('blur');
    }

    function handleReset(clearFilters) {
        clearFilters();
        setSearchText('');
    };

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

    const showModal1 = () => {
        setIsModalOpen1(true);

    };

    const cancelHandle = () => {
        setIsModalOpen1(false);
        getPayrollData();

    };

    const changeHandler = () => {
        setFreezeStatus(1);
        // submitPayLog();
        submitPayLog(1);

    }
    const deleteData = () => {
        setFreezeStatus(0)
        setIsModalOpen1(false);
        submitPayLog(0)
        getPayrollData();
    }


    const submitPayLog = (freezeStatus) => {
        const req = new PayRollMonthDto();

        if (form.getFieldValue('year') !== undefined) {
            req.years = (form.getFieldValue('year')).format('YYYYMM');
            req.month = (form.getFieldValue('year')).format('YYYYMM');
        }
        req.freezStatus = freezeStatus;

        service.updateFreezeStatus(req).then((res) => {
            console.log(req)
            if (res.status) {
                getPayrollData()
                message.success(res.internalMessage);
            } else {
                message.error(res.internalMessage);
                setRowData([]);
            }
        });
        // getPayrollData();
    }



    const columnsSkelton: any = [
        {
            title: 'S No',
            key: 'sno',
            responsive: ['sm'],
            width: 50, align: 'center',
            fixed: 'left',
            // render: (text, object, index) => (page - 1) * 10 + (index + 1)
            render: (text, object, index) => (page - 1) * pageSize + (index + 1),

        },
        {
            title: 'EMP Code',
            dataIndex: "employee_code", ...getColumnSearchProps("employee_code"),
            fixed: 'left',

        },
        {
            title: 'Name',
            dataIndex: "",
            ...getColumnSearchProps("employee_name"),
            render: (text, record) => {
                return <span>{record.employee_name} {record.emp_last_name}</span>

            },
            fixed: 'left',
            align: 'left'
        },
        {
            title: 'Payroll Month',
            dataIndex: "payroll_month",

        },
        {
            title: 'Department',
            dataIndex: "dept_name",
            sorter: (a, b) => a.dept_name?.localeCompare(b.dept_name),
            ...getColumnSearchProps("dept_name"),
            align: 'left'
        },
        {
            title: 'Act',
            dataIndex: '',
            children: [
                {
                    title: 'Act Basic',
                    dataIndex: 'basic',
                    align: 'right',
                    render: (text, record) => {
                        const basicAmount = Number(record.basic);

                        const formattedBasicAmount = basicAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedBasicAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act HRA',
                    dataIndex: 'hra_amount',
                    align: 'right',
                    render: (text, record) => {
                        const hraAmount = Number(record.basic);

                        const formattedHraAmount = hraAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedHraAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act EDU',
                    dataIndex: 'edu_amount',
                    align: 'right',
                    render: (text, record) => {
                        const eduAmount = Number(record.edu_amount);

                        const formattedEDUAmount = eduAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedEDUAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Medical',
                    dataIndex: 'medical_amount',
                    align: 'right',
                    width: 80,
                    render: (text, record) => {
                        const medAmount = Number(record.medical_amount);

                        const formattedMedAmount = medAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedMedAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Spl',
                    dataIndex: 'spl_amount',
                    align: 'right',
                    render: (text, record) => {
                        const splAmount = Number(record.spl_amount);

                        const formattedSplAmount = splAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedSplAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Conveyance',
                    dataIndex: 'conveyance_amount',
                    align: 'right',
                    width: 100,
                    render: (text, record) => {
                        const conveyanceAmount = Number(record.conveyance_amount);

                        const formattedConveyanceAmount = conveyanceAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedConveyanceAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Petrol',
                    dataIndex: 'petrol_Amount',
                    align: 'right',
                    width: 90,
                    render: (text, record) => {
                        const petrolAmount = Number(record.petrol_Amount);

                        const formattedPetrolAmount = petrolAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedPetrolAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Shoe',
                    dataIndex: 'shoe_amount',
                    align: 'right',
                    width: 70,
                    render: (text, record) => {
                        const shoeAmount = Number(record.shoe_amount);

                        const formattedShoeAmount = shoeAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedShoeAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act washing',
                    dataIndex: 'washing_amount',
                    align: 'right',
                    width: 80,
                    render: (text, record) => {
                        const washingAmount = Number(record.washing_amount);

                        const formattedWashingAmount = washingAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedWashingAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Uniform',
                    dataIndex: 'uniform_amount',
                    align: 'right',
                    width: 80,
                    render: (text, record) => {
                        const uniformAmount = Number(record.uniform_amount);

                        const formattedUniformAmount = uniformAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedUniformAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Helper',
                    dataIndex: 'helper_amount',
                    width: 70,
                    align: 'right',
                    render: (text, record) => {
                        const helperAmount = Number(record.helper_amount);

                        const formattedHelperAmount = helperAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedHelperAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Production',
                    dataIndex: 'production_amount',
                    align: 'right',
                    width: 100,
                    render: (text, record) => {
                        const productionAmount = Number(record.production_amount);

                        const formattedProductionAmount = productionAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedProductionAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act TA',
                    dataIndex: 'ta_amount',
                    align: 'right',
                    width: 70,
                    render: (text, record) => {
                        const taAmount = Number(record.ta_amount);

                        const formattedTaAmount = taAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedTaAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Bonus',
                    dataIndex: 'bonus_amount',
                    align: 'right',
                    width: 80,
                    render: (text, record) => {
                        const bonusAmount = Number(record.bonus_amount);

                        const formattedBonusAmount = bonusAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedBonusAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Act Gross',
                    dataIndex: 'gross',
                    align: 'right',
                    width: 70,
                    render: (text, record) => {
                        const grossAmount = Number(record.gross);

                        const formattedGrossAmount = grossAmount.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedGrossAmount}
                            </div>
                        );
                    },
                },
                {
                    title: 'Incentive Amount per Hr',
                    dataIndex: 'incentive_amount_per_hr',
                    align: 'right',
                    width: 100,
                    render: (text, record) => {
                        const incentiveAmountPerHr = Number(record.incentive_amount_per_hr);

                        const formattedIncentiveAmountPerHr = incentiveAmountPerHr.toLocaleString('en-IN');

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedIncentiveAmountPerHr}
                            </div>
                        );
                    },
                },

            ]
        },

        {
            title: 'Employee Salary Earnings Per Month',
            dataIndex: '',
            children: [
                {
                    title: 'Basic',
                    dataIndex: 'cal_basic',
                    align: 'right',
                    render: (text, record) => {
                        const calBasic = parseFloat(record.cal_basic);

                        const formattedCalBasic = calBasic.toLocaleString('en-IN', {
                            maximumFractionDigits: 2,
                        });

                        return (
                            <div style={{ textAlign: 'right' }}>
                                {formattedCalBasic}
                            </div>
                        );
                    },
                },
                {
                    title: 'HRA',
                    dataIndex: 'cal_hra',
                    align: 'right',
                },
                {
                    title: 'EDU',
                    dataIndex: "cal_edu",
                    align: 'right'
                },
                {
                    title: 'Medical',
                    dataIndex: 'cal_medical',
                    align: 'right',
                    width: 80,
                    render: (text, record) => {
                        const medValue = parseFloat(text);

                        const formattedMed = medValue.toLocaleString('en-IN');

                        return formattedMed;
                    },
                },

                {
                    title: 'SPL',
                    dataIndex: 'cal_spl',
                    align: 'right',
                    render: (text, record) => {
                        const splValue = parseFloat(text);

                        const calFormattedSpl = splValue.toLocaleString('en-IN');

                        return calFormattedSpl;
                    },
                },

                {
                    title: 'Conveyance',
                    dataIndex: "cal_conveyance",
                    width: 70,
                    align: 'right'
                },
                {
                    title: 'Petrol',
                    dataIndex: "cal_petrol",
                    width: 70,
                    align: 'right'
                },
                {
                    title: 'Shoe',
                    dataIndex: "cal_shoe",
                    width: 70,
                    align: 'right'
                },
                {
                    title: 'Washing',
                    dataIndex: "cal_washing",
                    width: 80,
                    align: 'right'
                },
                {
                    title: 'Uniform',
                    dataIndex: "cal_uniform",
                    width: 80,
                    align: 'right'
                },
                {
                    title: 'Helper',
                    dataIndex: "cal_helper",
                    width: 70,
                    align: 'right'
                },
                {
                    title: 'Production',
                    dataIndex: "cal_production",
                    align: 'right',
                    width: 90,
                },
                {
                    title: 'TA',
                    dataIndex: "cal_ta",
                    align: 'right'
                },
                {
                    title: 'Bonus',
                    dataIndex: "cal_bonus",
                    align: 'left'
                },
                {
                    title: 'Gross',
                    dataIndex: "cal_gross",
                    align: 'left'
                },
                {
                    title: 'Incentive Amount',
                    dataIndex: "incentive_amount",
                    width: 100,
                    align: 'left'
                },
            ]
        },
        {
            title: <div style={{ color: 'green' }}>Total Earnings</div>,
            dataIndex: 'total_earnings',
            align: 'right',
            render: (text, record) => (
                <div>{parseFloat(record.total_earnings).toLocaleString('en-IN')}</div>
            ),
        },
        {
            title: 'Employee Salary Deductions Per Month',
            dataIndex: '',
            children: [
                {
                    title: 'P.F',
                    dataIndex: 'epf_amount',
                    align: 'right',
                },
                {
                    title: 'ESIC',
                    dataIndex: "esic_amount",
                    width: 70,
                    align: 'right'
                },
                {
                    title: 'Mess',
                    dataIndex: "mess_d",
                    width: 80,
                    align: 'right'
                },
                {
                    title: 'Other',
                    dataIndex: "others_d",
                    width: 80,
                    align: 'right'
                },
                {
                    title: 'TDS',
                    dataIndex: "tds",
                    align: 'right',
                    width: 70,

                },
                {
                    title: 'PROF Tax',
                    dataIndex: "Professional_tax",
                    width: 100,
                    align: 'right'
                },

            ]
        },

        {
            title: 'Total Deductions',
            dataIndex: "total_deductions",
            width: 100,
            render: (text, record) => {
                const deductionsValue = parseFloat(text);
                const formattedDeductions = deductionsValue.toLocaleString('en-IN');

                return formattedDeductions;
            },
            align: 'right'
        },
        {
            title: 'Net Salary',
            dataIndex: 'net_salary',
            sorter: (a, b) => a.net_salary?.localeCompare(b.net_salary),
            render: (text, record) => {
                const net = Number(record.net_salary);

                const formattedNet = net.toLocaleString('en-IN'); // Format using Indian numeric system

                const netSalaryRender = {
                    children: (
                        <div
                            style={{
                                backgroundColor: net < 0 ? '#FA6F5C' : 'transparent',
                                color: net < 0 ? 'white' : 'black',
                                border: 'none', // Remove borders
                            }}
                        >
                            {formattedNet}
                        </div>
                    ),
                    props: {
                        style: { textAlign: 'right' },
                    },
                };

                return netSalaryRender;
            },
            align: 'right',
        },

        {
            title: 'Freeze Status',
            dataIndex: "freeze_status",
            fixed: 'right',
            sorter: (a, b) => a.freeze_status?.localeCompare(b.freeze_status),
            align: 'center',
            render: (freezeStatus) => {
                return freezeStatus === 1 ? 'Freezed' : 'Not Freezed';
            },
        },

    ];

    const handleExport = (e: any) => {
        e.preventDefault();

        const currentDate = new Date()
            .toISOString()
            .slice(0, 10)
            .split("-")
            .join("/");

        let exportingColumns: IExcelColumn[] = []
        exportingColumns = [
            {
                title: 'EMP Code',
                dataIndex: "employee_code",
                align: 'left',

            },
            {
                title: 'Name',
                dataIndex: "employee_name",
                align: 'left'
            },
            {
                title: 'Payroll Month',
                dataIndex: "payroll_month",

            },
            {
                title: 'Department',
                dataIndex: "dept_name",
                align: 'left'
            },
            {
                title: 'Act',
                dataIndex: '',
                children: [
                    {
                        title: 'Act Basic',
                        dataIndex: 'basic',
                        align: 'right',
                        render: (text, record) => {
                            const basicAmount = Number(record.basic);

                            const formattedBasicAmount = basicAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedBasicAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act HRA',
                        dataIndex: 'hra_amount',
                        align: 'right',
                        render: (text, record) => {
                            const hraAmount = Number(record.basic);

                            const formattedHraAmount = hraAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedHraAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act EDU',
                        dataIndex: 'edu_amount',
                        align: 'right',
                        render: (text, record) => {
                            const eduAmount = Number(record.edu_amount);

                            const formattedEDUAmount = eduAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedEDUAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Medical',
                        dataIndex: 'medical_amount',
                        align: 'right',
                        render: (text, record) => {
                            const medAmount = Number(record.medical_amount);

                            const formattedMedAmount = medAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedMedAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Spl',
                        dataIndex: 'spl_amount',
                        align: 'right',
                        render: (text, record) => {
                            const splAmount = Number(record.spl_amount);

                            const formattedSplAmount = splAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedSplAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Conveyance',
                        dataIndex: 'conveyance_amount',
                        align: 'right',
                        render: (text, record) => {
                            const conveyanceAmount = Number(record.conveyance_amount);

                            const formattedConveyanceAmount = conveyanceAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedConveyanceAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Petrol',
                        dataIndex: 'petrol_Amount',
                        align: 'right',
                        render: (text, record) => {
                            const petrolAmount = Number(record.petrol_Amount);

                            const formattedPetrolAmount = petrolAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedPetrolAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Shoe',
                        dataIndex: 'shoe_amount',
                        align: 'right',
                        render: (text, record) => {
                            const shoeAmount = Number(record.shoe_amount);

                            const formattedShoeAmount = shoeAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedShoeAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act washing',
                        dataIndex: 'washing_amount',
                        align: 'right',
                        render: (text, record) => {
                            const washingAmount = Number(record.washing_amount);

                            const formattedWashingAmount = washingAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedWashingAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Uniform',
                        dataIndex: 'uniform_amount',
                        align: 'right',
                        render: (text, record) => {
                            const uniformAmount = Number(record.uniform_amount);

                            const formattedUniformAmount = uniformAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedUniformAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Helper',
                        dataIndex: 'helper_amount',
                        align: 'right',
                        render: (text, record) => {
                            const helperAmount = Number(record.helper_amount);

                            const formattedHelperAmount = helperAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedHelperAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Production',
                        dataIndex: 'production_amount',
                        align: 'right',
                        render: (text, record) => {
                            const productionAmount = Number(record.production_amount);

                            const formattedProductionAmount = productionAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedProductionAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act TA',
                        dataIndex: 'ta_amount',
                        align: 'right',
                        render: (text, record) => {
                            const taAmount = Number(record.ta_amount);

                            const formattedTaAmount = taAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedTaAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Bonus',
                        dataIndex: 'bonus_amount',
                        align: 'right',
                        render: (text, record) => {
                            const bonusAmount = Number(record.bonus_amount);

                            const formattedBonusAmount = bonusAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedBonusAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Act Gross',
                        dataIndex: 'gross',
                        align: 'right',
                        render: (text, record) => {
                            const grossAmount = Number(record.gross);

                            const formattedGrossAmount = grossAmount.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedGrossAmount}
                                </div>
                            );
                        },
                    },
                    {
                        title: 'Incentive Amount per Hr',
                        dataIndex: 'incentive_amount_per_hr',
                        align: 'right',
                        render: (text, record) => {
                            const incentiveAmountPerHr = Number(record.incentive_amount_per_hr);

                            const formattedIncentiveAmountPerHr = incentiveAmountPerHr.toLocaleString('en-IN');

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedIncentiveAmountPerHr}
                                </div>
                            );
                        },
                    },

                ]
            },

            {
                title: 'Employee Salary Earnings Per Month',
                dataIndex: '',
                children: [
                    {
                        title: 'Basic',
                        dataIndex: 'cal_basic',
                        align: 'right',
                        render: (text, record) => {
                            const calBasic = parseFloat(record.cal_basic);

                            const formattedCalBasic = calBasic.toLocaleString('en-IN', {
                                maximumFractionDigits: 2,
                            });

                            return (
                                <div style={{ textAlign: 'right' }}>
                                    {formattedCalBasic}
                                </div>
                            );
                        },
                    },


                    {
                        title: 'HRA',
                        dataIndex: 'cal_hra',
                        align: 'right',
                    },
                    {
                        title: 'EDU',
                        dataIndex: "cal_edu",
                        align: 'right'
                    },
                    {
                        title: 'Medical',
                        dataIndex: 'cal_medical',
                        align: 'right',
                        render: (text, record) => {
                            const medValue = parseFloat(text);

                            const formattedMed = medValue.toLocaleString('en-IN');

                            return formattedMed;
                        },
                    },

                    {
                        title: 'SPL',
                        dataIndex: 'cal_spl',
                        align: 'right',
                        render: (text, record) => {
                            const splValue = parseFloat(text);

                            const calFormattedSpl = splValue.toLocaleString('en-IN');

                            return calFormattedSpl;
                        },
                    },

                    {
                        title: 'Conveyance',
                        dataIndex: "cal_conveyance",
                        align: 'right'
                    },
                    {
                        title: 'Petrol',
                        dataIndex: "cal_petrol",
                        align: 'right'
                    },
                    {
                        title: 'Shoe',
                        dataIndex: "cal_shoe",
                        align: 'right'
                    },
                    {
                        title: 'Washing',
                        dataIndex: "cal_washing",
                        align: 'right'
                    },
                    {
                        title: 'Uniform',
                        dataIndex: "cal_uniform",
                        align: 'right'
                    },
                    {
                        title: 'Helper',
                        dataIndex: "cal_helper",
                        align: 'right'
                    },
                    {
                        title: 'Production',
                        dataIndex: "cal_production",
                        align: 'right'
                    },
                    {
                        title: 'TA',
                        dataIndex: "cal_ta",
                        align: 'right'
                    },
                    {
                        title: 'Bonus',
                        dataIndex: "cal_bonus",
                        align: 'left'
                    },
                    {
                        title: 'Gross',
                        dataIndex: "cal_gross",
                        align: 'left'
                    },
                    {
                        title: 'Incentive Amount',
                        dataIndex: "incentive_amount",
                        align: 'left'
                    },
                ]
            },
            {
                title: 'Total Earnings',
                dataIndex: 'total_earnings',
                align: 'right',
                render: (text, record) => (
                    <div>{parseFloat(record.total_earnings).toLocaleString('en-IN')}</div>
                ),
            },
            {
                title: 'Employee Salary Deductions Per Month',
                dataIndex: '',
                children: [
                    {
                        title: 'P.F. Amount',
                        dataIndex: 'epf_amount',
                        align: 'right',
                    },
                    {
                        title: 'ESIC',
                        dataIndex: "esic_amount",
                        align: 'right'
                    },
                    {
                        title: 'Mess',
                        dataIndex: "mess_d",
                        align: 'right'
                    },
                    {
                        title: 'Other',
                        dataIndex: "others_d",
                        align: 'right'
                    },
                    {
                        title: 'TDS',
                        dataIndex: "tds",
                        align: 'right'
                    },
                    {
                        title: 'PROF Tax',
                        dataIndex: "Professional_tax",
                        align: 'right'
                    },

                ]
            },

            {
                title: 'Total Deductions',
                dataIndex: "total_deductions",
                // width:'60px',
                render: (text, record) => {
                    const deductionsValue = parseFloat(text);
                    const formattedDeductions = deductionsValue.toLocaleString('en-IN');

                    return formattedDeductions;
                },
                align: 'right'
            },
            {
                title: 'Net Salary',
                dataIndex: 'net_salary',
                render: (text, record) => {
                    const net = Number(record.net_salary);

                    const formattedNet = net.toLocaleString('en-IN'); // Format using Indian numeric system

                    const netSalaryRender = {
                        children: (
                            <div
                                style={{
                                    backgroundColor: net < 0 ? '#FA6F5C' : 'transparent',
                                    color: net < 0 ? 'white' : 'black',
                                    border: 'none', // Remove borders
                                }}
                            >
                                {formattedNet}
                            </div>
                        ),
                        props: {
                            style: { textAlign: 'right' },
                        },
                    };

                    return netSalaryRender;
                },
                align: 'right',
            },

        ];

        const excel = new Excel();
        excel.addSheet("Sheet1");
        // excel.addRow();
        excel.addColumns(exportingColumns);
        excel.addDataSource(rowData);
        excel.saveAs(`employee-wise-payroll-${currentDate}.xlsx`);
    }
    const getPayrollData = () => {

        const req = new PayRollMonthDto();
        const payrollReq = new PayRollRequest();

        if ((form.getFieldValue('year') !== undefined) && (form.getFieldValue('year') !== null)) {
            req.years = (form.getFieldValue('year')).format('YYYYMM');
            req.month = (form.getFieldValue('year')).format('YYYYMM');
            payrollReq.month = Number((form.getFieldValue('year')).format('YYYYMM'))
        }

        if ((form.getFieldValue('department') !== undefined) && (form.getFieldValue('year') !== null)) {
            req.department = form.getFieldValue('department');
            payrollReq.department = form.getFieldValue('department');
        }
        if ((form.getFieldValue('employeeId') !== undefined) && (form.getFieldValue('year') !== null)) {
            req.employeeId = form.getFieldValue('employeeId');
        }
        if (form.getFieldValue('empType') !== undefined) {
            req.empType = form.getFieldValue('empType');
        }
        service.getAllPayrollLogs(req).then((res) => {
            if (res.status) {
                setRowData(res.data);
                if (rowData.length === 0) {
                    // message.info("No relavent data");

                }
                else (rowData.length > 0)
                {
                    message.success(res.internalMessage);

                }
            } else {
                message.error("No relavent data is their for your selected option");
                setRowData([]);
            }
        })

    };

    return (
        <Card
            title={<span style={{ color: 'white' }}>Employee Wise Payroll</span>} extra={<Button onClick={handleExport}>Get Excel</Button>}
            style={{ textAlign: 'center' }}
            headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        >
            <Form form={form} layout="horizontal" onFinish={getPayrollData}>
                <Row gutter={24}>
                    <Col xs={24} sm={24} md={12} lg={6} xl={6}>
                        <Form.Item name='year' label='Payroll Month' >
                            <DatePicker picker='month' />
                        </Form.Item>
                    </Col>
                    {/* <Col xs={24} sm={24} md={12} lg={8} xl={8}>
                        <Form.Item
                            name="employeeId"
                            label="Employee Name"
                            rules={[{ required: false, message: "name is required" }]}
                        >
                            <Select
                                showSearch
                                placeholder="Select Employee Name"
                                optionFilterProp="children"
                                onFocus={onFocus}
                                onBlur={onBlur}
                                onSearch={onSearch}
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            >
                                {employeeData.map((employeeData) => (
                                    <Option key={employeeData.employeeId} value={employeeData.employeeId}>
                                        {`${employeeData.employeeName} ${employeeData.employeeLastName}`}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </Col> */}

                    <Col xs={24} sm={24} md={12} lg={8} xl={8}>
                        <Form.Item>
                            <Button htmlType="submit" icon={<SearchOutlined />} type="primary" style={{ marginRight: '10px' }}>
                                GET REPORT
                            </Button>
                            <Button
                                style={{ color: 'white', backgroundColor: '#067515', fontSize: 13, marginRight: '10px' }}
                                onClick={changeHandler}
                                type="primary"
                                disabled={rowData.length === 0 || rowData[5]?.freeze_status === 1}
                            >
                                Freeze
                            </Button>
                            <Button
                                style={{ color: 'white', backgroundColor: '#F5AE97', fontSize: 13 }}
                                onClick={showModal1}
                                disabled={rowData.length === 0 || rowData[0]?.freeze_status === 0}
                            >
                                Un-Freeze
                            </Button>
                        </Form.Item>
                    </Col>
                </Row>
                {rowData.length === 0 && (
                    <div style={{
                        position: 'fixed',
                        left: '50%',
                        transform: 'translate(-53%, -70%)',
                        textAlign: 'center',
                        borderRadius: '5px',
                    }}>
                        <p style={{ color: 'red' }}>
                            Without selecting any filter you cannot freeze or unfreeze
                        </p>
                    </div>
                )}



            </Form>

            {
                rowData && rowData.length > 0 ? (
                    <>
                        <Table
                            className='custom-table-wrapper'
                            rowKey={(record) => record}
                            columns={columnsSkelton}
                            dataSource={rowData}
                            // pagination={{
                            //   onChange(current, pageSize) {
                            //     setPage(current);
                            //     setPageSize(pageSize);
                            //   }
                            // }}
                            pagination={false}
                            scroll={{ x: 'max-content', y: 500 }}
                            bordered

                        />
                    </>
                ) : (
                    <>
                        <Table
                            className='custom-table-wrapper'
                            scroll={{ x: 'max-content' }}
                            bordered
                        />
                    </>)
            }
            <Modal
                className='print-docket-modal'
                key={'modal1' + Date.now()}
                width={'30%'}
                style={{ top: 30, alignContent: 'center' }}
                visible={isModalOpen1}

                footer={null}
                title={<React.Fragment>

                </React.Fragment>}
                onCancel={cancelHandle}

            >
                <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                    <p style={{ marginRight: '10px' }}>Are you sure want to Un-Freeze this Payroll Month:</p>
                    <p style={{ color: 'red', fontSize: 20 }}>{rowData[0]?.payroll_month}</p>
                </div>
                <div >
                    <Popconfirm title='Sure to UN-Freeze?' onConfirm={() => deleteData()}>
                        <Checkbox
                            onChange={(e) => setFreezeStatus(e.target.checked ? 0 : 1)}
                            defaultChecked={false}
                        >
                            Confirm Unfreezing
                        </Checkbox>
                    </Popconfirm>

                </div>

            </Modal>
        </Card >
    );
}
export default generatedPayGrid;
