import React, { useEffect,useRef, useState } from 'react';
import { Form, Tooltip } from 'antd';
import { PlusCircleOutlined } from '@ant-design/icons';
import { DefaultModal } from "../../Components/Modal/DefaultModal.jsx";
import { InputField } from "../../Components/Forms/InputField.jsx";
import { postSupplier } from "../../Features/ProductPage/ProductPage.js";
import { useDispatch } from 'react-redux';
import { getSession, validateSafeInput } from '../../Services/Others.js';
import {getConfigType} from '../../Features/BookingScreen/BookingData/BookingData.js';
import { DropDowns } from '../../Components/Forms/DropDown.jsx';

const AddSupplierModal = ({
  onSupplierAdded,
  message,
}) => {
  const dispatch = useDispatch();
  const formSupplierRef = useRef(null);

  const UserId = getSession('UserId');
  const CompId = getSession('CompId');
  const AppId = getSession('AppId');
  const BranchId = getSession('BranchId');

const [openPurSupplierModel, setOpenPurSupplierModel] = useState(false);
const [zipCodeData, setZipCodeData] = useState(false);
const [deliveryPerformanceData, SetDeleveryPerformanceData] = useState([]);
const [DiscountData, setDiscountData] = useState([]);
const [QualityData, setQualityData] = useState([]);
const [Delivery, setDeliveryValue] = useState();
const [DicountValue, setDicountValue] = useState();
const [QualityValue, setQualityValue] = useState();
const [ViewDtl, setViewDtl] = useState(false);

useEffect(() => {
  deliveryPerformance();
  discountLevel();
  qualityofSupp();
}, []);

  const addPurSupplier = () => {
    setOpenPurSupplierModel(true);
  };

  const pinCodeChange = async (e) => {
    if (e.target.value?.length < 6) {
      setZipCodeData(false);
      return false;
    }
    await getPincodeValues(e?.target?.value);
  };

  const getPincodeValues = async (pinCode) => {
    try {
      const response = await fetch(`https://api.postalpincode.in/pincode/${pinCode}`);
      const data = await response.json();

      if (data[0]["Status"] === "Success") {
        setZipCodeData(true);
        formSupplierRef.current?.setFieldsValue({
          City: data[0]["PostOffice"][0]["Block"],
          Dist: data[0]["PostOffice"][0]["District"],
          State: data[0]["PostOffice"][0]["State"],
        });
      } else {
        setZipCodeData(false);
      }
    } catch (error) {
      console.error('Error fetching pincode data:', error);
      setZipCodeData(false);
    }
  };

  const submitSupplier = async () => {
    try {
      const subSupplierData = await formSupplierRef?.current?.validateFields();
      const addSupplierData = {
        CompId,
        AppId,
        BranchId,
        SuppName: subSupplierData?.SuppName,
        SuppGSTIN: subSupplierData?.SuppGSTIN,
        SuppPOC: subSupplierData?.SuppPOC,
        SuppMobile: subSupplierData?.SuppMobile,
        SuppEmail: subSupplierData?.SuppEmail,
        Address1: subSupplierData?.Address1,
        Address2: subSupplierData?.Address1,
        Zip: subSupplierData?.Zip,
        City: subSupplierData?.City,
        State: subSupplierData?.State,
        Dist: subSupplierData?.Dist,
        SuppPOCMobile: subSupplierData?.SuppPOCMobile,
        SuppPOCEmail: subSupplierData?.SuppPOCEmail,
        DeliveryPerformance: subSupplierData?.DeliveryPerformance,
        DiscountLevel: subSupplierData?.DiscountLevel,
        QualityofSupp: subSupplierData?.QualityofSupp,
        CreatedBy: UserId,
      };



      const response = await dispatch(postSupplier(addSupplierData)).unwrap();

      if (response?.data?.statusCode === 1) {
        message({type: "success", data: response?.data?.response});
        formSupplierRef?.current?.resetFields();
        setZipCodeData(false);
        setOpenPurSupplierModel(false);
        setDeliveryValue();
        setDicountValue();
        setQualityValue();
        setViewDtl(false);
        // Call the callback function to refresh supplier data
        if (onSupplierAdded && typeof onSupplierAdded === 'function') {
          await onSupplierAdded();
        }
      } else {
         message({type: "error", data: response?.data?.response});
        formSupplierRef?.current?.resetFields();
      }
    } catch (error) {
      console.error('Error submitting supplier:', error);
      message({type: "error", data: "Failed to add supplier. Please try again."});
    }
  };

  const handleSupplier = () => {
    setOpenPurSupplierModel(false);
    formSupplierRef?.current?.resetFields();
    setZipCodeData(false);
  };

const handleDeliveryPerformanceChange = (value) => {
  formSupplierRef?.current?.setFieldsValue({ DeliveryPerformance: value });
  setDeliveryValue(value);
};

const handleDiscountLevelChange = (value) => {
  formSupplierRef?.current?.setFieldsValue({ DiscountLevel: value });
  setDicountValue(value);
};

const handleQualityofSuppChange = (value) => {
  formSupplierRef?.current?.setFieldsValue({ QualityofSupp: value });
  setQualityValue(value);
};

const ViewMoreFields = () =>{

  if(ViewDtl){
  setViewDtl(false)
  }else{
  setViewDtl(true)
  }

}

const deliveryPerformance = async () => {
  let response = await dispatch(
    getConfigType({ TypeName: 'Delivery Performance' })
  ).unwrap();
  SetDeleveryPerformanceData(response?.data?.data);
};

const discountLevel = async () => {
  let response = await dispatch(
    getConfigType({ TypeName: 'Discount Level' })
  ).unwrap();
  setDiscountData(response?.data?.data);
};

const qualityofSupp = async () => {
  let response = await dispatch(
    getConfigType({ TypeName: 'Quality Of Supplier' })
  ).unwrap();
  setQualityData(response?.data?.data);
};

const validatePhoneNumber = (rule, value, callback) => {
  if (value && value?.length !== 10) {
    callback();
  } else {
    callback();
  }
};

const validateEmail = (rule, value, callback) => {
  const regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

  if (!value || regex.test(value)) {
    callback();
  } else {
    callback('Please enter a valid Mail Id');
  }
};


  return (
    <div style={{position: "absolute", left : "16rem",top:"1px"}}>
      <Tooltip title={"Add Supplier"} placement={"top"}>
        <PlusCircleOutlined onClick={addPurSupplier} />
      </Tooltip>

      <DefaultModal
        title="Add Supplier"
        open={openPurSupplierModel}
        footer={true}
        buttonText="Submit"
        handleSubmit={submitSupplier}
        handleCancel={handleSupplier}
      >
        <Form ref={formSupplierRef} className="formDivAnt">
          <div className='subRowFlex'>
            <Form.Item
              name="SuppName"
              rules={[
                {
                  required: true,
                  pattern: /^(?!\s*$).+/,
                  message: "Please Enter Supplier Name",
                },
                {
                  validator: async (_, value) => {
                    await validateSafeInput(value);
                    if (value && value.length > 30) {
                      return Promise.reject("Supplier Name should not exceed 30 characters");
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <InputField
                label={<label className="required">Supplier Name</label>}
                autoComplete="off"
              />
            </Form.Item>

            <Form.Item
              name="Address1"
              rules={[
                {
                  required: true,
                  pattern: /^(?!\s*$).+/,
                  message: "Please Enter Address1",
                },
                {
                  validator: async (_, value) => {
                    await validateSafeInput(value);
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <InputField
                autoComplete="off"
                label={<label className="required">Address</label>}
              />
            </Form.Item>

            <Form.Item
              name="Zip"
              rules={[
                {
                  required: true,
                  pattern: /^(?!\s*$).+/,
                  message: "Please Enter Zipcode",
                },
                {
                  validator: async (_, value) => {
                    await validateSafeInput(value);
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <InputField
                autoComplete="off"
                label={<label className="required">Zipcode</label>}
                maxLength="6"
                onChange={pinCodeChange}
              />
            </Form.Item>

 <p style={{color:'#1292ee',justifyContent:'end'}} onClick={ViewMoreFields}> {ViewDtl ? "Less More" : "View More"}</p>

                    {ViewDtl &&

                      <>
                                          <Form.Item
                                          name="SuppGSTIN"
                                          rules={[
                                            {
                                              pattern:
                                                /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Za-z]{1}[Z]{1}[0-9A-Za-z]{1}$/,
                                              message: 'Enter a valid GSTIN',
                                            },
                                          ]}
                                        >
                                          <InputField
                                            style={{ textTransform: 'uppercase' }}
                                            autoComplete="off"
                                            label="GST No"
                                            maxLength={15}
                                            autocapitalize="on"
                                            // isOnChange={formType == 'edit' ? true : false}
                                          />
                                        </Form.Item>

                                        <Form.Item
                                          name="SuppMobile"
                                          rules={[
                                            {
                                              pattern: /^\d{10}$/,
                                              message: 'Please Enter a Valid Mobile Number',
                                            },

                                            { validator: validatePhoneNumber },
                                          ]}
                                        >
                                          <InputField
                                            label={<label>Mobile Number</label>}
                                            maxLength="10"
                                            autocomplete="off"
                                            // isOnChange={formType == 'edit' ? true : false}
                                            inputMode="numeric"
                                            onInput={(e) =>
                                              (e.target.value = e.target.value.replace(/[^0-9]/g, ''))
                                            }
                                          />
                                        </Form.Item>

                                        <Form.Item
                                          name="SuppEmail"
                                          rules={[{ validator: validateEmail }]}
                                        >
                                          <InputField
                                            label={<label>MailId</label>}
                                            autocomplete="off"
                                            // isOnChange={formType == 'edit' ? true : false}
                                          />
                                        </Form.Item>

                                        <Form.Item
                                          name="SuppPOC"
                                          rules={[
                                            {
                                              pattern: /^(?!\s*$).+/,
                                              message: 'Please Enter Point of Contact Name',
                                            },
                                            {
                                              validator: async (_, value) => {
                                                await validateSafeInput(value);
                                                if (value?.length > 30) {
                                                  return Promise.reject(
                                                    'Point of Contact cannot exceeds more than 30 chars'
                                                  );
                                                }
                                                return Promise.resolve();
                                              },
                                            },
                                          ]}
                                        >
                                          <InputField
                                            label={<label class="">Point of Contact</label>}
                                            autocomplete="off"
                                            // isOnChange={formType == 'edit' ? true : false}
                                          />
                                        </Form.Item>

                                        <Form.Item
                                          name="SuppPOCMobile"
                                          rules={[
                                            {
                                              pattern: /^\d{10}$/,
                                              message: 'Please Enter a Valid Mobile Number',
                                            },
                                            {
                                              //   required: true,
                                              message: 'Please Enter Mobile Number',
                                            },
                                            { validator: validatePhoneNumber },
                                          ]}
                                        >
                                          <InputField
                                            label={<label class="">POC Mobile Number</label>}
                                            autocomplete="off"
                                            maxLength="10"
                                            // isOnChange={formType == 'edit' ? true : false}
                                          />
                                        </Form.Item>

                                        <Form.Item
                                          name="SuppPOCEmail"
                                          rules={[{ validator: validateEmail }]}
                                        >
                                          <InputField
                                            label={<label class="">POC MailId</label>}
                                            autocomplete="off"
                                            // isOnChange={formType == 'edit' ? true : false}
                                          />
                                        </Form.Item>

                                        <Form.Item
                                          name="DeliveryPerformance"
                                          rules={[
                                            {
                                              required: false,
                                              message: 'Please Select DeliveryPerformance',
                                            },
                                          ]}
                                        >
                                          <DropDowns
                                            options={deliveryPerformanceData?.map((option) => ({
                                              value: option.ConfigId,
                                              label: option.ConfigName,
                                            }))}
                                            label={<label>Delivery Performance</label>}
                                            className="field-DropDown"
                                            id="DeliveryPerformance"
                                            onChangeFunction={(e) =>
                                              handleDeliveryPerformanceChange(e)
                                            }
                                            // isOnChange={formType == 'edit' ? true : false}
                                            valueData={Delivery}
                                          />
                                        </Form.Item>

                                        <Form.Item
                                          name="DiscountLevel"
                                          rules={[
                                            {
                                              required: false,
                                              message: 'Please Select DiscountLevel',
                                            },
                                          ]}
                                        >
                                          <DropDowns
                                            options={DiscountData?.map((option) => ({
                                              value: option.ConfigId,
                                              label: option.ConfigName,
                                            }))}
                                            label={<label>Discount Level</label>}
                                            className="field-DropDown"
                                            id="DiscountLevel"
                                            onChangeFunction={(e) => handleDiscountLevelChange(e)}
                                            // isOnChange={formType == 'edit' ? true : false}
                                            valueData={DicountValue}
                                          />
                                        </Form.Item>

                                        <Form.Item
                                          name="QualityofSupp"
                                          rules={[
                                            {
                                              required: false,
                                              message: 'Please Select QualityofSupp',
                                            },
                                          ]}
                                        >
                                          <DropDowns
                                            options={QualityData?.map((option) => ({
                                              value: option.ConfigId,
                                              label: option.ConfigName,
                                            }))}
                                            label={<label>Quality of Supplier</label>}
                                            className="field-DropDown"
                                            id="QualityofSupp"
                                            onChangeFunction={(e) => handleQualityofSuppChange(e)}
                                            // isOnChange={formType == 'edit' ? true : false}
                                            valueData={QualityValue}
                                          />
                                        </Form.Item>
                      </>

                    }

            {zipCodeData && (
              <>
                <Form.Item
                  name="City"
                  rules={[
                    {
                      required: true,
                    },
                    {
                      validator: async (_, value) => {
                        await validateSafeInput(value);
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <InputField
                    disabled={true}
                    isOnChange={true}
                    label="City"
                  />
                </Form.Item>

                <Form.Item
                  name="Dist"
                  rules={[
                    {
                      required: true,
                    },
                    {
                      validator: async (_, value) => {
                        await validateSafeInput(value);
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <InputField
                    disabled={true}
                    isOnChange={true}
                    label="District"
                  />
                </Form.Item>

                <Form.Item
                  name="State"
                  rules={[
                    {
                      required: true,
                    },
                    {
                      validator: async (_, value) => {
                        await validateSafeInput(value);
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <InputField
                    disabled={true}
                    isOnChange={true}
                    label="State"
                  />
                </Form.Item>
              </>
            )}
          </div>
        </Form>
      </DefaultModal>
    </div>
  );
};

export default AddSupplierModal;