
import { useState, useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { InputField } from '../../Components/Forms/InputField.jsx';
import Buttons from '../../Components/Forms/Buttons.jsx';
import { ArrowRightOutlined } from '@ant-design/icons';
import { Messages } from '../../Components/Notifications/Messages.jsx';
import { Form, } from 'antd';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { getSession } from '../../Services/Others.js';
import { useNavigate, useLocation } from 'react-router-dom';

import { getBranchDetail } from '../../Features/BrachLogin/BranchLogin.js';
import { postEInvoice, putEInvoice } from '../../Features/GStInvoice/gstinvoice.js';

const subDirectory = import.meta.env.BASE_URL;

const GstInvoiceSetUpForm = ({ formType }) => {

    const formRef = useRef(null);
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const location = useLocation();
    const state = location?.state;
    const editstate = state?.editstate;

    const CompId = getSession('CompId');
    const BranchId = getSession('BranchId');
    const UserId = getSession('UserId');
    const [messageType, setMessageType] = useState(null);
    const [messageData, setMessageData] = useState(null);
    // const [AppPreference, setAppPreference] = useState([]);
    const [BrGSTIN, setBrGSTIN] = useState([]);
    const [brAddId, SetBrAddId] = useState([]);


    const items = [
        {
            name: 'Home',
            link: `${subDirectory}app-page/home`,
        },

        {
            name: 'GST Invoice Setup',
            link: `${subDirectory}setting/gst-invoice-setup`,
        },
        {
            name: editstate ? 'Edit' : 'New',
            link: null,
        },
    ];



    useEffect(() => {
        dispatch(changeBreadCrumb({ items: items }));
        getBranchGST();
 
    }, []);

    useEffect(() => {
        if (BrGSTIN && formRef.current) {
            formRef.current.setFieldsValue({
                GSTIN: BrGSTIN,
            });
        }
    }, [BrGSTIN]);

    const onFinish = async (values) => {
        try {
            const PostData = {
                CompId,
                BranchId,
                AddId: brAddId,

                GSTNo: values.GSTIN || BrGSTIN,
                LegalName: values.LegalName,
                TradeName: values.TradeName,
                StateCode: values.StateCode,

                ClientId: values.ClientId,
                ClientSecret: values.ClientSecret,
                APIUserName: values.APIUserName,
                APIPassword: values.APIPassword,

                GSPProviderName: values.GSPProviderName || null,
                Remarks: values.Remarks || "",

                CreatedBy: UserId,
            };

            const Response = editstate
                ? await dispatch(putEInvoice(PostData)).unwrap()
                : await dispatch(postEInvoice(PostData)).unwrap();
            if (Response?.data?.statusCode === 1) {
                navigate(`${subDirectory}setting/gst-invoice-setup`, {
                    state: {
                        type: "success",
                        message: editstate
                            ? "GST Invoice Setup updated successfully"
                            : "GST Invoice Setup saved successfully",
                    },
                });

            } else {
                setMessageType("error");
                setMessageData(
                    Response?.data?.response || "Error saving GST Invoice Setup"
                );
            }
        } catch (err) {
            console.error("GST Invoice Error:", err);
            setMessageType("error");
            setMessageData("Something went wrong");
        }
    };

    const getBranchGST = async () => {
        const data = {
            BrId: BranchId
        }
        const response = await dispatch(getBranchDetail(data)).unwrap();
        if (response?.data?.statusCode === 1) {
            setBrGSTIN(response?.data?.data?.[0]?.BrGSTIN)
            SetBrAddId(response?.data?.data?.[0]?.AddId)
        }
        // console.log(response?.data?.data?.[0]?.BrGSTIN, 'getBranchGST');
    }

    // const getApplicationPreference = async () => {
    //     const response = await dispatch(getCommonAppPreference(AppId)).unwrap();
    //     if (response?.data?.statusCode === 1) {
    //         setAppPreference(response?.data?.data);
    //     }
    // };




    return (
        <div className="pageOverAll">
            <div className="userPage">
                <div className="userPageContent">
                    <Messages messageType={messageType} messageData={messageData} />
                    <div className="formName">
                        <FormHeader title={'GST Invoice Setup'} />

                    </div>

                    <div className="formDiv" style={{ scrollbarWidth: 'thin' }}>
                        <Form
                            ref={formRef}
                            className="formDivAnt"
                            onFinish={onFinish}
                            initialValues={{ ...editstate }}
                        >
                            <div className="formDivS">
                                <div className="inputForm">
                                    <Form.Item
                                        name="GSTIN"
                                        rules={[
                                            {
                                                required: true,
                                                pattern: /^(?!\s*$).+/,
                                                message: "Please Enter GST",
                                            },
                                        ]}
                                    >
                                        <InputField
                                            field="GSTIN"
                                            name="GSTIN"
                                            label={<label className="required">GST No</label>}
                                            fieldState={true}
                                            fieldApi={true}
                                            isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.GSTIN ? true : false}
                                            id="error2"
                                            autoComplete="off"
                                        />
                                    </Form.Item>

                                    <Form.Item
                                        name="LegalName"
                                        rules={[
                                            {
                                                required: true,
                                                pattern: /^(?!\s*$).+/,
                                                message: 'Please Enter Legal Name',
                                            }
                                        ]}
                                    >
                                        <InputField
                                            field="Legal Name"
                                            name="LegalName"
                                            label={<label class="required">Legal Name</label>}
                                            fieldState={true}
                                            fieldApi={true}
                                            isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.LegalName ? true : false}
                                            id="error2"
                                            autocomplete="off"

                                        />
                                    </Form.Item>
                                    <Form.Item
                                        name="TradeName"
                                        rules={[
                                            {
                                                required: false,
                                                pattern: /^(?!\s*$).+/,

                                            }

                                        ]}
                                    >
                                        <InputField
                                            field="Trade Name"
                                            name="TradeName"
                                            label={<label >Trade Name </label>}
                                            fieldState={true}
                                            fieldApi={true}
                                            isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.TradeName ? true : false}
                                            id="error2"
                                            autocomplete="off"

                                        />
                                    </Form.Item>
                                    <Form.Item
                                        name="StateCode"
                                        rules={[
                                            {
                                                required: true,
                                                pattern: /^(?!\s*$).+/,
                                                message: 'Please Enter StateCode',
                                            }
                                        ]}
                                    >
                                        <InputField
                                            field="State Code"
                                            name="StateCode"
                                            label={<label class="required">StateCode </label>}
                                            fieldState={true}
                                            fieldApi={true}
                                            isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.StateCode ? true : false}
                                            id="error2"
                                            autocomplete="off"

                                        />
                                    </Form.Item>
                                    <Form.Item
                                        name="APIUserName"
                                        rules={[
                                            {
                                                required: true,
                                                pattern: /^(?!\s*$).+/,
                                                message: 'Please Enter IRPUserName',
                                            }

                                        ]}
                                    >
                                        <InputField
                                            field="APIUserName"
                                            name="APIUserName"
                                            label={<label class="required">IRPUserName </label>}
                                            fieldState={true}
                                            fieldApi={true}
                                            isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.APIUserName ? true : false}
                                            id="error2"
                                            autocomplete="off"

                                        />
                                    </Form.Item>
                                    <Form.Item
                                        name="APIPassword"
                                        rules={[
                                            {
                                                required: true,
                                                pattern: /^(?!\s*$).+/,
                                                message: "Please Enter IRPPassword",
                                            }

                                        ]}
                                    >
                                        <InputField
                                            field="APIPassword"
                                            name="APIPassword"
                                            label={
                                                <label class="required">
                                                    IRPPassword
                                                </label>
                                            }
                                            fieldState={true}
                                            fieldApi={true}
                                            isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.APIPassword ? true : false}
                                            id="error2"
                                            autocomplete="off"
                                        />
                                    </Form.Item>
                                    <Form.Item
                                        name="ClientId"
                                        rules={[
                                            {
                                                // required: true,
                                                pattern: /^(?!\s*$).+/,
                                                message: 'Please Enter PrivateKey',
                                            }

                                        ]}
                                    >
                                        <InputField
                                            field="ClientId"
                                            name="ClientId"
                                            label={<label class="required">PrivateKey </label>}
                                            fieldState={true}
                                            fieldApi={true}
                                            isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.ClientId ? true : false}
                                            id="error2"
                                            autocomplete="off"

                                        />
                                    </Form.Item>

                                    <Form.Item
                                        name="ClientSecret"
                                        rules={[
                                            {
                                                // required: true,
                                                pattern: /^(?!\s*$).+/,
                                                message: 'Please Enter PublicKey',
                                            }

                                        ]}
                                    >
                                        <InputField
                                            field="ClientSecret"
                                            name="ClientSecret"
                                            label={<label class="required">PublicKey</label>}
                                            fieldState={true}
                                            fieldApi={true}
                                            isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.ClientSecret ? true : false}
                                            id="error2"
                                            autocomplete="off"

                                        />
                                    </Form.Item>




                                </div>

                            </div>

                            <div className="submitButton">
                                <Buttons
                                    buttonText="SUBMIT"
                                    color="901D77"
                                    icon={<ArrowRightOutlined />}
                                // handleSubmit={handleSubmit}
                                />
                            </div>
                        </Form>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default GstInvoiceSetUpForm;
