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

const subDirectory = import.meta.env.BASE_URL;

const SupplierForm = ({ formType }) => {
  const formRef = useRef(null);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const state = location?.state;
  const editstate = state?.editstate;

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [SelectedLatitude, setSelectedLatitude] = useState(null);
  const [SelectedLongitude, setSelectedLongitude] = useState(null);
  const [zipCodeData, setZipCodeData] = useState(false);
  const [cmpId, setcmpId] = useState(getSession('CompId'));
  const [brId, setBrId] = useState(getSession('BranchId'));
  const [AppId, setAppId] = useState(getSession('AppId'));
  const AppType = getSession('AppType');
  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 items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },

    {
      name: AppType === 'Wholesale' ? 'Seller' : 'Supplier',
      link: `${subDirectory}setting/supplier-master`,
    },
    {
      name: editstate ? 'Edit' : 'New',
      link: null,
    },
  ];

  useEffect(() => {
    try {
      dispatch(changeBreadCrumb({ items: items }));
      if (!brId) {
        fetchData();
      } else {
        fetchDataBranchBased();
      }
      if (formType === 'edit') {
        if (editstate) {
          console.log('editstate', editstate);
          if (editstate?.Zip) {
            setZipCodeData(true);
          }
          setDeliveryValue(editstate?.DeliveryPerformance);
          setDicountValue(editstate?.DiscountLevel);
          setQualityValue(editstate?.QualityofSupp);
          formRef?.current?.setFieldsValue(editstate);
          setSelectedLatitude(editstate?.Latitude);
          setSelectedLongitude(editstate?.Longitude);
        } else {
          navigate(`${subDirectory}setting/supplier-master/`);
        }
      }
    } catch (err) {
      console.log(err, 'err');
    }
  }, []);

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

  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 onFinish = async (values) => {
    let postData = values;
    postData['CreatedBy'] = getSession('UserId');
    postData['CompId'] = getSession('CompId');
    postData['AppId'] = AppId;
    postData['BranchId'] = brId;

    let response = {};
    if (formType === 'add') {
      response = await dispatch(postsupplier(postData)).unwrap();
    } else if (formType === 'edit') {
      if (editstate) {
        postData['SuppId'] = editstate?.SuppId;
        postData['AddId'] = editstate?.AddId;
        postData['UpdatedBy'] = getSession('UserId');
      }

      response = await dispatch(putsupplier(postData)).unwrap();
    }

    if (response?.data?.statusCode == 1) {
      navigate(`${subDirectory}setting/supplier-master/`, {
        state: {
          Notiffy: {
            messageType: 'success',
            messageData: response?.data?.response,
          },
        },
      });
    } else {
      setMessageType('error');
      setMessageData(response?.data?.response);
    }
  };

  const validatePhoneNumber = (_, value) => {
    if (!value) {
      return Promise.reject('Mobile number is required');
    }

    // Must be 10 digits and start with 6-9
    const phoneRegex = /^[6-9]\d{9}$/;

    if (!phoneRegex.test(value)) {
      return Promise.reject('Please enter a valid 10-digit mobile number starting with 6, 7, 8, or 9');
    }

    return Promise.resolve();
  };

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

  async function fetchData() {
    const gettingBranchDropDown = await dispatch(
      getBranchDataBasedonCmpAppId({ cmpId: cmpId, AppId: AppId })
    ).unwrap();
    if (gettingBranchDropDown?.data?.statusCode === 1) {
      if (gettingBranchDropDown?.data?.data?.length === 1) {
        formRef?.current?.setFieldsValue({
          BranchId:
            gettingBranchDropDown?.data?.data?.length === 1
              ? gettingBranchDropDown?.data?.data[0]?.BrId
              : null,
        });
        await BranchDropDownChange(gettingBranchDropDown?.data?.data[0]?.BrId);
      }
    }
  }

  const fetchDataBranchBased = async () => {
    const gettingBranchDropDown = await dispatch(
      getBranchDataBasedonCmpAppId({ cmpId: cmpId, AppId: AppId })
    ).unwrap();
    if (gettingBranchDropDown?.data?.statusCode === 1) {
      let finalBranchDropDown = gettingBranchDropDown?.data?.data?.filter(
        (value) => value.BrId === brId
      );

      if (finalBranchDropDown?.length === 1) {
        formRef.current?.setFieldsValue({
          BranchId:
            finalBranchDropDown?.length === 1
              ? finalBranchDropDown[0]?.BrId
              : null,
        });
        await BranchDropDownChange(finalBranchDropDown[0]?.BrId);
      }
    }
  };

  const onMarkerClick = async (location) => {
    setSelectedLatitude(
      typeof location.lat === 'function' ? location.lat() : SelectedLatitude
    );
    setSelectedLongitude(
      typeof location.lng === 'function' ? location.lng() : SelectedLongitude
    );
    formRef.current?.setFieldsValue({
      Latitude:
        typeof location.lat === 'function' ? location.lat() : SelectedLatitude,
      Longitude:
        typeof location.lng === 'function' ? location.lng() : SelectedLongitude,
    });
  };
  const pinCodeChange = async (e) => {
    if (e?.target?.value?.length < 6) {
      setZipCodeData(false);
      return false;
    }
    await getPincodeValues(e?.target?.value);
  };

  const getPincodeValues = async (pinCode) => {
    if (pinCode?.length == 6) {
      let response = '';
      await fetch(`https://api.postalpincode.in/pincode/${pinCode}`)
        .then((res) => res.text())
        .then((text) => (response = JSON.parse(text)));

      if (response[0]['Status'] === 'Success') {
        setZipCodeData(true);
        formRef.current?.setFieldsValue({
          City: response[0]['PostOffice'][0]['Block'],
          Dist: response[0]['PostOffice'][0]['District'],
          State: response[0]['PostOffice'][0]['State'],
        });
      } else {
        setZipCodeData(false);
      }
    }
  };

  const BranchDropDownChange = async (e) => {
    formRef.current?.setFieldsValue({ BranchId: e });
  };

  const handleDeliveryPerformanceChange = (value) => {
    formRef?.current?.setFieldsValue({ DeliveryPerformance: value });
    setDeliveryValue(value);
  };
  const handleDiscountLevelChange = (value) => {
    formRef?.current?.setFieldsValue({ DiscountLevel: value });
    setDicountValue(value);
  };
  const handleQualityofSuppChange = (value) => {
    formRef?.current?.setFieldsValue({ QualityofSupp: value });
    setQualityValue(value);
  };

  return (
    <div className="pageOverAll">
      <div className="userPage">
        <div className="userPageContent">
          <Messages messageType={messageType} messageData={messageData} />
          <div className="formName">
            <FormHeader
              title={AppType === 'Wholesale' ? 'Seller' : 'Supplier'}
            />
          </div>

          <div className="formDiv">
            <Form
              ref={formRef}
              className="formDivAnt"
              onFinish={onFinish}
              initialValues={{
                ...editstate,
              }}
            >
              <div className="formDivS">
                <div className="inputForm">
                  {/* <Form.Item
                    name="BranchId"
                    rules={[
                      {
                        required: true,
                        message: "Please Select Branch Name",
                      },
                    ]}
                  >
                    <DropDowns
                      options={BranchDropDown?.map((option) => ({
                        value: option.BrId,
                        label: option.BrName,
                      }))}
                      label={<label class="required">Branch Name</label>}
                      id="BranchId"
                      field="BranchId"
                      fieldState={true}
                      fieldApi={true}
                      className="field-DropDown-Emp"
                      onChangeFunction={(e) => BranchDropDownChange(e)}
                      isOnchanges={formType == "edit" ? true : false}
                      valueData={SelectedBranchData}
                      disabled={brId ? true : false}

                      // defaultValue={LastSelectConfig}
                    />
                  </Form.Item> */}

                  <Form.Item
                    name="SuppName"
                    rules={[
                      {
                        required: true,
                        pattern: /^(?!\s*$).+/,
                        message: `Please Enter ${AppType === 'Wholesale' ? 'Seller' : 'Supplier'} Name`,
                      },
                      {
                        validator: async (_, value) => {
                          await validateSafeInput(value);
                          if (value?.length > 30) {
                            return Promise.reject(
                              'Supplier Name cannot exceeds more than 30 chars'
                            );
                          }
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <InputField
                      label={
                        <label class="required">
                          {AppType === 'Wholesale'
                            ? 'Seller Name'
                            : 'Supplier Name'}
                        </label>
                      }
                      autocomplete="off"
                      isOnChange={formType == 'edit' ? true : false}
                      disabled={
                        formType === 'edit' &&
                        formRef?.current?.getFieldsValue()?.SuppName === 'Self'
                      }
                    />
                  </Form.Item>
                  <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={[
                      { 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={[
                      { 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>
                </div>
                <div className="formAddressDiv">
                  <p> Address Details</p>
                </div>
                <div className="subinputForm">
                  <div>
                    <Form.Item
                      name="Address1"
                      rules={[
                        {
                          // required: formType == "edit" ? false : true,
                          pattern: /^(?!\s*$).+/,
                          message: 'Please Enter Address1',
                        },
                        {
                          validator: async (_, value) => {
                            await validateSafeInput(value); // To block HTML tags & SQL keywords
                            return Promise.resolve();
                          },
                        },
                      ]}
                    >
                      <InputField
                        autoComplete="off"
                        label={<label>Address Line1</label>}
                        isOnChange={editstate?.Address1 ? true : false}
                      />
                    </Form.Item>
                    <Form.Item
                      name="Address2"
                      rules={[
                        {
                          pattern: /^(?!\s*$).+/,
                          message: 'Please Enter Address2',
                        },
                        {
                          validator: async (_, value) => {
                            await validateSafeInput(value); // To block HTML tags & SQL keywords
                            return Promise.resolve();
                          },
                        },
                      ]}
                    >
                      <InputField
                        autoComplete="off"
                        label="Address Line2"
                        isOnChange={editstate?.Address2 ? true : false}
                      />
                    </Form.Item>
                    <Form.Item
                      name="Zip"
                      rules={[
                        {
                          pattern: /^(?!\s*$).+/,
                          message: 'Please Enter Zipcode',
                        },
                        {
                          validator: async (_, value) => {
                            await validateSafeInput(value); // To block HTML tags & SQL keywords
                            return Promise.resolve();
                          },
                        },
                      ]}
                    >
                      <InputField
                        autoComplete="off"
                        label={<label>Zipcode</label>}
                        maxLength="6"
                        onKeyPress={(event) => {
                          // Allow only numbers and prevent any other input
                          if (!/[0-9]/.test(event.key)) {
                            event.preventDefault();
                          }
                        }}
                        isOnChange={
                          editstate?.Zip || editstate?.Zip == 0 ? true : false
                        }
                        onChange={pinCodeChange}
                      />
                    </Form.Item>
                    {zipCodeData ? (
                      <>
                        <Form.Item
                          name="City"
                          rules={[
                            {
                              required: true,
                            },
                            {
                              validator: async (_, value) => {
                                await validateSafeInput(value); // To block HTML tags & SQL keywords
                                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); // To block HTML tags & SQL keywords
                                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); // To block HTML tags & SQL keywords
                                return Promise.resolve();
                              },
                            },
                          ]}
                        >
                          <InputField
                            disabled={true}
                            isOnChange={true}
                            label="State"
                          />
                        </Form.Item>
                      </>
                    ) : (
                      ''
                    )}

                    <Form.Item
                      name="Latitude"
                      rules={[
                        {
                          pattern: /^(?!\s*$).+/,
                          message: 'Please Enter Latitude',
                        },
                        {
                          validator: async (_, value) => {
                            await validateSafeInput(value); // To block HTML tags & SQL keywords
                            return Promise.resolve();
                          },
                        },
                      ]}
                    >
                      <InputField
                        label="Latitude"
                        isOnChange={
                          SelectedLatitude ||
                          editstate?.Latitude ||
                          editstate?.Latitude == 0
                            ? true
                            : false
                        }
                        autoComplete="off"
                      />
                    </Form.Item>
                    <Form.Item
                      name="Longitude"
                      rules={[
                        {
                          pattern: /^(?!\s*$).+/,
                          message: 'Please Enter Longitude',
                        },
                        {
                          validator: async (_, value) => {
                            await validateSafeInput(value); // To block HTML tags & SQL keywords
                            return Promise.resolve();
                          },
                        },
                      ]}
                    >
                      <InputField
                        label="Longitude"
                        isOnChange={
                          SelectedLongitude ||
                          editstate?.Longitude ||
                          editstate?.Longitude == 0
                            ? true
                            : false
                        }
                        autoComplete="off"
                      />
                    </Form.Item>
                  </div>

                  <div className="MapDiv">
                    <MapView
                      onMarkerClick={onMarkerClick}
                      prevlca={
                        editstate
                          ? {
                              lat: editstate.Latitude,
                              lng: editstate.Longitude,
                            }
                          : null
                      }
                    />
                  </div>
                </div>
              </div>
              <div className="submitButton">
                <Buttons
                  buttonText="SUBMIT"
                  color="901D77"
                  icon={<ArrowRightOutlined />}
                  // handleSubmit={handleSubmit}
                />
              </div>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SupplierForm;
