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';
import { Button, Form, Input, InputNumber, Tooltip, Collapse } from 'antd';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { getSession, validateSafeInput } from '../../Services/Others';
import { useNavigate, useLocation } from 'react-router-dom';
import { DatePic } from '../../Components/Forms/DatePickerEmpMaster.jsx';
import {
  getBranchDataBasedonCmpAppId,
  UserDataBasedOnBranchId,
  postEmp,
  putEmp,
  EmpTypeDropDown,
  EmpDesgDropDown,
  EmpDepartMentDropDown,
  GettingShiftData,
  checkTrialCompany,
} from '../../Features/EmpMaster/EmpMaster.js';
import moment from 'moment';
import { DropDowns } from '../../Components/Forms/DropDown.jsx';
import MapView from '../../Components/MapView/MapView.jsx';
import { RadioGrpButton } from '../../Components/Forms/RadioGroup.jsx';
import Imageupload from '../../Components/Forms/Upload.jsx';
import { EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import { FaMapMarkedAlt } from 'react-icons/fa';
import '../../Styles/Employee/EmpMaster.scss';
import { getCommonAppPreference } from '../../Features/BrachLogin/BranchLogin.js';
import { AiOutlineDownCircle, AiOutlineUpCircle } from 'react-icons/ai';
// import TextArea from 'antd/es/input/TextArea.js';
import CropUpload from '../../Components/Forms/CropUpload.jsx';
const { Panel } = Collapse;
const { TextArea } = Input;
const subDirectory = import.meta.env.BASE_URL;

const EmployeeForm = ({ 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 [userDropDown, setuserDropDown] = useState([]);
  const [selectedUserData, setSelectedUserData] = 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 [AdminUserId, setAdminUserId] = useState(getSession('UserId'));
  const [ImageUrl, setImageUrl] = useState(null);
  const [EmpTypeDropDownData, setEmpTypeDropDownData] = useState([]);
  const [seletedEmpTypeDrop, setseletedEmpTypeDrop] = useState(null);
  const [EmpDesgDropDownData, setEmpDesgDropDownData] = useState([]);
  const [seletedEmpDesigDrop, setseletedEmpDesigDrop] = useState(null);
  const [EmpDeptDropDownData, setEmpDeptDropDownData] = useState([]);
  const [seletedEmpDeptDrop, setseletedEmpDeptDrop] = useState(null);
  const [ShiftDownData, setShiftDownData] = useState([]);
  const [seletedShiftDrop, setseletedShiftDrop] = useState(null);
  const [SelectedMobApp, setSelectedMobApp] = useState(
    editstate?.MobileAppAccess ? editstate?.MobileAppAccess : 'N'
  );
  const [SelectedUserCreation, setSelectedUserCreation] = useState('E');
  const [SelectedDate, setSelectedDate] = useState(null);
  const [showPassword, setShowPassword] = useState(false);
  const [ShowMode, setShowMode] = useState(false);
  const [AppPreference, setAppPreference] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [showMap, setShowMap] = useState(false);
  const [fieldChangeMap, setFieldChangeMap] = useState({});
  const [imageUrls, setImageUrls] = useState([]);
  console.log(fieldChangeMap, 'fieldChangeMap');

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

    {
      name: 'Employee',
      link: `${subDirectory}setting/employee-master`,
    },
    {
      name: editstate ? 'Edit' : 'New',
      link: null,
    },
  ];

  const departmentTypePreference = AppPreference?.[0]?.PreferenceDetails?.find(
    (preference) => preference?.PreferredCatName === 'Department'
  );

  const activeDeptTypes =
    departmentTypePreference?.PreferenceCatDetails?.filter(
      (payment) => payment.PreferredStatus === 'Y'
    );

  console.log(
    departmentTypePreference,
    activeDeptTypes,
    'departmentTypePreference'
  );

  const onFinish = async (values) => {
    const values1 = formRef.current.getFieldsValue();
    const updatedChangeMap = { ...fieldChangeMap };

    Object.keys(values1).forEach((key) => {
      if (
        values1[key] !== undefined &&
        values1[key] !== null &&
        values1[key] !== ''
      ) {
        updatedChangeMap[key] = true;
      }
    });

    setFieldChangeMap(updatedChangeMap);
    console.log(updatedChangeMap, 'updatedChangeMap');
    let postData = values;
    console.log(values, 'values');
    postData['CreatedBy'] = getSession('UserId');
    postData['CompId'] = getSession('CompId');
    postData['EmpDOJ'] = moment(SelectedDate).format('YYYY-MM-DD');
    postData['BranchId'] = brId;
    postData['MobileAppAccess'] = SelectedMobApp ? SelectedMobApp : 'N';
    postData['EmpPhotoLink'] = ImageUrl
      ? ImageUrl
      : 'https://api.pozo.app/pozo-common-image-api/upload?fileId=655c9e25fe20def9916edf1f.png';
    //  postData["Description"]=form?.getFieldValue("coachQualifications"),
    //  postData["Certification"]=form?.getFieldValue("coachQualifications"),
    //  postData["Experience"]=form?.getFieldValue("coachQualifications"),
    //  "Description":
    //   "Certification": "string",
    //   "Experience": form?.getFieldValue("coachExperience"),
    postData['ImageDetails'] =
      (imageUrls || [])
        .filter((item) => item && (item.image || item.name))
        .map((item, index) => ({
          ImageUrl: item.image || '',
          ImageType: item.name || '',
          // ImageType: "Coach",
          DisplayOrder: index + 1,
        })) || [];
    let response = {};
    if (formType === 'add') {
      // if (SelectedUserCreation === "N") {
      postData['AppId'] = AppId;
      // }

      response = await dispatch(postEmp(postData)).unwrap();
    } else if (formType === 'edit') {
      if (editstate) {
        postData['EmpCode'] = editstate?.EmpCode;
        postData['UniqueId'] = editstate?.UniqueId;
        postData['AddId'] = editstate?.AddId;
        postData['AppId'] = editstate?.AppId;
        postData['UpdatedBy'] = getSession('UserId');
        // postData["ShiftId"] = editstate?.ShiftId;
      }

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

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

  useEffect(() => {
    try {
      if (formType === 'edit') {
        if (editstate) {
          if (editstate?.Zip) {
            setZipCodeData(true);
          }
          UserDropDownChange(editstate?.UserId);
          EmpTypeDropDownChange(editstate?.EmpType);
          EmpDesigDropDownChange(editstate?.EmpDesig);
          EmpDeptDropDownChange(editstate?.EmpDept);
          ShiftDropDownChange(editstate?.EmpShiftId);
          setseletedEmpTypeDrop(editstate?.EmpType);
          setseletedEmpDesigDrop(editstate?.EmpDesig);
          setseletedEmpDeptDrop(editstate?.EmpDept);
          setseletedShiftDrop(editstate?.EmpShiftId);
          setSelectedDate(editstate?.EmpDOJ);
          setImageUrl(editstate?.EmpPhotoLink);
          setSelectedLatitude(editstate?.Latitude);
          setSelectedLongitude(editstate?.Longitude);
          formRef.current?.setFieldsValue({
            EmpDOJ: moment(editstate?.EmpDOJ),
          });

          formRef.current?.setFieldsValue(editstate);
        } else {
          navigate(`${subDirectory}setting/employee-master/`);
        }
      }
    } catch (err) {
      console.log(err, 'err');
    }
  }, []);
  useEffect(() => {
    if (isOpen && formRef.current) {
      const values = formRef.current.getFieldsValue();
      const updatedChangeMap = { ...fieldChangeMap };

      Object.keys(values).forEach((key) => {
        if (
          values[key] !== undefined &&
          values[key] !== null &&
          values[key] !== ''
        ) {
          updatedChangeMap[key] = true;
        }
      });

      setFieldChangeMap(updatedChangeMap);
    }
  }, [isOpen]);
  const updateImageUrls = (url, index = 0) => {
    setImageUrls((prev) => {
      const copy = Array.isArray(prev) ? [...prev] : [];
      copy[index] = {
        ...(copy[index] || {}),
        image: url,
      };
      return copy;
    });

    setImageUrl(url);
  };

  const updateImageName = (name, index = 0) => {
    setImageUrls((prev) => {
      const copy = Array.isArray(prev) ? [...prev] : [];
      copy[index] = {
        ...(copy[index] || {}),
        name: name,
      };
      return copy;
    });
  };
  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');
    }
  };

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

  useEffect(() => {
    if (SelectedUserCreation === 'N') {
      HandleEmpTypeDropDownData();
    }
  }, [SelectedUserCreation]);

  useEffect(() => {
    //
    if (!brId) {
      fetchData();
    } else {
      fetchDataBranchBased();
    }
  }, []);

  async function fetchData() {
    handleApplicationChange(AdminUserId, AppId);
    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
      // );
      let finalBranchDropDown = gettingBranchDropDown?.data?.data?.filter(
        (value) => value?.BrId === brId && value.ActiveStatus === 'A'
      );

      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) => {
    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 });
    let gettinguserDropDown = [];
    if (formType === 'add') {
      gettinguserDropDown = await dispatch(
        UserDataBasedOnBranchId({
          BranchId: e,
          Type: 'E',
        })
      ).unwrap();
    } else {
      gettinguserDropDown = await dispatch(
        UserDataBasedOnBranchId({
          BranchId: e,
          Type: 'EE',
        })
      ).unwrap();
    }

    if (gettinguserDropDown?.data?.statusCode === 1) {
      let finaluserDropDown = gettinguserDropDown?.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );
      if (gettinguserDropDown?.data?.data?.length === 1) {
        setSelectedUserData(
          gettinguserDropDown?.data?.data?.length === 1
            ? gettinguserDropDown?.data?.data[0]?.UserId
            : null
        );
        formRef.current?.setFieldsValue({
          UserId:
            gettinguserDropDown?.data?.data?.length === 1
              ? gettinguserDropDown?.data?.data[0]?.UserId
              : null,
        });
        if (formType === 'add') {
          await UserDropDownChangeMobile(
            gettinguserDropDown?.data?.data[0]?.UserId,
            finaluserDropDown
          );
        }
      }

      setuserDropDown(finaluserDropDown);
    }
  };

  const HandleEmpTypeDropDownData = async () => {
    const gettingEmpTypeDropDown = await dispatch(EmpTypeDropDown()).unwrap();
    if (gettingEmpTypeDropDown?.data?.statusCode === 1) {
      let finalEmpTypeDropDown = gettingEmpTypeDropDown?.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );

      if (gettingEmpTypeDropDown?.data?.data?.length === 1) {
        setseletedEmpTypeDrop(
          gettingEmpTypeDropDown?.data?.data?.length === 1
            ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId
            : null
        );
        formRef.current?.setFieldsValue({
          EmpType:
            gettingEmpTypeDropDown?.data?.data?.length === 1
              ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId
              : null,
        });
        await EmpTypeDropDownChange(
          gettingEmpTypeDropDown?.data?.data[0]?.ConfigId
        );
      }
      //
      setEmpTypeDropDownData(finalEmpTypeDropDown);
    }
  };

  const UserDropDownChange = async (e) => {
    // MobileNo
    let mob = userDropDown.filter((item) => item?.UserId === e);
    console.log(mob, 'mobmob');
    formRef.current?.setFieldsValue({
      UserId: e,
      EmpFirstName: mob?.[0]?.UserName,
      MobileNo: mob?.[0]?.MobileNo,
      Address1: mob?.[0]?.Address1,
      Address2: mob?.[0]?.Address2,
      City: mob?.[0]?.City,
      Dist: mob?.[0]?.Dist,
      Latitude: mob?.[0]?.Latitude,
      Longitude: mob?.[0]?.Longitude,
      MailId: mob?.[0]?.MailId,
      Password: mob?.[0]?.Password,
      Pin: mob?.[0]?.Pin,
      State: mob?.[0]?.State,
      UserImage: mob?.[0]?.UserImage,
      UserTypeName: mob?.[0]?.UserTypeName,
      Zip: mob?.[0]?.Zip,
    });
    console.log(mob?.[0]?.Zip, 'eeeeeeeeeeeeeeeeeeeee');
    await getPincodeValues(mob?.[0]?.Zip);
    setSelectedUserData(e);

    const gettingEmpTypeDropDown = await dispatch(EmpTypeDropDown()).unwrap();
    if (gettingEmpTypeDropDown?.data?.statusCode === 1) {
      let finalEmpTypeDropDown = gettingEmpTypeDropDown?.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );

      if (gettingEmpTypeDropDown?.data?.data?.length === 1) {
        setseletedEmpTypeDrop(
          gettingEmpTypeDropDown?.data?.data?.length === 1
            ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId
            : null
        );
        formRef.current?.setFieldsValue({
          EmpType:
            gettingEmpTypeDropDown?.data?.data?.length === 1
              ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId
              : null,
        });
        await EmpTypeDropDownChange(
          gettingEmpTypeDropDown?.data?.data[0]?.ConfigId
        );
      }
      //
      setEmpTypeDropDownData(finalEmpTypeDropDown);
    }
  };

  // useEffect(() => {

  //   const image = formRef.current?.getFieldsValue();
  //   console.log(formRef.current?.getFieldsValue(), 'kkkkkkkkkkk');

  //   if (image) {
  //     setShowImage(true);
  //   }
  // }, [formRef.current]);

  const UserDropDownChangeMobile = async (e, Mobile) => {
    // MobileNo
    let mob = Mobile.filter((item) => item?.UserId === e);
    console.log(mob, 'ddddddddd');
    const data = mob?.length > 0 ? mob[0] : {};

    formRef.current?.setFieldsValue({
      UserId: e,
      MobileNo: data.MobileNo,
      Address1: data.Address1,
      Address2: data.Address2,
      Latitude: data.Latitude,
      Longitude: data.Longitude,
      Zip: data.Zip,
      MailId: data.MailId,
      State: data.State,
      UserImage: data.UserImage,
    });
    await getPincodeValues(mob?.[0]?.Zip);
    setSelectedUserData(e);

    const gettingEmpTypeDropDown = await dispatch(EmpTypeDropDown()).unwrap();
    if (gettingEmpTypeDropDown?.data?.statusCode === 1) {
      let finalEmpTypeDropDown = gettingEmpTypeDropDown?.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );

      if (gettingEmpTypeDropDown?.data?.data?.length === 1) {
        setseletedEmpTypeDrop(
          gettingEmpTypeDropDown?.data?.data?.length === 1
            ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId
            : null
        );
        formRef.current?.setFieldsValue({
          EmpType:
            gettingEmpTypeDropDown?.data?.data?.length === 1
              ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId
              : null,
        });
        await EmpTypeDropDownChange(
          gettingEmpTypeDropDown?.data?.data[0]?.ConfigId
        );
      }
      //
      setEmpTypeDropDownData(finalEmpTypeDropDown);
    }
  };

  const EmpTypeDropDownChange = async (e) => {
    formRef.current?.setFieldsValue({ EmpType: e });
    setseletedEmpTypeDrop(e);
    const gettingEmpDesgDropDown = await dispatch(
      EmpDesgDropDown({ AppId: AppId })
    ).unwrap();
    if (gettingEmpDesgDropDown.data?.statusCode === 1) {
      let finalEmpDesgDropDown = gettingEmpDesgDropDown.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );
      if (gettingEmpDesgDropDown?.data?.data?.length === 1) {
        setseletedEmpDesigDrop(
          gettingEmpDesgDropDown?.data?.data?.length === 1
            ? gettingEmpDesgDropDown?.data?.data[0]?.ConfigId
            : null
        );
        formRef.current?.setFieldsValue({
          EmpDesig:
            gettingEmpDesgDropDown?.data?.data?.length === 1
              ? gettingEmpDesgDropDown?.data?.data[0]?.ConfigId
              : null,
        });
        await EmpDesigDropDownChange(
          gettingEmpDesgDropDown?.data?.data[0]?.ConfigId
        );
      }
      setEmpDesgDropDownData(finalEmpDesgDropDown);
    }
  };

  const EmpDesigDropDownChange = async (e) => {
    formRef.current?.setFieldsValue({ EmpDesig: e });
    setseletedEmpDesigDrop(e);
    const gettingEmpDeptDropDown = await dispatch(
      EmpDepartMentDropDown()
    ).unwrap();
    if (gettingEmpDeptDropDown.data?.statusCode === 1) {
      let finalEmpDeptDropDown = gettingEmpDeptDropDown.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );
      if (gettingEmpDeptDropDown?.data?.data?.length === 1) {
        setseletedEmpDeptDrop(
          gettingEmpDeptDropDown?.data?.data?.length === 1
            ? gettingEmpDeptDropDown?.data?.data[0]?.ConfigId
            : null
        );
        formRef.current?.setFieldsValue({
          EmpDept:
            gettingEmpDeptDropDown?.data?.data?.length === 1
              ? gettingEmpDeptDropDown?.data?.data[0]?.ConfigId
              : null,
        });
        await EmpDeptDropDownChange(
          gettingEmpDeptDropDown?.data?.data[0]?.ConfigId
        );
      }
      setEmpDeptDropDownData(finalEmpDeptDropDown);
    }
  };

  const EmpDeptDropDownChange = async (e) => {
    // EmpDept
    formRef.current?.setFieldsValue({ EmpDept: e });
    setseletedEmpDeptDrop(e);
    const gettingShiftDropDown = await dispatch(
      GettingShiftData(cmpId)
    ).unwrap();
    if (gettingShiftDropDown.data?.statusCode === 1) {
      let finalShiftDropDown = gettingShiftDropDown.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );
      if (gettingShiftDropDown?.data?.data?.length === 1) {
        setseletedShiftDrop(
          gettingShiftDropDown?.data?.data?.length === 1
            ? gettingShiftDropDown?.data?.data[0]?.ShiftId
            : null
        );
        formRef.current?.setFieldsValue({
          EmpShiftId:
            gettingShiftDropDown?.data?.data?.length === 1
              ? gettingShiftDropDown?.data?.data[0]?.ShiftId
              : null,
        });
        await ShiftDropDownChange(gettingShiftDropDown?.data?.data[0]?.ShiftId);
      }
      setShiftDownData(finalShiftDropDown);
    }
  };

  useEffect(() => {
    getApplicationPreference();
  }, []);

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

  const ShiftDropDownChange = async (e) => {
    formRef.current?.setFieldsValue({ EmpShiftId: e });
    setseletedShiftDrop(e);
  };

  //   seletedEmpTypeDrop

  const updateImageUrl = (url) => {
    setImageUrl(url);
  };

  const selectValue = async (e) => {
    setSelectedMobApp(e);
  };
  const selectUserValue = async (e) => {
    setSelectedUserCreation(e);
  };

  const onChange = async (date, dateString) => {
    if (dateString === '') {
      setSelectedDate();
    } else if (dateString) {
      const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );

      formRef.current?.setFieldsValue({ EmpDOJ: Date1 });
      await setSelectedDate(Date1);
    }
  };
  const handlePasswordToggle = () => {
    setShowPassword(!showPassword);
  };
  //mohan
  const handleApplicationChange = async (UserId, AppId) => {
    // var TrialData =[];
    // if (UserType === 'Admin') {
    var TrialData = await dispatch(
      checkTrialCompany({ UserId: UserId, AppId: AppId })
    ).unwrap();
    // }
    // else{
    //    TrialData =await dispatch(
    //     checkTrialCompany({ UserId: UserId, AppId: AppId })
    //   ).unwrap();
    // }

    if (TrialData.data?.statusCode == 1 && formType != 'edit') {
      const Trial = TrialData?.data?.data[0];
      const Count = TrialData.data?.data?.length;
      let fliterFeatConstraintdata = Trial?.FeatureDetails?.filter((a) =>
        a.FeatName === 'Users' ? a.FeatConstraint : 0
      );
      let fliterFeatConstraint =
        fliterFeatConstraintdata?.length > 0
          ? fliterFeatConstraintdata[0]?.FeatConstraint
          : 0;

      if (Trial) {
        if (Trial.PricingName.toUpperCase() == 'FREE' && Trial.UserCount >= 1) {
          setShowMode(false);
        } else if (Trial.PricingName.toUpperCase() != 'FREE') {
          if (fliterFeatConstraint <= Trial.UserCount) {
            setShowMode(false);
          } else {
            setShowMode(true);
          }
        }
      }
    } else {
      setShowMode(false);
    }
  };
  //mohan
  const handleToggle = () => {
    setIsOpen(!isOpen);
  };
  const handleMapShow = (e) => {
    setShowMap(e);
  };
  return (
    <div className="pageOverAll">
      <div className="userPage">
        <div className="userPageContent">
          <Messages messageType={messageType} messageData={messageData} />
          <div className="formName">
            <FormHeader title={'Employee'} />
            {formType != 'edit' && ShowMode != false ? (
              <li className="drp_btn_Mode">
                <RadioGrpButton
                  content={[
                    { value: 'E', label: 'Existing User' },
                    { value: 'N', label: 'New User' },
                  ]}
                  fieldState={true}
                  defaultSelect={SelectedUserCreation}
                  Header={'Mode Of Creation'}
                  onSelectFuntion={(e) => selectUserValue(e)}
                />
              </li>
            ) : null}
          </div>

          <div className="formDiv" style={{ scrollbarWidth: 'thin' }}>
            <Form
              ref={formRef}
              className="formDivAnt"
              onFinish={onFinish}
              initialValues={{ ...editstate }}
            >
              <div className="formDivS">
                <div className="inputForm">
                  {SelectedUserCreation === 'E' ? (
                    <Form.Item
                      name="UserId"
                      rules={[
                        {
                          required: true,
                          message: 'Please Select User Name',
                        },
                      ]}
                    >
                      <DropDowns
                        options={userDropDown?.map((option) => ({
                          value: option.UserId,
                          label:
                            option.UserName != ''
                              ? option.UserName
                              : option.MobileNo,
                        }))}
                        label={<label class="required">User Name</label>}
                        id="UserId"
                        field="UserId"
                        fieldState={true}
                        fieldApi={true}
                        className="field-DropDown-Emp"
                        onChangeFunction={(e) => UserDropDownChange(e)}
                        isOnchanges={formType == 'edit' ? true : false}
                        valueData={selectedUserData}
                        disabled={formType == 'edit' ? true : false}
                        // defaultValue={LastSelectConfig}
                      />
                    </Form.Item>
                  ) : null}
                  {/* {isOpen && <> */}
                  <Form.Item
                    name="EmpFirstName"
                    //  hidden={!isOpen}
                    rules={[
                      {
                        required: true,
                        pattern: /^(?!\s*$).+/,
                        message: 'Please Enter First Name',
                      },
                      {
                        pattern: /^[A-Za-z]+$/,
                        message:
                          'First Name should contain only letters (no numbers or special characters)',
                      },
                      {
                        validator: async (_, value) => {
                          await validateSafeInput(value);

                          if (value && value.length > 20) {
                            return Promise.reject(
                              'First Name should not exceed 20 characters'
                            );
                          }

                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <InputField
                      field="First Name"
                      name="First Name"
                      label={<label class="required">First Name</label>}
                      fieldState={true}
                      fieldApi={true}
                      id="error2"
                      autocomplete="off"
                      isOnChange={
                        formType == 'edit' || fieldChangeMap['EmpFirstName']
                          ? true
                          : false
                      }
                    />
                  </Form.Item>

                  <Form.Item
                    name="EmpLastName"
                    hidden={!isOpen}
                    rules={[
                      {
                        // required: true,
                        pattern: /^(?!\s*$).+/,
                        // message: "Please Enter Last Name",
                      },
                      {
                        validator: async (_, value) => {
                          await validateSafeInput(value);

                          if (value && value.length > 20) {
                            return Promise.reject(
                              'Last Name should not exceed 20 characters'
                            );
                          }

                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <InputField
                      field="Last Name"
                      name="Last Name"
                      label={
                        <label style={{ fontSize: '12px', color: '#5A5A5A' }}>
                          Last Name
                        </label>
                      }
                      fieldState={true}
                      fieldApi={true}
                      id="error2"
                      autocomplete="off"
                      isOnChange={formType == 'edit' ? true : false}
                    />
                  </Form.Item>
                  {/* </>
               } */}
                  {SelectedUserCreation === 'E' && (
                    <Form.Item
                      name="MobileNo"
                      rules={[
                        {
                          required: true,
                          pattern: /^\d{10}$/,
                          message: 'Please Enter a Valid Mobile Number',
                        },

                        { validator: validatePhoneNumber },
                      ]}
                    >
                      <InputField
                        field="MobileNo"
                        label={<label class="required">Mobile Number</label>}
                        fieldState={true}
                        maxLength="10"
                        fieldApi={true}
                        autocomplete="off"
                        disabled={true}
                        isOnChange={
                          formRef.current?.getFieldsValue()?.MobileNo !=
                          undefined
                            ? true
                            : false
                        }
                      />
                    </Form.Item>
                  )}
                  {SelectedUserCreation === 'N' && (
                    <Form.Item
                      name="MobileNo"
                      rules={[
                        {
                          required: true,
                          pattern: /^\d{10}$/,
                          message: 'Please Enter a Valid Mobile Number',
                        },

                        { validator: validatePhoneNumber },
                      ]}
                    >
                      <InputField
                        field="MobileNo"
                        label={<label class="required">Mobile Number</label>}
                        fieldState={true}
                        maxLength="10"
                        fieldApi={true}
                        autocomplete="off"
                        isOnChange={formType == 'edit' ? true : false}
                      />
                    </Form.Item>
                  )}
                  {SelectedUserCreation === 'N' ? (
                    <Form.Item
                      name="MailId"
                      rules={[{ validator: validateEmail }]}
                    >
                      <InputField
                        field="MailId"
                        label={<label class="required">MailId</label>}
                        fieldState={true}
                        fieldApi={true}
                        autocomplete="off"
                        isOnChange={formType == 'edit' ? true : false}
                      />
                    </Form.Item>
                  ) : null}
                  {SelectedUserCreation === 'N' ? (
                    <Form.Item
                      name="Password"
                      // rules={[{ required: true }]}
                      // hasFeedback
                    >
                      <Input.Password
                        field="Password"
                        fieldState={true}
                        fieldApi={true}
                        autocomplete="off"
                        iconRender={(visible) =>
                          visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
                        }
                        onIconClick={handlePasswordToggle}
                        visibilityToggle={true}
                        addonBefore="Password"
                        isOnChange={formType == 'edit' ? true : false}
                        style={{ width: '250px' }}
                        // disabled={formType == "edit" ? true : false}
                      />
                    </Form.Item>
                  ) : null}
                  {SelectedUserCreation === 'N' ? (
                    <Form.Item
                      name="Pin"
                      rules={[
                        {
                          pattern: /^[0-9]{4}$/,
                          message: 'Pin number must be a 4-digit',
                          required: true,
                        },
                        {
                          validator: async (_, value) => {
                            await validateSafeInput(value); // To block HTML tags & SQL keywords
                            return Promise.resolve();
                          },
                        },
                      ]}
                    >
                      <InputField
                        field="Pin"
                        label={<label class="required">Pin</label>}
                        fieldState={true}
                        fieldApi={true}
                        maxLength="4"
                        autocomplete="off"
                        isOnChange={formType == 'edit' ? true : false}
                      />
                    </Form.Item>
                  ) : null}
                  {/* EmpType */}
                  <Form.Item
                    name="EmpType"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Employee Type',
                      },
                    ]}
                  >
                    <DropDowns
                      options={EmpTypeDropDownData?.map((option) => ({
                        value: option.ConfigId,
                        label: option.ConfigName,
                      }))}
                      label={<label class="required">Employee Type</label>}
                      id="EmpType"
                      field="EmpType"
                      fieldState={true}
                      fieldApi={true}
                      className="field-DropDown-Emp"
                      onChangeFunction={(e) => EmpTypeDropDownChange(e)}
                      isOnchanges={formType == 'edit' ? true : false}
                      valueData={seletedEmpTypeDrop}
                      // defaultValue={LastSelectConfig}
                    />
                  </Form.Item>
                  {/* EmpDesig */}
                  <Form.Item
                    name="EmpDesig"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Designation',
                      },
                    ]}
                  >
                    <DropDowns
                      options={EmpDesgDropDownData?.map((option) => ({
                        value: option.ConfigId,
                        label: option.ConfigName,
                      }))}
                      label={<label class="required">Designation</label>}
                      id="EmpDesig"
                      field="EmpDesig"
                      fieldState={true}
                      fieldApi={true}
                      className="field-DropDown-Emp"
                      onChangeFunction={(e) => EmpDesigDropDownChange(e)}
                      isOnchanges={formType == 'edit' ? true : false}
                      valueData={seletedEmpDesigDrop}
                      // defaultValue={LastSelectConfig}
                    />
                  </Form.Item>
                  {/* EmpDept */}
                  <Form.Item
                    name="EmpDept"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Department',
                      },
                    ]}
                  >
                    <DropDowns
                      options={activeDeptTypes?.map((option) => ({
                        value: option.PreferredSubCatId,
                        label: option.PreferredSubCatName,
                      }))}
                      label={<label class="required">Department</label>}
                      id="EmpDept"
                      field="EmpDept"
                      fieldState={true}
                      fieldApi={true}
                      className="field-DropDown-Emp"
                      onChangeFunction={(e) => EmpDeptDropDownChange(e)}
                      isOnchanges={formType == 'edit' ? true : false}
                      valueData={seletedEmpDeptDrop}
                      // defaultValue={LastSelectConfig}
                    />
                  </Form.Item>

                  {/* EmpShiftId */}

                  <Form.Item
                    name="EmpShiftId"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Shift Name',
                      },
                    ]}
                  >
                    <DropDowns
                      options={ShiftDownData?.map((option) => ({
                        value: option.ShiftId,
                        label: option.ShiftName,
                      }))}
                      label={<label class="required">Shift Name</label>}
                      id="ShiftId"
                      field="ShiftId"
                      fieldState={true}
                      fieldApi={true}
                      className="field-DropDown-Emp"
                      onChangeFunction={(e) => ShiftDropDownChange(e)}
                      isOnchanges={formType == 'edit' ? true : false}
                      valueData={seletedShiftDrop}
                      // defaultValue={LastSelectConfig}
                    />
                  </Form.Item>

                  {/* EmpDOJ */}

                  <Form.Item
                    name="EmpDOJ"
                    className="EmpDOJMain"
                    // hasFeedback
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Date of Join',
                      },
                    ]}
                  >
                    {/* <DatePic
                      field="EmpDOJ"
                      name="EmpDOJ"
                      label="Date of Join"
                      // fieldState={true}
                      fieldApi={true}
                      isOnChange={formRef.current?.getFieldsValue()?.EmpDOJ!=undefined ? true : false}
                      canSelectPast={true}
                      className={"Emp"}
                      id="error3"
                      defaultValue={SelectedDate}
                      fieldState={moment(SelectedDate)}
                      onChange={onChange}

                    
                    /> */}
                    {/* <label>Employee DOJ</label><br/><br/> */}
                    <DatePic
                      canSelectPast={true}
                      onChange={onChange}
                      valueData={SelectedDate}
                      // label={<label class="required">Date of Join</label>}
                      isOnChange={true}
                    />
                  </Form.Item>
                  {/* MobileAppAccess */}
                  <p
                    style={{
                      fontSize: '13px',
                      cursor: 'pointer',
                      padding: '1rem 0.3rem',
                      display: 'flex',
                      // alignItems: "center",
                      flexDirection: 'row',
                      columnGap: '0.3rem',
                      color: 'rgb(18, 146, 238)',
                    }}
                  >
                    {' '}
                    {isOpen ? (
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'flex-start',
                          gap: '4px',
                        }}
                        onClick={handleToggle}
                      >
                        More info close{' '}
                        <AiOutlineUpCircle style={{ marginTop: '4px' }} />
                      </div>
                    ) : (
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'flex-start',
                          gap: '4px',
                        }}
                        onClick={handleToggle}
                      >
                        More info open{' '}
                        <AiOutlineDownCircle style={{ marginTop: '4px' }} />
                      </div>
                    )}{' '}
                  </p>
                  {isOpen && (
                    <>
                      <Form.Item
                        name="MobileAppAccess"
                        className="MobileAppAccessmain"
                      >
                        <li className="drp_btn_Emp">
                          <RadioGrpButton
                            content={[
                              { value: 'Y', label: 'Yes' },
                              { value: 'N', label: 'No' },
                            ]}
                            fieldState={true}
                            defaultSelect={SelectedMobApp}
                            Header={'Mobile App Access'}
                            onSelectFuntion={(e) => selectValue(e)}
                          />
                        </li>
                      </Form.Item>

                      {/* EmpPhotoLink */}

                      <div className="upload_btn emp-master-form__upload">
                        <p>Upload Profile</p>
                        <Form.Item
                          name="UserImage"
                          getValueFromEvent={(e) =>
                            formType === 'edit' ? editstate?.EmpPhotoLink : e
                          }
                        >
                          <Imageupload
                            singleImage={true}
                            updateImageUrl={updateImageUrl}
                            ImageLink={(() => {
                              const link =
                                formType === 'edit'
                                  ? editstate?.EmpPhotoLink
                                  : formRef.current?.getFieldsValue()
                                      ?.UserImage || ImageUrl;
                              // Always return a string
                              return typeof link === 'string' ? link : '';
                            })()}
                          />
                        </Form.Item>
                      </div>
                    </>
                  )}
                </div>
                {isOpen && (
                  <>
                    <div className="formAddressDiv emp-master-form__address-header">
                      <p> Address Details</p>
                    </div>
                  </>
                )}
                <div className="subinputForm">
                  <div className={showMap ? 'withmapaddress' : 'Withoutmap'}>
                    {SelectedUserCreation === 'E' && (
                      <Form.Item
                        name="Address1"
                        hidden={!isOpen}
                        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
                          field="Address1"
                          autoComplete="off"
                          label={<label class="required">Address Line1</label>}
                          fieldState={true}
                          fieldApi={true}
                          // isOnChange={editstate?.Address1 ? true : false}
                          isOnChange={
                            formRef.current?.getFieldsValue()?.Address1 !=
                            undefined
                              ? true
                              : false
                          }
                        />
                      </Form.Item>
                    )}
                    {SelectedUserCreation === 'E' && (
                      <Form.Item
                        name="Address2"
                        hidden={!isOpen}
                        rules={[
                          {
                            pattern: /^(?!\s*$).+/,
                            message: 'Please Enter Address2',
                          },
                          {
                            validator: async (_, value) => {
                              await validateSafeInput(value); // To block HTML tags & SQL keywords
                              return Promise.resolve();
                            },
                          },
                        ]}
                      >
                        <InputField
                          field="Address2"
                          autoComplete="off"
                          label={
                            <label
                              style={{ fontSize: '12px', color: '#5A5A5A' }}
                            >
                              Address Line 2
                            </label>
                          }
                          fieldState={true}
                          fieldApi={true}
                          // isOnChange={editstate?.Address2 ? true : false}
                          isOnChange={
                            formRef.current?.getFieldsValue()?.Address2 !=
                            undefined
                              ? true
                              : false
                          }
                        />
                      </Form.Item>
                    )}
                    {
                      <Form.Item
                        name="Zip"
                        hidden={!isOpen}
                        rules={[
                          {
                            required: formType !== 'edit',
                            message: 'ZIP code is required',
                          },
                          {
                            pattern: /^[0-9]+$/,
                            message: 'Please enter only numbers',
                          },
                          {
                            validator: (_, value) =>
                              (value || editstate?.Zip) &&
                              value?.toString().length === 6
                                ? Promise.resolve()
                                : editstate?.Zip?.toString().length === 6
                                  ? Promise.resolve()
                                  : Promise.reject(
                                      'Please enter a 6-digit ZIP code'
                                    ),
                          },
                        ]}
                      >
                        <InputField
                          field="Zip"
                          autoComplete="off"
                          label={<label className="required">Zipcode</label>}
                          maxLength={6}
                          fieldState={true}
                          fieldApi={true}
                          // isOnChange={editstate?.Zip ? true : false}
                          isOnChange={
                            formRef.current?.getFieldsValue()?.Zip != undefined
                              ? true
                              : false
                          }
                          inputMode="numeric"
                          onChange={pinCodeChange}
                        />
                      </Form.Item>
                    }
                    {zipCodeData ? (
                      <>
                        <Form.Item
                          name="City"
                          hidden={!isOpen}
                          rules={[
                            {
                              required: true,
                            },
                            {
                              validator: async (_, value) => {
                                await validateSafeInput(value); // To block HTML tags & SQL keywords
                                return Promise.resolve();
                              },
                            },
                          ]}
                        >
                          <InputField
                            field="City"
                            disabled={true}
                            isOnChange={true}
                            label={
                              <label
                                style={{ fontSize: '12px', color: '#5A5A5A' }}
                              >
                                City
                              </label>
                            }
                            fieldState={true}
                            fieldApi={true}
                          />
                        </Form.Item>
                        <Form.Item
                          name="Dist"
                          hidden={!isOpen}
                          rules={[
                            {
                              required: true,
                            },
                            {
                              validator: async (_, value) => {
                                await validateSafeInput(value); // To block HTML tags & SQL keywords
                                return Promise.resolve();
                              },
                            },
                          ]}
                        >
                          <InputField
                            field="Dist"
                            disabled={true}
                            isOnChange={true}
                            // label="District"
                            label={
                              <label
                                style={{ fontSize: '12px', color: '#5A5A5A' }}
                              >
                                District
                              </label>
                            }
                            fieldState={true}
                            fieldApi={true}
                          />
                        </Form.Item>
                        <Form.Item
                          name="State"
                          hidden={!isOpen}
                          rules={[
                            {
                              required: true,
                            },
                            {
                              validator: async (_, value) => {
                                await validateSafeInput(value); // To block HTML tags & SQL keywords
                                return Promise.resolve();
                              },
                            },
                          ]}
                        >
                          <InputField
                            field="State"
                            disabled={true}
                            isOnChange={true}
                            // label="State"
                            label={
                              <label
                                style={{ fontSize: '12px', color: '#5A5A5A' }}
                              >
                                State
                              </label>
                            }
                            fieldState={true}
                            fieldApi={true}
                          />
                        </Form.Item>
                      </>
                    ) : (
                      ''
                    )}
                    {isOpen && (
                      <>
                        <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
                            field="Latitude"
                            // label="Latitude"
                            label={
                              <label
                                style={{ fontSize: '12px', color: '#5A5A5A' }}
                              >
                                Latitude
                              </label>
                            }
                            // isOnChange={
                            //   SelectedLatitude || (editstate?.Latitude || editstate?.Latitude == 0) ? true : false
                            // }
                            isOnChange={
                              SelectedLatitude ||
                              (formRef.current?.getFieldsValue()?.Latitude !=
                              undefined
                                ? true
                                : false)
                            }
                            fieldState={true}
                            fieldApi={true}
                            autoComplete="off"
                            suffix={
                              <Tooltip title="View Map">
                                <FaMapMarkedAlt
                                  style={{
                                    color: '#1677ff',
                                    fontSize: '18px',
                                    cursor: 'pointer',
                                  }}
                                  onClick={() => handleMapShow(!showMap)} // 👈 Show map on click
                                />
                              </Tooltip>
                            }
                          />
                        </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
                            field="Longitude"
                            label={
                              <label
                                style={{ fontSize: '12px', color: '#5A5A5A' }}
                              >
                                Longitude
                              </label>
                            }
                            // isOnChange={
                            //   SelectedLongitude || (editstate?.Longitude || editstate?.Longitude == 0)
                            //     ? true
                            //     : false
                            // }
                            isOnChange={
                              SelectedLatitude ||
                              (formRef.current?.getFieldsValue()?.Longitude !=
                              undefined
                                ? true
                                : false)
                            }
                            fieldState={true}
                            fieldApi={true}
                            autoComplete="off"
                          />
                        </Form.Item>

                        <Form.Item label="Experience (Years)" name="Experience">
                          <InputNumber
                            min={0}
                            max={50}
                            style={{ width: '100%' }}
                            placeholder="Enter years of experience"
                            onChange={(value) =>
                              formRef.current?.setFieldsValue({
                                Experience: value,
                              })
                            }
                            isOnChange={
                              formType == 'edit' || fieldChangeMap['Experience']
                                ? true
                                : false
                            }
                          />
                        </Form.Item>
                        <Form.Item label="Description" name="Description">
                          <TextArea
                            rows={2}
                            placeholder="Enter the Description"
                            onChange={(e) =>
                              formRef.current?.setFieldsValue({
                                Description: e.target.value,
                              })
                            }
                            isOnChange={
                              formType == 'edit' ||
                              fieldChangeMap['Description']
                                ? true
                                : false
                            }
                          />
                        </Form.Item>
                        <Form.Item label="Certification" name="Certification">
                          <TextArea
                            rows={2}
                            placeholder="Enter the Certification"
                            onChange={(e) =>
                              formRef.current?.setFieldsValue({
                                Certification: e.target.value,
                              })
                            }
                            isOnChange={
                              formType == 'edit' ||
                              fieldChangeMap['Certification']
                                ? true
                                : false
                            }
                          />
                        </Form.Item>

                        <div className="sports-masterimage">
                          {Array.from({
                            length: Math.max(1, imageUrls.length),
                          }).map((_, idx) => (
                            <div key={idx} style={{ marginBottom: 12 }}>
                              <CropUpload
                                onlineImage={''}
                                ImageLink={imageUrls[idx]?.image}
                                updateImageUrl={(url) =>
                                  updateImageUrls(url, idx)
                                }
                              />

                              <Input
                                placeholder={`Image name (optional)`}
                                value={imageUrls[idx]?.name || ''}
                                onChange={(e) =>
                                  updateImageName(e.target.value, idx)
                                }
                                style={{ marginTop: 8 }}
                              />

                              <div
                                style={{
                                  display: 'flex',
                                  gap: 8,
                                  marginTop: 8,
                                }}
                              >
                                <Button
                                  size="small"
                                  onClick={() =>
                                    setImageUrls((prev) => {
                                      const copy = Array.isArray(prev)
                                        ? [...prev]
                                        : [];
                                      copy.splice(idx + 1, 0, {
                                        image: '',
                                        name: '',
                                      });
                                      return copy;
                                    })
                                  }
                                >
                                  Add
                                </Button>
                                <Button
                                  size="small"
                                  danger
                                  onClick={() =>
                                    setImageUrls((prev) =>
                                      (prev || []).filter((__, i) => i !== idx)
                                    )
                                  }
                                >
                                  Remove
                                </Button>
                              </div>
                            </div>
                          ))}
                        </div>
                      </>
                    )}
                  </div>
                  {showMap && (
                    <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 EmployeeForm;
