import { ExpandMore } from "@mui/icons-material";
import { VisibilityOffOutlined, VisibilityOutlined } from "@mui/icons-material";
import VerifiedIcon from "@mui/icons-material/Verified";
import {
  AppBar,
  Box,
  Button,
  ButtonBase,
  Drawer,
  FormControl,
  FormHelperText,
  Grid,
  IconButton,
  InputAdornment,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  TextField,
  Toolbar,
  Tooltip,
  Typography,
} from "@mui/material";
import { useTheme } from "@mui/material/styles";
import axios from "axios";
import { useFormik } from "formik";
import { debounce } from "lodash";
import React, { useEffect, useRef, useState, useCallback } from "react";
import Dropzone from "react-dropzone";
import ReactCrop from "react-image-crop";
import "react-image-crop/dist/ReactCrop.css";
import "react-phone-input-2/lib/style.css";
import { useDispatch, useSelector } from "react-redux";
import { Link, useNavigate } from "react-router-dom";
import * as Yup from "yup";
import logo from "../../../src/assets/images/logo/BSmart_Logo_1b 2.svg";
import uploadIcon from "../../assets/images/icon/upload.svg";
import { IMAGE_LOCATION_BASE_URL } from "../../common/envVariables";
import CustomizedCheckbox from "../../components/Checkbox";
import CustomFileUpload from "../../components/CustomFileUpload";
import CustomStepper from "../../components/CustomStepper";
import FormFooterMessage from "../../components/FormFooterMessage";
import FormPageHeader from "../../components/FormPageHeader";
import FormSectionHeading from "../../components/FormSectionHeading";
import Loader from "../../components/Loader";
import TermsAndCondition from "../../components/TermsAndCondition";
import {
  ABN_NUMBER_LENGTH,
  GST_NUMBER_LENGTH,
  IMAGE_TYPE,
  MAX_FILES,
  MAX_FILE_SIZE_IN_MB,
  MEDIICARE_NUMBER_LENGTH,
  NOTIFICATION,
  ONLY_ALPHA_NUMERIC_ACCEPT_REGEX,
  WEBSITE_REGEX,
} from "../../constants";
import {
  fileUpload,
  getPresignedUrl,
  uploadToS3,
} from "../../services/file.upload.services";
import { pushNotification } from "../../utils/notification";
import {
  passwordLengthRegex,
  passwordLetterRegex,
  passwordNumberRegex,
  passwordSpacesRegex,
} from "../../utils/regex";
import { capitalizeAllLetters, capitalizeFirstLetter } from "../../utils/share";
import PasswordValidation from "../Login/component/PasswordValidation";
import { resetFormData, updateFormDetails } from "./signupAction";
import { useStyles } from "./styles/signupStyles";
import { getLatestClinicId } from "../../services/clinics.service";
import { getEmailOtp, signup, verifyOtp } from "../../services/auth.services";
import { decodeJWT } from "../../services/jwt.services";

function YourDetailsForm() {
  const classes = useStyles();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const theme = useTheme();
  const [latestClinicID, setLatestClinicID] = useState(0);
  const [otpField, setOtpField] = useState(false);
  const [otp, setOtp] = useState("");
  const [otpVerified, setOtpVerified] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [localityOption, setLocalityOption] = useState([]);
  const [countryOption, setCountryOption] = useState(["Australia", "India"]);
  const [pincodeData, setPincodeData] = useState();
  const selectedLocalityRef = useRef();
  const [testConnection, setTestConnDone] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    getLatestClinicId().then((res) => {
      setLatestClinicID(res?.data?.data);
    });
    setIsLoading(false);
  }, []);

  // Form data from Redux
  const yourDetailsFormData = useSelector((state) => state.signup);

  // Logo state variables
  const logoRef = useRef(null);
  const testConnectionRef = useRef(null);
  const otpButtonRef = useRef(null);
  const fileInputRef = useRef(null);
  const [aspect, setAspect] = useState(1);
  const [logoname, setLogoname] = useState();
  const [logoImage, setLogoImage] = useState();
  const [crop, setCrop] = useState({
    unit: "%",
    width: 100,
    height: 100,
    aspect: 1 / 1,
  });

  const userRoles = [
    { id: "practice_manager", name: "Practice Manager" },
    { id: "director", name: "Director" },
  ];

  const mobilePrefixOptions = [
    { id: "61", name: "+61" },
    { id: "91", name: "+91" },
  ];

  const integrationOptions = [
    { id: "bp", name: "BP Software" },
    { id: "medical_director", name: "Medical Director" },
  ];

  // Default form data
  const defaultFormData = useRef({
    // Personal details
    name: "",
    email: "",
    password: "",
    mobileNumber: "",
    mobilePrefix: "",
    confirmPassword: "",
    otp: "",

    // Clinic details
    companyName: "",
    designation: "",
    businessPhonePrefix: mobilePrefixOptions[0].name,
    businessPhone: "",
    emergencyBusinessPhone: "",
    emergencyBusinessPhonePrefix: mobilePrefixOptions[0].name,
    businessFax: "",
    clinicLogo: "",
    businessEmail: "",
    pincode: "",
    state: "",
    locality: "",
    country: "",
    fullAddress: "",
    companyABNImageNumber: "",
    companyABNImage: "",
    termsAccepted: "",
    practiceManagementSystem: "",
    practiceId: "",
    practiceName: "",

    // contract management
    contract: "",
  });

  // Field references for focus and validation
  const fieldRefs = {
    // Personal details fields
    name: useRef(null),
    email: useRef(null),
    mobileNumber: useRef(null),
    mobilePrefix: useRef(null),
    password: useRef(null),
    confirmPassword: useRef(null),
    otp: useRef(null),

    // Clinic details fields
    companyName: useRef(null),
    businessPhone: useRef(null),
    businessPhonePrefix: useRef(null),
    emergencyBusinessPhone: useRef(null),
    emergencyBusinessPhonePrefix: useRef(null),
    businessFax: useRef(null),
    businessEmail: useRef(null),
    practiceManagementSystem: useRef(null),
    practiceId: useRef(null),
    practiceName: useRef(null),
    designation: useRef(null),
    pincode: useRef(null),
    state: useRef(null),
    locality: useRef(null),
    country: useRef(null),
    fullAddress: useRef(null),
    companyABNImageNumber: useRef(null),
    companyABNImage: useRef(null),

    // contract management
    contract: useRef(null),
  };

  if (yourDetailsFormData) {
    Object.keys(defaultFormData.current).forEach((field) => {
      if (yourDetailsFormData[field]) {
        defaultFormData.current[field] = yourDetailsFormData[field];
      }
    });
  }

  const validationSchema = Yup.object().shape({
    // Personal details validation
    name: Yup.string().required("Name is required"),
    email: Yup.string()
      .email("Please enter valid Email Address")
      .required("Email Address is required")
      .typeError("Email Address must be string"),
    mobileNumber: Yup.string()
      .required("Mobile Number is required")
      .matches(/^[0-9]+$/, "Mobile Number must be a valid number")
      .min(10, "Mobile number should have 10 digits only.")
      .max(10, "Mobile number should have 10 digits only."),
    mobilePrefix: Yup.string().required("Mobile Prefix is required"),
    password: Yup.string()
      .matches(passwordLengthRegex, "Password must be at least 8 characters")
      .matches(passwordLetterRegex, "Password must contain at least one letter")
      .matches(passwordNumberRegex, "Password must contain at least one number")
      .matches(
        passwordSpacesRegex,
        "Password must not start or end with a space"
      )
      .required("Password is required"),
    confirmPassword: Yup.string()
      .oneOf([Yup.ref("password"), null], "Passwords must match")
      .required("The password must match"),

    // Clinic details validation
    companyName: Yup.string().required("Clinic Name is required"),
    businessPhone: Yup.string()
      .required("Business Phone is required")
      .matches(/^[0-9]+$/, "Business Phone must be a valid number")
      .min(10, "Business Phone number should have 10 digits only.")
      .max(10, "Business Phone number should have 10 digits only."),
    businessPhonePrefix: Yup.string().required(
      "Business Phone Prefix is required"
    ),
    emergencyBusinessPhone: Yup.string()
      .required("Emergency Business Phone is required")
      .matches(/^[0-9]+$/, "Emergency Business Phone must be a valid number")
      .min(10, "Emergency Business Phone number should have 10 digits only.")
      .max(10, "Emergency Business Phone number should have 10 digits only."),
    emergencyBusinessPhonePrefix: Yup.string().required(
      "Emergency Business Phone Prefix is required"
    ),
    businessEmail: Yup.string()
      .required("Business Email is required")
      .email("Please enter valid Email Address"),
    practiceManagementSystem: Yup.string()
      .required("Practice Management System is required")
      .typeError("Practice Management System must be string"),
    designation: Yup.string()
      .required("Designation is required")
      .typeError("Designation must be string"),
    pincode: Yup.string().required("Pincode is required"),
    state: Yup.string().required(),
    locality: Yup.string().required("City is required"),
    country: Yup.string().required("Country is required"),
    fullAddress: Yup.string()
      .required("Full Address is required")
      .typeError("Address must be string"),
    companyABNImageNumber: Yup.string()
      .required("ABN number is required")
      .matches(
        ONLY_ALPHA_NUMERIC_ACCEPT_REGEX,
        "ABN Number must only contain numbers and letters"
      )
      .length(ABN_NUMBER_LENGTH, "Enter valid ABN Number"),
    companyABNImage: Yup.string().required("Clinic ABN document is required"),
    contract: Yup.string().required("Contract is required"),
    termsAccepted: Yup.boolean()
      .oneOf([true], "You must accept the terms and conditions")
      .required("You must accept the terms and conditions"),
    practiceId: Yup.string().required("Practice ID is required"),
    practiceName: Yup.string().required("Practice Name is required"),
  });

  // Debounced function for pincode lookup
  const debouncedFetchPincodeData = useCallback(
    debounce(
      async (pincode, formik, setLocalityOption, selectedLocalityRef) => {
        if (!pincode) return; // Don't make API call if pincode is empty
        try {
          const countryShort =
            formik.values.country === "Australia" ? "au" : "in";
          const resp = await axios.get(
            `https://api.zippopotam.us/${countryShort}/${pincode}`
          );
          formik.setFieldValue("state", resp?.data?.places[0]?.state);
          setLocalityOption(
            resp?.data?.places?.map((object) => object["place name"])
          );
          formik.setFieldValue("locality", selectedLocalityRef.current);
        } catch (error) {
          // Handle error
          setLocalityOption([]);
          formik.setFieldValue("state", "");
          formik.setFieldValue("locality", "");
          pushNotification("Invalid pincode", NOTIFICATION.ERROR);
        }
      },
      1000
    ),
    []
  );

  const handleTogglePasswordVisibility = (field) => {
    if (field === "password") {
      setShowPassword((prevShowPassword) => !prevShowPassword);
    } else if (field === "confirmPassword") {
      setShowConfirmPassword(
        (prevShowConfirmPassword) => !prevShowConfirmPassword
      );
    }
  };

  const handleTestConnection = () => {
    // logic here
    setTestConnDone(true);
    pushNotification("Test connection successful", "success");
  };

  const handleOTPButton = async () => {
    setOtpField(true);
    const payload = {
      email: formik.values.email,
    };
    const response = await getEmailOtp(payload);
    if (response?.data?.error) {
      pushNotification(response?.data?.message, NOTIFICATION.ERROR);
      return;
    }
    pushNotification("OTP sent successfully to your email", NOTIFICATION.SUCCESS);
  };

  const verifyOTP = async (e) => {
    e.preventDefault();
    console.log(otp);
    console.log("OTP verified");
    const payload = {
      email: formik.values.email,
      otp: otp,
    };
    const response = await verifyOtp(payload);
    if (response?.data?.error) {
      pushNotification(response?.data?.message, NOTIFICATION.ERROR);
      setOtpVerified(false);
      return;
    }
    pushNotification("OTP verified successfully", NOTIFICATION.SUCCESS);
    setOtpVerified(true);
    setOtpField(true);
    // setOtp("");
  };

  const handleFormSubmit = async () => {
    // dispatch(updateFormDetails(formik.values));

    if (!otpField) {
      pushNotification("Please Request OTP first", NOTIFICATION.ERROR);
      return;
    }

    if (!otpVerified) {
      pushNotification("Please verify OTP first", NOTIFICATION.ERROR);
      return;
    }

    const body = formatedData(formik.values);

    try {
      // TODO: verify otp first

      const response = await signup(body);
      if (response?.data?.error) {
        pushNotification(response?.data?.message, NOTIFICATION.ERROR);
        return;
      }
      pushNotification(response?.data?.message, NOTIFICATION.SUCCESS);
      // open new page for stripe payment from url
      const newWindow = window.open(response?.data?.data, "_blank", "noopener,noreferrer");
      // if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {
      //   // Fallback in case popup is blocked
      //   window.location.href = response?.data?.data;
      // }
      dispatch(resetFormData());
      navigate("/");
    } catch (error) {
      console.error("Error signing up:", error);
    } finally {
      formik.isSubmitting(false);
    }
  };

  // Initialize formik with a submission handler defined inline to avoid circular references
  const formik = useFormik({
    initialValues: defaultFormData.current,
    validationSchema,
    onSubmit: handleFormSubmit,
  });

  // Handle country and pincode changes
  useEffect(() => {
    if (formik?.values?.country !== defaultFormData.current.country) {
      formik.setFieldValue("pincode", "");
      formik.setFieldValue("state", "");
      // formik.setFieldValue("locality", "");
    }
  }, [formik?.values?.country]);

  const handlePincodeChange = (event) => {
    formik.handleChange(event);
    debouncedFetchPincodeData(
      event.target.value,
      formik,
      setLocalityOption,
      selectedLocalityRef
    );
  };

  useEffect(() => {
    if (Array.isArray(pincodeData) && pincodeData.length > 0) {
      formik.setFieldValue("state", pincodeData[0]?.state);
      // formik.setFieldValue("locality", selectedLocalityRef.current);
    } else {
      setCountryOption(["Australia", "India"]);
      // formik.setFieldValue("state", "");
      // formik.setFieldValue("locality", "");
      formik.setFieldError("pincode", "Invalid pincode");
    }
  }, [pincodeData]);

  // Logo image handling functions
  const handleClearLogoImage = () => {
    setLogoImage();
    setCrop({
      unit: "%",
      width: 100,
      height: 100,
      aspect: 1 / 1,
    });
    setLogoname();
    formik.setFieldValue("clinicLogo", "");
  };

  const handleFileUpload = async (value) => {
    try {
      // Store the file object directly in the form values
      // We'll use this later for the actual upload after form submission

      const filePayload = {
        folder: "assests",
        file_name: value.name,
      };

      const presignedUrlResponseClinicLogo = await getPresignedUrl(filePayload);

      await uploadToS3(
        value,
        presignedUrlResponseClinicLogo?.data?.data?.api_url
      );

      formik.setFieldValue(
        "clinicLogo",
        presignedUrlResponseClinicLogo?.data?.data?.key
      );

      // Return a temporary local URL for preview purposes
      return URL.createObjectURL(value);
    } catch (error) {
      pushNotification("Error processing file", NOTIFICATION.ERROR);
    }
  };

  const handleDrop = (acceptedFiles) => {
    if (acceptedFiles.length > 0) {
      handleFileUpload(acceptedFiles?.[0]);
      if (acceptedFiles?.[0]) {
        const reader = new FileReader();
        reader.onload = (event) => {
          const img = new Image();
          img.onload = () => {
            const aspectRatio = img?.width / img?.height;
            setAspect(aspectRatio);
          };
          img.src = event.target.result;
          setLogoImage(img.src);
        };
        reader?.readAsDataURL(acceptedFiles?.[0]);
      }
    }
  };

  const handelRejection = (rejectedFiles) => {
    rejectedFiles.forEach((rejection) => {
      pushNotification(
        `${rejection?.file?.name} :  ${rejection?.errors?.[0]?.message}`,
        NOTIFICATION.ERROR
      );
    });
  };

  const onLoad = (img) => {
    logoRef.current = img;
  };

  const onCropChange = (crop) => {
    setCrop(crop);
  };

  const onCropComplete = (crop) => {
    createCroppedImage(crop);
  };

  const createCroppedImage = async (crop) => {
    try {
      const { file } = await getCroppedImg(logoRef.current, crop, logoname);
      handleFileUpload(file);
    } catch (error) {
      // Error handling
    }
  };

  const getCroppedImg = (logoImage, crop, fileName) => {
    const canvas = document.createElement("canvas");
    const scaleX = logoImage?.naturalWidth / logoImage?.width;
    const scaleY = logoImage?.naturalHeight / logoImage?.height;
    canvas.width = crop.width;
    canvas.height = crop.height;
    const ctx = canvas.getContext("2d");

    ctx.drawImage(
      logoImage,
      crop.x * scaleX,
      crop.y * scaleY,
      crop.width * scaleX,
      crop.height * scaleY,
      0,
      0,
      crop.width,
      crop.height
    );

    return new Promise((resolve, reject) => {
      canvas.toBlob((blob) => {
        if (!blob) {
          reject("Canvas is empty");
          return;
        }
        const file = new File([blob], fileName, { type: "image/*" });
        const blobUrl = URL.createObjectURL(blob);
        resolve({ file, blobUrl });
      }, "image/*");
    });
  };

  // Terms and conditions drawer
  const toggleDrawer = () => {
    setDrawerOpen(!drawerOpen);
  };

  // Set uploaded file URL
  const setUploadedFileUrl = (documentName, fileUrl) => {
    if (documentName && fileUrl !== undefined) {
      formik.setFieldValue(documentName, fileUrl);
    } else {
      console.error("Invalid parameters for setUploadedFileUrl:", {
        documentName,
        fileUrl,
      });
    }
  };

  // handleSaveAndNext will use formik's handleSubmit

  // Helper function for formatted data
  function formatedData(inputData) {
    const data = {
      user: {
        username: inputData.name,
        email: inputData.email,
        mobile: `${inputData.mobilePrefix ?? mobilePrefixOptions[0].name} ${
          inputData.mobileNumber
        }`,
        password: inputData.password,
        clinicRole: inputData.designation,
        userType: "clinic_admin",
      },
      clinic: {
        name: inputData.companyName,
        address: inputData.fullAddress,
        state: inputData.state,
        phone: `${
          inputData.businessPhonePrefix ?? mobilePrefixOptions[0].name
        } ${inputData.businessPhone}`,
        emergencyPhone: `${
          inputData.emergencyBusinessPhonePrefix ?? mobilePrefixOptions[0].name
        } ${inputData.emergencyBusinessPhone}`,
        fax: inputData.businessFax,
        email: inputData.businessEmail,
        integration: inputData.practiceManagementSystem,
        pms_id: inputData.practiceId,
        practice_name: inputData.practiceName,
        logo: inputData.clinicLogo || null,
        country: inputData.country,
        postal_code: inputData.pincode,
        city: inputData.locality,
        abn_number: inputData.companyABNImageNumber,
        abn_doc: inputData.companyABNImage,
        contract_doc: inputData.contract,
      },
    };
    return data;
  }

  const handleSaveAndNext = async () => {
    if (!otpField) {
      pushNotification("Please Request OTP first", NOTIFICATION.ERROR);
      return;
    }
    if (!otpVerified) {
      pushNotification("Please verify OTP first", NOTIFICATION.ERROR);
      otpButtonRef.current?.focus();
      return;
    }

    if (!testConnection) {
      pushNotification("Please test the connection first", NOTIFICATION.ERROR);
      // scroll to test connection button
      // testConnectionRef.current?.scrollIntoView({
      //   behavior: "smooth",
      // });
      testConnectionRef.current?.focus();
      return;
    }

    const formikError = await formik.validateForm(formik.values);

    const errors = Object.keys(formikError);

    if (errors.length) {
      // Find the first invalid field and focus it
      const firstErrorField = errors[0];
      const firstErrorRef = fieldRefs[firstErrorField]?.current;

      if (firstErrorRef) {
        // Scroll to the first invalid field smoothly
        if (typeof firstErrorRef?.scrollIntoView === "function") {
          firstErrorRef?.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }

        // Focus the field after a slight delay (to ensure scrolling completes first)
        setTimeout(() => firstErrorRef.focus(), 300);
      }

      // Show error notification
      if (formik?.touched[firstErrorField])
        pushNotification(formikError[firstErrorField], NOTIFICATION.ERROR);
      return;
    }

    // If no errors, trigger the formik submission
    formik.handleSubmit();
  };

  return (
    <Box>
      <AppBar
        enableColorOnDark
        position="fixed"
        className={classes.appBarStyle}
        elevation={1}
      >
        <Toolbar>
          <Box className={classes.logoBox}>
            <ButtonBase component={Link} to="/">
              <img className={classes.logo} src={logo} />
            </ButtonBase>
          </Box>
        </Toolbar>
      </AppBar>
      <Box display="flex" className={classes.contentBox}>
        <Box className={classes.mainContent}>
          <FormPageHeader pageTitle={"Business Registration"} showGoBack />

          <Grid container spacing={theme.spacing(2.2)}>
            <Grid item md={12} className={classes.screenViewGridItem}>
              {isLoading ? (
                <Loader />
              ) : (
                <Paper className={classes.whitePaper}>
                  <Box className={classes.paperContainerBox}>
                    <Box>
                      <form>
                        {/* Practice ID */}
                        <FormSectionHeading title="practice id" />
                        <Grid
                          container
                          spacing={theme.spacing(2.3)}
                          padding={`0 ${theme.spacing(3.2)}`}
                          className={classes.formRoot}
                        >
                          <Grid item md={4} sm={6} xs={12}>
                            <TextField value={latestClinicID + 1} disabled />
                          </Grid>
                        </Grid>

                        {/* Personal Details Section */}
                        <FormSectionHeading title="PERSONAL DETAILS" />
                        <Grid
                          container
                          spacing={theme.spacing(2.3)}
                          padding={`0 ${theme.spacing(3.2)}`}
                          className={classes.formRoot}
                        >
                          {/* your name grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Your Full Name*
                            </InputLabel>
                            <TextField
                              fullWidth
                              placeholder="Enter Your Full Name"
                              color="secondary"
                              variant="outlined"
                              name="name"
                              value={formik.values.name}
                              onChange={(e) => {
                                e.target.value = capitalizeFirstLetter(
                                  e.target.value
                                );
                                formik.handleChange(e);
                              }}
                              onBlur={(e) => {
                                formik.setFieldValue(
                                  "name",
                                  e.target.value.trim()
                                );
                                formik.handleBlur(e);
                              }}
                              inputRef={fieldRefs.name}
                              error={Boolean(
                                formik.errors.name && formik.touched.name
                              )}
                              helperText={
                                formik.errors.name && formik.touched.name
                                  ? formik.errors.name
                                  : ""
                              }
                            />
                          </Grid>

                          {/* mobile numer grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Enter Mobile Number*
                            </InputLabel>
                            <TextField
                              className={classes.mobileNumberInput}
                              fullWidth
                              placeholder="Enter Mobile Number"
                              color="secondary"
                              variant="outlined"
                              name="mobileNumber"
                              value={formik.values.mobileNumber}
                              onChange={(e) => {
                                if (e.target.value.length <= 10) {
                                  const value =
                                    e.target.value?.match(/\d+/g) || "";
                                  formik.setFieldValue(
                                    "mobileNumber",
                                    value?.toString()
                                  );
                                }
                              }}
                              onBlur={formik.handleBlur}
                              InputProps={{
                                type: "text",
                                pattern: "[0-9]*",
                                startAdornment: (
                                  <InputAdornment position="start">
                                    <Box sx={{ padding: "1px" }}>
                                      <Select
                                        name="mobilePrefix"
                                        value={formik.values.mobilePrefix}
                                        onChange={formik.handleChange}
                                        onBlur={formik.handleBlur}
                                        inputRef={fieldRefs.mobilePrefix}
                                      >
                                        {mobilePrefixOptions.map((option) => (
                                          <MenuItem
                                            sx={{
                                              outline: "none",
                                              border: "none",
                                            }}
                                            key={option.id}
                                            value={option.name}
                                          >
                                            {option.name}
                                          </MenuItem>
                                        ))}
                                      </Select>
                                    </Box>
                                  </InputAdornment>
                                ),
                              }}
                              inputRef={fieldRefs.mobileNumber}
                              error={Boolean(
                                formik.errors.mobileNumber &&
                                  formik.touched.mobileNumber
                              )}
                              helperText={
                                formik.errors.mobileNumber &&
                                formik.touched.mobileNumber
                                  ? formik.errors.mobileNumber
                                  : ""
                              }
                            />
                          </Grid>

                          {/* email id grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Your Official Email ID*
                            </InputLabel>
                            <TextField
                              fullWidth
                              placeholder="Enter Your Email"
                              color="secondary"
                              variant="outlined"
                              name="email"
                              value={formik.values.email}
                              onChange={formik.handleChange}
                              onBlur={formik.handleBlur}
                              disabled={otpVerified}
                              inputRef={fieldRefs.email}
                              error={Boolean(
                                formik.errors.email && formik.touched.email
                              )}
                              helperText={
                                formik.errors.email && formik.touched.email
                                  ? formik.errors.email
                                  : ""
                              }
                              InputProps={{
                                endAdornment: (
                                  <InputAdornment position="end">
                                    <Button
                                      variant="text"
                                      color="info"
                                      disabled={
                                        !formik.values.email || otpVerified
                                      }
                                      onClick={handleOTPButton}
                                      ref={otpButtonRef}
                                    >
                                      Request OTP
                                    </Button>
                                  </InputAdornment>
                                ),
                              }}
                            />
                            <Typography className={classes.emailNote}>
                              Note: This will be your login ID.
                            </Typography>
                          </Grid>

                          {/* otp verification grid */}
                          {otpField && (
                            <Grid item md={4} sm={6} xs={12}>
                              <InputLabel className={classes.inputLabel}>
                                Enter OTP*
                              </InputLabel>
                              <TextField
                                fullWidth
                                placeholder="Enter OTP"
                                color="secondary"
                                variant="outlined"
                                name="otp"
                                value={otp}
                                onChange={(e) => setOtp(e.target.value)}
                                onBlur={formik.handleBlur}
                                disabled={otpVerified}
                                InputProps={{
                                  type: "text",
                                  pattern: "[0-9]*",
                                  endAdornment: otpVerified ? (
                                    <InputAdornment position="end">
                                      <VerifiedIcon
                                        className={classes.verifyIcon}
                                      />
                                    </InputAdornment>
                                  ) : (
                                    <InputAdornment position="end">
                                      <Button
                                        variant="text"
                                        color="info"
                                        disabled={!otpButtonRef}
                                        onClick={verifyOTP}
                                        ref={otpButtonRef}
                                      >
                                        Verify OTP
                                      </Button>
                                    </InputAdornment>
                                  ),
                                }}
                                inputRef={fieldRefs.otp}
                                error={Boolean(
                                  formik.errors.otp && formik.touched.otp
                                )}
                                helperText={
                                  formik.errors.otp && formik.touched.otp
                                    ? formik.errors.otp
                                    : ""
                                }
                              />
                            </Grid>
                          )}

                          {/* password grid heading */}
                          <FormSectionHeading title="CREATE PASSWORD" />
                          {/* enter password grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Enter Password*
                            </InputLabel>
                            <TextField
                              className={classes.passwordTextFiled}
                              color="secondary"
                              placeholder="Enter Password"
                              variant="outlined"
                              margin="normal"
                              fullWidth
                              type={showPassword ? "text" : "password"}
                              name="password"
                              value={formik.values.password}
                              onChange={formik.handleChange}
                              onBlur={formik.handleBlur}
                              inputRef={fieldRefs.password}
                              error={Boolean(
                                formik.errors.password &&
                                  formik.touched.password
                              )}
                              helperText={
                                formik.errors.password &&
                                formik.touched.password
                                  ? formik.errors.password
                                  : ""
                              }
                              InputProps={{
                                endAdornment: (
                                  <IconButton
                                    onClick={() =>
                                      handleTogglePasswordVisibility("password")
                                    }
                                    edge="end"
                                  >
                                    {showPassword ? (
                                      <VisibilityOutlined />
                                    ) : (
                                      <VisibilityOffOutlined />
                                    )}
                                  </IconButton>
                                ),
                              }}
                            />
                            {/* Password validation display */}
                            {!formik.isValid && (
                              <>
                                <Typography
                                  className={classes.passwordCheckListTitle}
                                >
                                  Note: Password must be
                                </Typography>
                                <Box className={classes.passwordCheckList}>
                                  <PasswordValidation
                                    isValid={passwordLengthRegex.test(
                                      formik.values.password
                                    )}
                                    text="at least 8 characters"
                                  />
                                  <PasswordValidation
                                    isValid={passwordLetterRegex.test(
                                      formik.values.password
                                    )}
                                    text="at least 1 letter"
                                  />
                                  <PasswordValidation
                                    isValid={passwordNumberRegex.test(
                                      formik.values.password
                                    )}
                                    text="at least 1 number"
                                  />
                                  <PasswordValidation
                                    isValid={passwordSpacesRegex.test(
                                      formik.values.password
                                    )}
                                    text="with no spaces at the beginning/end"
                                  />
                                </Box>
                              </>
                            )}
                          </Grid>

                          {/* confirmPassword Grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Confirm Password*
                            </InputLabel>
                            <TextField
                              className={classes.passwordTextFiled}
                              color="secondary"
                              placeholder="Confirm Password"
                              variant="outlined"
                              margin="normal"
                              fullWidth
                              type={showConfirmPassword ? "text" : "password"}
                              name="confirmPassword"
                              value={formik.values.confirmPassword}
                              onChange={(e) => {
                                formik.handleChange(e);
                              }}
                              onBlur={formik.handleBlur}
                              inputRef={fieldRefs.confirmPassword}
                              error={Boolean(
                                formik.errors.confirmPassword &&
                                  formik.touched.confirmPassword
                              )}
                              helperText={
                                formik.errors.confirmPassword &&
                                formik.touched.confirmPassword
                                  ? formik.errors.confirmPassword
                                  : ""
                              }
                              InputProps={{
                                endAdornment: (
                                  <IconButton
                                    onClick={() =>
                                      handleTogglePasswordVisibility(
                                        "confirmPassword"
                                      )
                                    }
                                    edge="end"
                                  >
                                    {showConfirmPassword ? (
                                      <VisibilityOutlined />
                                    ) : (
                                      <VisibilityOffOutlined />
                                    )}
                                  </IconButton>
                                ),
                              }}
                            />
                          </Grid>
                        </Grid>

                        {/* Business Details Section */}
                        <FormSectionHeading title="Business DETAILS" />
                        <Grid
                          container
                          spacing={theme.spacing(2.3)}
                          padding={`0 ${theme.spacing(3.2)}`}
                          className={classes.formRoot}
                        >
                          {/* Clinic name grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Business Name*
                            </InputLabel>

                            <TextField
                              fullWidth
                              placeholder="Enter Business Name"
                              color="secondary"
                              variant="outlined"
                              name="companyName"
                              value={formik.values.companyName}
                              onChange={(e) => {
                                e.target.value = capitalizeFirstLetter(
                                  e.target.value
                                );
                                formik.handleChange(e);
                              }}
                              onBlur={(e) => {
                                formik.setFieldValue(
                                  "companyName",
                                  e.target.value.trim()
                                );
                                formik.handleBlur(e);
                              }}
                              inputRef={fieldRefs.companyName}
                              error={Boolean(
                                formik.errors.companyName &&
                                  formik.touched.companyName
                              )}
                              helperText={
                                formik.errors.companyName &&
                                formik.touched.companyName
                                  ? formik.errors.companyName
                                  : ""
                              }
                            />
                          </Grid>

                          {/* Your designation grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              User Role*
                            </InputLabel>
                            <Select
                              fullWidth
                              name="designation"
                              value={formik.values.designation}
                              onChange={formik.handleChange}
                              onBlur={formik.handleBlur}
                              inputRef={fieldRefs.designation}
                              error={Boolean(
                                formik.errors.designation &&
                                  formik.touched.designation
                              )}
                              helperText={
                                formik.errors.designation &&
                                formik.touched.designation
                                  ? formik.errors.designation
                                  : ""
                              }
                            >
                              {userRoles.map((option) => (
                                <MenuItem key={option.id} value={option.id}>
                                  {option.name}
                                </MenuItem>
                              ))}
                            </Select>
                          </Grid>

                          {/* Business Phone grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Business Phone Number*
                            </InputLabel>
                            <TextField
                              className={classes.mobileNumberInput}
                              fullWidth
                              placeholder="Enter Business Phone Number"
                              color="secondary"
                              variant="outlined"
                              name="businessPhone"
                              value={formik.values.businessPhone}
                              onChange={(e) => {
                                if (e.target.value.length <= 10) {
                                  const value =
                                    e.target.value?.match(/\d+/g) || "";
                                  formik.setFieldValue(
                                    "businessPhone",
                                    value?.toString()
                                  );
                                }
                              }}
                              onBlur={formik.handleBlur}
                              InputProps={{
                                type: "text",
                                pattern: "[0-9]*",
                                startAdornment: (
                                  <InputAdornment position="start">
                                    <Box sx={{ padding: "1px" }}>
                                      <Select
                                        name="businessPhonePrefix"
                                        value={
                                          formik.values.businessPhonePrefix
                                        }
                                        onChange={formik.handleChange}
                                        onBlur={formik.handleBlur}
                                        inputRef={fieldRefs.businessPhonePrefix}
                                      >
                                        {mobilePrefixOptions.map((option) => (
                                          <MenuItem
                                            sx={{
                                              outline: "none",
                                              border: "none",
                                            }}
                                            key={option.id}
                                            value={option.id}
                                          >
                                            {option.name}
                                          </MenuItem>
                                        ))}
                                      </Select>
                                    </Box>
                                  </InputAdornment>
                                ),
                              }}
                              inputRef={fieldRefs.businessPhone}
                              error={Boolean(
                                formik.errors.businessPhone &&
                                  formik.touched.businessPhone
                              )}
                              helperText={
                                formik.errors.businessPhone &&
                                formik.touched.businessPhone
                                  ? formik.errors.businessPhone
                                  : ""
                              }
                            />
                          </Grid>

                          {/* business emergency phone */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Business Emergency Phone Number*
                            </InputLabel>
                            <TextField
                              className={classes.mobileNumberInput}
                              fullWidth
                              placeholder="Enter Emergency Phone Number"
                              color="secondary"
                              variant="outlined"
                              name="emergencyBusinessPhone"
                              value={formik.values.emergencyBusinessPhone}
                              onChange={(e) => {
                                if (e.target.value.length <= 10) {
                                  const value =
                                    e.target.value?.match(/\d+/g) || "";
                                  formik.setFieldValue(
                                    "emergencyBusinessPhone",
                                    value?.toString()
                                  );
                                }
                              }}
                              onBlur={formik.handleBlur}
                              InputProps={{
                                type: "text",
                                pattern: "[0-9]*",
                                startAdornment: (
                                  <InputAdornment position="start">
                                    <Box sx={{ padding: "1px" }}>
                                      <Select
                                        name="emergencyBusinessPhonePrefix"
                                        value={
                                          formik.values
                                            .emergencyBusinessPhonePrefix
                                        }
                                        onChange={formik.handleChange}
                                        onBlur={formik.handleBlur}
                                        inputRef={
                                          fieldRefs.emergencyBusinessPhonePrefix
                                        }
                                      >
                                        {mobilePrefixOptions.map((option) => (
                                          <MenuItem
                                            sx={{
                                              outline: "none",
                                              border: "none",
                                            }}
                                            key={option.id}
                                            value={option.id}
                                          >
                                            {option.name}
                                          </MenuItem>
                                        ))}
                                      </Select>
                                    </Box>
                                  </InputAdornment>
                                ),
                              }}
                              inputRef={fieldRefs.emergencyBusinessPhone}
                              error={Boolean(
                                formik.errors.emergencyBusinessPhone &&
                                  formik.touched.emergencyBusinessPhone
                              )}
                              helperText={
                                formik.errors.emergencyBusinessPhone &&
                                formik.touched.emergencyBusinessPhone
                                  ? formik.errors.emergencyBusinessPhone
                                  : ""
                              }
                            />
                          </Grid>

                          {/* Business Fax grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Business Fax Number
                            </InputLabel>
                            <TextField
                              // className={classes.mobileNumberInput}
                              fullWidth
                              placeholder="Enter Fax Number"
                              color="secondary"
                              variant="outlined"
                              name="businessFax"
                              value={formik.values.businessFax}
                              onChange={(e) => {
                                if (e.target.value.length <= 10) {
                                  const value =
                                    e.target.value?.match(/\d+/g) || "";
                                  formik.setFieldValue(
                                    "businessFax",
                                    value?.toString()
                                  );
                                }
                              }}
                              onBlur={formik.handleBlur}
                              InputProps={{
                                type: "text",
                                pattern: "[0-9]*",
                              }}
                              inputRef={fieldRefs.businessFax}
                              error={Boolean(
                                formik.errors.businessFax &&
                                  formik.touched.businessFax
                              )}
                              helperText={
                                formik.errors.businessFax &&
                                formik.touched.businessFax
                                  ? formik.errors.businessFax
                                  : ""
                              }
                            />
                          </Grid>

                          {/* Business Email grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Business Email*
                            </InputLabel>
                            <TextField
                              // className={classes.mobileNumberInput}
                              fullWidth
                              placeholder="Enter Business Email"
                              color="secondary"
                              variant="outlined"
                              name="businessEmail"
                              value={formik.values.businessEmail}
                              onChange={formik.handleChange}
                              onBlur={formik.handleBlur}
                              InputProps={{
                                type: "email",
                              }}
                              inputRef={fieldRefs.businessEmail}
                              error={Boolean(
                                formik.errors.businessEmail &&
                                  formik.touched.businessEmail
                              )}
                              helperText={
                                formik.errors.businessEmail &&
                                formik.touched.businessEmail
                                  ? formik.errors.businessEmail
                                  : ""
                              }
                            />
                          </Grid>

                          {/* practice management system */}
                          <Grid item xs={6} md={4}>
                            <InputLabel
                              className={classes.inputLabel}
                              id="integration-software-label"
                            >
                              Integrate with
                            </InputLabel>
                            <Select
                              fullWidth
                              name="practiceManagementSystem"
                              value={formik.values.practiceManagementSystem}
                              onChange={formik.handleChange}
                              inputRef={fieldRefs.practiceManagementSystem}
                              error={Boolean(
                                formik.errors.practiceManagementSystem &&
                                  formik.touched.practiceManagementSystem
                              )}
                              helperText={
                                formik.errors.practiceManagementSystem &&
                                formik.touched.practiceManagementSystem
                                  ? formik.errors.practiceManagementSystem
                                  : ""
                              }
                            >
                              {integrationOptions.map((option) => (
                                <MenuItem key={option.id} value={option.id}>
                                  {option.name}
                                </MenuItem>
                              ))}
                            </Select>
                          </Grid>

                          {/* PMS ID grid */}
                          <Grid item xs={12} md={4}>
                            <InputLabel className={classes.inputLabel}>
                              PMS ID
                            </InputLabel>
                            <TextField
                              fullWidth
                              name="practiceId"
                              value={formik.values.practiceId}
                              onChange={formik.handleChange}
                              variant="outlined"
                              disabled={!formik.values.practiceManagementSystem}
                              error={
                                !!formik.values.practiceManagementSystem &&
                                formik.errors.practiceId
                              }
                              helperText={
                                !!formik.values.practiceManagementSystem &&
                                formik.errors.practiceId
                                  ? "Practice ID is required"
                                  : ""
                              }
                            />
                          </Grid>

                          {/* Practice Name grid */}
                          <Grid item xs={12} md={4}>
                            <InputLabel className={classes.inputLabel}>
                              Practice Name
                            </InputLabel>
                            <TextField
                              fullWidth
                              name="practiceName"
                              value={formik.values.practiceName}
                              onChange={formik.handleChange}
                              variant="outlined"
                              disabled={!formik.values.practiceManagementSystem}
                              error={
                                !!formik.values.practiceManagementSystem &&
                                formik.errors.practiceName
                              }
                              helperText={
                                !!formik.values.practiceManagementSystem &&
                                formik.errors.practiceName
                                  ? "Practice Name is required"
                                  : ""
                              }
                            />
                          </Grid>

                          {/* Test Connection Button */}
                          <Grid item xs={12} md={8}>
                            <Button
                              variant="contained"
                              color="primary"
                              onClick={handleTestConnection}
                              ref={testConnectionRef}
                            >
                              Test Connection
                            </Button>
                          </Grid>

                          {/* Clinic logo grid */}
                          {/* <Grid item md={5} sm={12}>
                            <InputLabel
                              sx={{
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "space-between",
                              }}
                              className={classes.inputLabel}
                            >
                              Add Business Logo
                              {(logoImage || formik.values.clinicLogo) && (
                                <div>
                                  <button
                                    className={classes.imgButton}
                                    onClick={handleClearLogoImage}
                                  >
                                    REMOVE
                                  </button>
                                </div>
                              )}
                            </InputLabel>
                            <Box display="flex">
                              <Box className={classes.dropZoneOuterBox}>
                                <label htmlFor="clinicLogo">
                                  <Dropzone
                                    accept={{
                                      "image/": [...IMAGE_TYPE],
                                    }}
                                    onDrop={(e) => handleDrop(e)}
                                    onDropRejected={handelRejection}
                                    maxFiles={MAX_FILES}
                                    maxSize={MAX_FILE_SIZE_IN_MB * 1024 * 1024}
                                  >
                                    {({
                                      getRootProps,
                                      getInputProps,
                                      open,
                                    }) => {
                                      fileInputRef.current = open;
                                      return (
                                        <div
                                          {...getRootProps({
                                            onClick: (event) => {
                                              if (
                                                logoImage ||
                                                formik.values.clinicLogo
                                              ) {
                                                event.stopPropagation();
                                              }
                                            },
                                          })}
                                        >
                                          <input {...getInputProps()} />
                                          <Box className={classes.addButton}>
                                            <Box
                                              className={
                                                classes.addButtonContent
                                              }
                                            >
                                              {!logoImage &&
                                              !formik.values.clinicLogo ? (
                                                <>
                                                  <Box
                                                    className={classes.addIcon}
                                                    component="img"
                                                    src={uploadIcon}
                                                  />
                                                  <Typography
                                                    className={classes.addText}
                                                  >
                                                    Drag and drop file here, or
                                                    click add
                                                  </Typography>
                                                  <Typography
                                                    className={
                                                      classes.addSubtext
                                                    }
                                                  >
                                                    Allowed file types are jpeg,
                                                    png, svg to a maximum size
                                                    of 5 MB
                                                  </Typography>
                                                </>
                                              ) : (
                                                <>
                                                  {logoImage && (
                                                    <ReactCrop
                                                      src={logoImage}
                                                      crop={crop}
                                                      onChange={onCropChange}
                                                      onComplete={
                                                        onCropComplete
                                                      }
                                                      onImageLoaded={onLoad}
                                                      aspect={aspect}
                                                    >
                                                      <img
                                                        alt="Crop me"
                                                        src={logoImage}
                                                        ref={logoRef}
                                                        height="125px"
                                                        width="auto"
                                                      />
                                                    </ReactCrop>
                                                  )}
                                                  {!logoImage &&
                                                    formik.values
                                                      .clinicLogo && (
                                                      <img
                                                        alt="Edit me"
                                                        src={
                                                          IMAGE_LOCATION_BASE_URL +
                                                          formik.values
                                                            .clinicLogo
                                                        }
                                                        className={
                                                          classes.editImage
                                                        }
                                                        height="100%"
                                                      />
                                                    )}
                                                </>
                                              )}
                                            </Box>
                                            {formik.errors.clinicLogo &&
                                              formik.touched.clinicLogo && (
                                                <Box
                                                  component="span"
                                                  className={
                                                    classes.logoUploadErrorBox
                                                  }
                                                >
                                                  <span
                                                    className={
                                                      classes.errorText
                                                    }
                                                  >
                                                    {formik.errors.clinicLogo
                                                      ? formik.errors.clinicLogo
                                                      : ""}
                                                  </span>
                                                </Box>
                                              )}
                                          </Box>
                                        </div>
                                      );
                                    }}
                                  </Dropzone>
                                </label>
                              </Box>
                            </Box>
                          </Grid> */}
                        </Grid>

                        {/* ADD Business ADDRESS */}
                        <FormSectionHeading title="ADD Business ADDRESS" />

                        <Grid
                          container
                          spacing={theme.spacing(2.3)}
                          padding={`0 ${theme.spacing(3.2)}`}
                          className={classes.formRoot}
                        >
                          {/* Country grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Country*
                            </InputLabel>

                            <Select
                              className={classes.textAreaLast}
                              variant="outlined"
                              margin="normal"
                              name="country"
                              value={formik.values.country}
                              onChange={(e) => {
                                formik.handleChange(e);
                              }}
                              onBlur={formik.handleBlur}
                              IconComponent={ExpandMore}
                              displayEmpty
                              inputRef={fieldRefs.country}
                              error={Boolean(
                                formik.errors.country && formik.touched.country
                              )}
                              helperText={formik.errors.country}
                            >
                              <MenuItem value="" disabled>
                                <Typography className={classes.placeholderText}>
                                  Select Country
                                </Typography>
                              </MenuItem>
                              {countryOption?.map((option) => (
                                <MenuItem value={option} key={option}>
                                  {option}
                                </MenuItem>
                              ))}
                            </Select>

                            {formik.errors.country && formik.touched.country ? (
                              <FormHelperText className={classes.helperText}>
                                {formik.errors.country}
                              </FormHelperText>
                            ) : null}
                          </Grid>

                          {/* pincode grid */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Pin/Post Code*
                            </InputLabel>
                            <TextField
                              fullWidth
                              placeholder="Enter Your Pincode"
                              color="secondary"
                              variant="outlined"
                              name="pincode"
                              value={formik.values.pincode}
                              onChange={(e) => {
                                if (e.target.value.length <= 6) {
                                  handlePincodeChange(e);
                                }
                              }}
                              onBlur={formik.handleBlur}
                              inputRef={fieldRefs.pincode}
                              error={Boolean(
                                formik.errors.pincode && formik.touched.pincode
                              )}
                              helperText={
                                formik.errors.pincode && formik.touched.pincode
                                  ? formik.errors.pincode
                                  : ""
                              }
                            />
                          </Grid>

                          {/* state grid disable */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              State
                            </InputLabel>
                            <TextField
                              className={classes.stateTextField}
                              fullWidth
                              placeholder="State"
                              color="secondary"
                              variant="outlined"
                              name="state"
                              value={formik.values.state}
                              inputRef={fieldRefs.state}
                              onChange={(e) => {
                                formik.setFieldValue("state", e.target.value);
                              }}
                            />
                          </Grid>

                          {/* locality grid dropdown */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              City*
                            </InputLabel>

                            <Select
                              className={classes.textAreaLast}
                              variant="outlined"
                              margin="normal"
                              name="locality"
                              value={formik.values.locality}
                              onChange={(e) => {
                                formik.handleChange(e);
                              }}
                              onBlur={formik.handleBlur}
                              IconComponent={ExpandMore}
                              displayEmpty
                              inputRef={fieldRefs.locality}
                              error={Boolean(
                                formik.errors.locality &&
                                  formik.touched.locality
                              )}
                              helperText={formik.errors.locality}
                            >
                              <MenuItem value="" disabled>
                                <Typography className={classes.placeholderText}>
                                  Select City
                                </Typography>
                              </MenuItem>
                              {localityOption?.map((option) => (
                                <MenuItem value={option} key={option}>
                                  {option}
                                </MenuItem>
                              ))}
                            </Select>

                            {formik.errors.locality &&
                            formik.touched.locality ? (
                              <FormHelperText className={classes.helperText}>
                                {formik.errors.locality}
                              </FormHelperText>
                            ) : null}
                          </Grid>

                          {/* full address grid */}
                          <Grid item md={12} sm={12} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Full Address*
                            </InputLabel>
                            <TextField
                              fullWidth
                              multiline
                              placeholder="Enter Full Address"
                              color="secondary"
                              variant="outlined"
                              name="fullAddress"
                              value={formik.values.fullAddress}
                              onChange={formik.handleChange}
                              onBlur={(e) => {
                                formik.setFieldValue(
                                  "fullAddress",
                                  e.target.value.trim()
                                );
                                formik.handleBlur(e);
                              }}
                              inputRef={fieldRefs.fullAddress}
                              error={Boolean(
                                formik.errors.fullAddress &&
                                  formik.touched.fullAddress
                              )}
                              helperText={
                                formik.errors.fullAddress &&
                                formik.touched.fullAddress
                                  ? formik.errors.fullAddress
                                  : ""
                              }
                            />
                          </Grid>
                        </Grid>

                        {/* ADD DOCUMENTS */}
                        <FormSectionHeading
                          title="ADD DOCUMENTS"
                          className={classes.formSectionHeadingMargin}
                        />

                        <Grid
                          container
                          spacing={theme.spacing(2.3)}
                          padding={`0 ${theme.spacing(3.2)}`}
                          className={classes.formRoot}
                          sx={{ display: "flex", flexDirection: "column" }}
                        >
                          {/* PAN NUMBER GRID  */}
                          <Grid item md={4} sm={6} xs={12}>
                            <InputLabel className={classes.inputLabel}>
                              Clinic ABN/ACN Number*
                            </InputLabel>

                            <TextField
                              fullWidth
                              placeholder="Enter Clinic ABN/ACN Number"
                              color="secondary"
                              variant="outlined"
                              name="companyABNImageNumber"
                              value={formik.values.companyABNImageNumber}
                              onChange={(e) => {
                                if (
                                  e.target.value.length <= ABN_NUMBER_LENGTH
                                ) {
                                  e.target.value = capitalizeAllLetters(
                                    e.target.value
                                  );
                                  formik.handleChange(e);
                                }
                              }}
                              onBlur={(e) => {
                                formik.setFieldValue(
                                  "companyABNImageNumber",
                                  e.target.value.trim()
                                );
                                formik.handleBlur(e);
                              }}
                              inputRef={fieldRefs.companyABNImageNumber}
                              error={Boolean(
                                formik.errors.companyABNImageNumber &&
                                  formik.touched.companyABNImageNumber
                              )}
                              helperText={
                                formik.errors.companyABNImageNumber &&
                                formik.touched.companyABNImageNumber
                                  ? formik.errors.companyABNImageNumber
                                  : ""
                              }
                              InputProps={{
                                endAdornment: (
                                  <InputAdornment position="end">
                                    {!formik.errors.companyABNImageNumber ? (
                                      <VerifiedIcon
                                        className={classes.verifyIcon}
                                      />
                                    ) : null}
                                  </InputAdornment>
                                ),
                              }}
                            />
                          </Grid>

                          {/* PAN image upload grid */}
                          <Grid item md={4} sm={12} xs={12}>
                            <CustomFileUpload
                              label="Add ABN/ACN Image*"
                              documentName="companyABNImage"
                              onUploadDone={setUploadedFileUrl}
                              maxFileSizeInMb={MAX_FILE_SIZE_IN_MB}
                              maxFiles={MAX_FILES}
                              uploadedFileUrl={formik.values.companyABNImage}
                              errorMessage={
                                formik.errors.companyABNImage &&
                                formik.touched.companyABNImage
                                  ? formik.errors.companyABNImage
                                  : ""
                              }
                            />
                          </Grid>

                          {/* contract grid */}
                          <Grid
                            display="flex"
                            flexDirection="row"
                            justifyContent="space-between"
                            alignItems="center"
                            item
                            md={4}
                            sm={12}
                            xs={12}
                          >
                            <Box mr={2}>
                              <Tooltip title="Download the contract template">
                                <Button>Download Contract Template</Button>
                              </Tooltip>
                            </Box>
                            <CustomFileUpload
                              label="Add Contract*"
                              documentName="contract"
                              onUploadDone={setUploadedFileUrl}
                              maxFileSizeInMb={MAX_FILE_SIZE_IN_MB}
                              maxFiles={MAX_FILES}
                              uploadedFileUrl={formik.values.contract}
                              errorMessage={
                                formik.errors.contract &&
                                formik.touched.contract
                                  ? formik.errors.contract
                                  : ""
                              }
                            />
                          </Grid>

                          {/* terms and condition grid */}
                          <Grid item md={12}>
                            <Box display="flex">
                              <Box className={classes.checkBox}>
                                <CustomizedCheckbox
                                  size={"18px"}
                                  checked={
                                    formik.values.termsAccepted === "true"
                                  }
                                  onChange={() =>
                                    formik.setFieldValue(
                                      "termsAccepted",
                                      formik.values.termsAccepted === "true"
                                        ? "false"
                                        : "true"
                                    )
                                  }
                                  name="termsAccepted"
                                />
                              </Box>
                              <Typography
                                ref={fieldRefs.termsAccepted}
                                className={classes.checkBoxLabel}
                              >
                                I agree to{" "}
                                <span>
                                  {" "}
                                  <Link
                                    className={classes.linkText}
                                    onClick={toggleDrawer}
                                  >
                                    {" "}
                                    Terms and Conditions
                                  </Link>
                                </span>{" "}
                                of 24/7 AI Healthcare Receptionist.
                              </Typography>
                            </Box>
                            {formik.errors.termsAccepted &&
                              formik.touched.termsAccepted && (
                                <div
                                  className={
                                    classes.termsAndConditionErrorMessage
                                  }
                                >
                                  {formik.errors.termsAccepted}
                                </div>
                              )}
                          </Grid>
                          <Drawer
                            anchor="right"
                            open={drawerOpen}
                            onClose={toggleDrawer}
                            variant="persistent"
                            className={classes.termsAndConditionDrawer}
                          >
                            <TermsAndCondition onClose={toggleDrawer} />
                          </Drawer>
                        </Grid>
                      </form>
                    </Box>
                  </Box>
                  <FormFooterMessage
                    mandatoryFieldText="Please Note: All the starred fields are mandatory."
                    nextButtonTitle="Save & Next"
                    nextButtonOnClick={handleSaveAndNext}
                    isSubmitting={formik.isSubmitting}
                  />
                </Paper>
              )}
            </Grid>
          </Grid>
        </Box>
      </Box>
    </Box>
  );
}

export default YourDetailsForm;
