import { forwardRef, useCallback, useState } from "react";
import { DefaultModal } from "../../../Components/Modal/DefaultModal";
import { Form } from "antd";
import { DropDowns } from "../../../Components/Forms/DropDown";
import { InputField } from "../../../Components/Forms/InputField";
import { getSession, validateSafeInput } from "../../../Services/Others";
import { useDispatch } from "react-redux";
import { Messages } from "../../../Components/Notifications/Messages";
import { DatePic } from '../../../Components/Forms/DatePicker.jsx';
import { getAdmin as getTax } from "../../../Features/Tax/Tax.js";
import { getAdmin, postTax } from "../../../Features/ProductPage/ProductPage.js";
const AddTaxModal = forwardRef((
    {
        open = false,
        close = () => { },
        prodTaxData = [],
        flag = false,
    }, ref) => {

    const dispatch = useDispatch();
    console.log(prodTaxData, 'prodTaxData in modal');
    const AppId = getSession('AppId');
    const CompId = getSession('CompId');
    const UserId = getSession('UserId');

    const [messageType, setMessageType] = useState(null);
    const [messageData, setMessageData] = useState(null);
    const [selectedTaxNameId, setSelectedTaxNameId] = useState(null);

    const handleTaxNameDropDownChange = async (ConfigId) => {
        ref.current?.setFieldsValue({ TaxName: ConfigId });
        await setSelectedTaxNameId(ConfigId);
    };

    const handleTaxModalClose = () => {
        close(false);
        setSelectedTaxNameId(null);
        ref.current?.resetFields();
    }

    const handleSubmitTax = async () => {
        try {
            const subTaxData = await ref?.current?.validateFields();
            const effectiveDate = new Date(subTaxData.EffectiveFrom);
            const formattedDate = effectiveDate.toLocaleDateString('en-CA');
            const addTaxData = {
                CompId: CompId,
                AppId: AppId,
                TaxName: subTaxData?.TaxName,
                TaxPercentage: subTaxData?.TaxPercentage,
                EffectiveFrom: formattedDate,
                Reference: subTaxData.Reference,
                CreatedBy: UserId,
            };

            const response = await dispatch(postTax(addTaxData)).unwrap();
            if (response?.data?.statusCode == 1) {
                setMessageType('success');
                setMessageData(response?.data?.response);
                close(false);
                if (flag) {
                    await dispatch(getTax({ CompId: CompId, AppId: AppId }));
                } else {
                    await dispatch(getAdmin({ CompId: CompId, AppId: AppId }));
                }
                ref?.current?.resetFields();
                setSelectedTaxNameId(null);
            } else {
                setMessageType('error');
                setMessageData(response?.data?.response);
            }
        } catch (error) {
            console.log('Error:', error?.message);
        }
    };

    const onComplete = useCallback(() => {
        setMessageType(null);
        setMessageData(null);
    }, []);

    return (
        <>
            <Messages messageData={messageData} messageType={messageType} onComplete={onComplete} />
            <DefaultModal
                title="Add Tax"
                open={open}
                footer={true}
                buttonText="Submit"
                children={
                    <Form ref={ref} className="formDivAnt">
                        <div className="ProSubRowFlex">
                            <Form.Item name="TaxName">
                                <DropDowns
                                    options={prodTaxData?.map((option) => ({
                                        value: option.ConfigId,
                                        label: option.ConfigName,
                                    }))}
                                    label="Tax Name"
                                    className="field-DropDown"
                                    onChangeFunction={handleTaxNameDropDownChange}
                                    valueData={selectedTaxNameId}
                                />
                            </Form.Item>

                            <Form.Item
                                name="TaxPercentage"
                                rules={[
                                    {
                                        required: true,
                                        pattern: /^(?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?)$/,
                                        message: 'Please Enter Valid Percentage',
                                    },
                                    {
                                        validator: async (_, value) => {
                                            await validateSafeInput(value); // To block HTML tags & SQL keywords
                                            return Promise.resolve();
                                        },
                                    },
                                ]}
                            >
                                <InputField
                                    autoComplete="off"
                                    label="Tax Percentage"
                                    inputMode="decimal"
                                    onInput={(e) => {
                                        let cleanedValue = e.target.value.replace(
                                            /[^0-9.]/g,
                                            ''
                                        ); // Remove invalid characters
                                        const parts = cleanedValue.split('.');

                                        if (cleanedValue.startsWith('.')) {
                                            cleanedValue = '0' + cleanedValue;
                                        }

                                        e.target.value =
                                            parts.length > 2
                                                ? `${parts[0]}.${parts.slice(1).join('')}`
                                                : cleanedValue;
                                    }}
                                />
                            </Form.Item>

                            <Form.Item
                                name="Reference"
                                rules={[
                                    {
                                        pattern: /^(?!\s*$).+/,
                                        message: 'Please Enter Reference',
                                    },
                                    {
                                        validator: async (_, value) => {
                                            await validateSafeInput(value); // To block HTML tags & SQL keywords
                                            return Promise.resolve();
                                        },
                                    },
                                ]}
                            >
                                <InputField label="Reference No" autoComplete="off" />
                            </Form.Item>
                            <div>
                                <label className="required">Effective From :</label>
                            </div>

                            <Form.Item
                                name="EffectiveFrom"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please Enter Effective From',
                                    },
                                ]}
                            >
                                <DatePic
                                    field="EffectiveFrom"
                                    type="number"
                                    min={1}
                                    max={100}
                                    fieldState={true}
                                />
                            </Form.Item>
                        </div>
                    </Form>
                }
                handleSubmit={handleSubmitTax}
                handleCancel={handleTaxModalClose}
            />
        </>
    )
});

export default AddTaxModal;