import React, { ChangeEvent, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
  Box,
  Paper,
  Button,
  Container,
  Typography,
  Stack,
  Snackbar,
  Alert,
  IconButton,
  useMediaQuery,
  styled,
  TextField,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { ICountry } from "country-state-city";
import { CountrySelect } from "react-country-state-city";
import "react-country-state-city/dist/react-country-state-city.css";
import { TEXT, ERROR_MESSAGES, TYPOGRAPHY_TEXT } from "../../const";
import themestyle from "../../theme";
import { useMutation } from "@apollo/client";
import { UPDATE_PROFILE_USER } from "../../graphql/mutation";
import IntelliwealthTextField from "../../components/intelliwealthTextField";
import { Country } from "country-state-city";
import { useSession } from "../../context/sessioncontext";

interface CountryDataType {
  id: number;
  name: string;
  isoCode: string;
  phonecode: string;
  flag: string;
  currency: string;
  latitude: string;
  longitude: string;
  timezones: Array<{
    zoneName: string;
    gmtOffset: number;
    gmtOffsetName: string;
    abbreviation: string;
    tzName: string;
  }>;
}

interface AppCountry {
  id: number;
  isoCode: string;
  name: string;
}

const Item = styled("div")(({ theme }) => ({
  marginBottom: "0px",
  padding: "7px",
  textAlign: "center",
  [theme.breakpoints.down("sm")]: {
    marginBottom: "0px",
    padding: "4px",
  },
}));

const customStyles = `
  .rsc-input {
    height: 30px !important;
    padding: 5px 10px !important;
    font-size: 14px !important;
    border-radius: 8px !important;
    border: 1px solid #FFFFFF !important;
    width: 100% !important;
    line-height: 20px !important;
  }
  .rsc-input-error {
    border: 1px solid #d32f2f !important;
  }
  .rsc-select .rsc-option {
    padding: 5px 10px !important;
    font-size: 14px !important;
    color: #222222 !important;
    line-height: 20px !important;
  }
  .stdropdown-container {
    border: 1px solid #222222 !important;
  }
`;

const styleSheet = new CSSStyleSheet();
styleSheet.replaceSync(customStyles);
document.adoptedStyleSheets = [styleSheet];

const ClientOnBoard: React.FC = () => {
  const apiBase = (() => {
    const gqlUrl = process.env.REACT_APP_API_URL;
    try {
      return gqlUrl ? new URL(gqlUrl).origin : "";
    } catch {
      return "";
    }
  })();

  const startDiditVerification = async () => {
    const workflowId = process.env.REACT_APP_DIDIT_WORKFLOW_ID as string | undefined;
    const redirectUri = process.env.REACT_APP_REDIRECT_URI as string | undefined;
    if (!apiBase || !workflowId || !redirectUri) {
      console.error("Didit config missing: apiBase/workflowId/redirectUri");
      return false;
    }
    try {
      const res = await fetch(`${apiBase}/api/didit/verification-sessions`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ workflowId, redirectUri }),
      });
      if (!res.ok) {
        const text = await res.text();
        throw new Error(text || `HTTP ${res.status}`);
      }
      const json = await res.json();
      const url = json?.url as string | undefined;
      if (!url) throw new Error("No Didit URL returned");
      window.location.href = url;
      return true;
    } catch (e) {
      console.error("Failed to start Didit verification:", e);
      return false;
    }
  };

  const [email, setEmail] = useState("");
  const { login } = useSession();
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [country, setCountry] = useState<AppCountry | null>(null);
  const [phoneNumber, setPhoneNumber] = useState("");
  const [companyName, setCompanyName] = useState("");
  const [address, setAddress] = useState("");
  const [pincode, setPincode] = useState("");
  const [emailErrorMessage, setEmailErrorMessage] = useState("");
  const [firstNameErrorMessage, setFirstNameErrorMessage] = useState("");
  const [lastNameErrorMessage, setLastNameErrorMessage] = useState("");
  const [countryErrorMessage, setCountryErrorMessage] = useState("");
  const [phoneNumberErrorMessage, setPhoneNumberErrorMessage] = useState("");
  const [companyNameErrorMessage, setCompanyNameErrorMessage] = useState("");
  const [addressErrorMessage, setAddressErrorMessage] = useState("");
  const [pincodeErrorMessage, setPincodeErrorMessage] = useState("");
  const [successMessage, setSuccessMessage] = useState("");
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">(
    "error"
  );
  const [isSubmitButtonDisabled, setIsSubmitButtonDisabled] = useState(true);
  const navigate = useNavigate();
  const [updateProfile, { loading: updateLoading, error: updateError }] =
    useMutation(UPDATE_PROFILE_USER);
  const isMobile = useMediaQuery("(max-width:600px)");

  useEffect(() => {
    const storedUserData = localStorage.getItem("user");
    if (storedUserData) {
      try {
        const storedUser = JSON.parse(storedUserData);
        if (storedUser && storedUser.id) {
          setEmail(storedUser.email || "");
          setFirstName(
            storedUser.firstName === "Unknown" ? "" : storedUser.firstName || ""
          );
          setLastName(
            storedUser.lastName === "Unknown" ? "" : storedUser.lastName || ""
          );
          setPhoneNumber(storedUser.phoneNumber || "");
          setCompanyName(storedUser.companyName || "");
          setAddress(storedUser.address || "");
          setPincode(storedUser.pincode || "");

          if (storedUser.country) {
            const countryData = Country.getAllCountries().find(
              (c: ICountry) => c.name === storedUser.country
            ) as CountryDataType | undefined;

            if (countryData) {
              const countryObj: AppCountry = {
                id: countryData.id,
                isoCode: countryData.isoCode,
                name: countryData.name,
              };
              setCountry(countryObj);
            } else {
            }
          }
        }
      } catch (e) {
        console.error("Failed to parse user data from localStorage:", e);
      }
    }
  }, []);

  const isValidEmail = (email: string): boolean => {
    const emailRegex = ERROR_MESSAGES.EMAILREG;
    return emailRegex.test(email);
  };

  const isValidName = (name: string): boolean => {
    return ERROR_MESSAGES.NAMEREG.test(name.trim());
  };

  const isValidPhoneNumber = (phone: string): boolean => {
    if (!phone || phone.trim() === "") return false;
    const phoneRegex = ERROR_MESSAGES.PHONEREG;
    return phoneRegex.test(phone);
  };

  const isValidCompanyName = (company: string): boolean => {
    return company.trim().length >= 3;
  };

  const isValidCountry = (country: AppCountry | null): boolean => {
    return !!country && country.id !== undefined && country.id > 0;
  };

  const isValidAddress = (address: string): boolean => {
    return address.trim().length >= 5;
  };

  const isValidPincode = (pincode: string): boolean => {
    if (!pincode || pincode.trim() === "") return false;
    const pincodeRegex = ERROR_MESSAGES.POSTCODEREG;
    return pincodeRegex.test(pincode);
  };

  useEffect(() => {
    const emailValid = isValidEmail(email);
    const firstNameValid = isValidName(firstName);
    const lastNameValid = isValidName(lastName);
    const countryValid = isValidCountry(country);
    const phoneValid = isValidPhoneNumber(phoneNumber);
    const companyValid = isValidCompanyName(companyName);
    const addressValid = isValidAddress(address);
    const pincodeValid = isValidPincode(pincode);
    setIsSubmitButtonDisabled(
      !(
        emailValid &&
        firstNameValid &&
        lastNameValid &&
        countryValid &&
        phoneValid &&
        companyValid &&
        addressValid &&
        pincodeValid
      )
    );
  }, [email, firstName, lastName, country, phoneNumber, companyName, address, pincode]);

  const handleEmailChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value);
  };

  const handleFirstNameChange = (e: ChangeEvent<HTMLInputElement>) => {
    setFirstName(e.target.value);
  };

  const handleLastNameChange = (e: ChangeEvent<HTMLInputElement>) => {
    setLastName(e.target.value);
  };

  const handleCountrySelectChange = (selectedCountry: any) => {
    const countryObj: AppCountry | null = selectedCountry
      ? {
          id: selectedCountry.id,
          isoCode: selectedCountry.isoCode,
          name: selectedCountry.name,
        }
      : null;
    setCountry(countryObj);
    setCountryErrorMessage("");
  };

  const handlePhoneNumberChange = (e: ChangeEvent<HTMLInputElement>) => {
    setPhoneNumber(e.target.value);
  };

  const handleCompanyNameChange = (e: ChangeEvent<HTMLInputElement>) => {
    setCompanyName(e.target.value);
  };

  const handleAddressChange = (e: ChangeEvent<HTMLInputElement>) => {
    setAddress(e.target.value);
  };

  const handlePincodeChange = (e: ChangeEvent<HTMLInputElement>) => {
    setPincode(e.target.value);
  };

  const handleEmailFocus = () => {
    setEmailErrorMessage("");
  };
  const handleFirstNameFocus = () => {
    setFirstNameErrorMessage("");
  };
  const handleLastNameFocus = () => {
    setLastNameErrorMessage("");
  };
  const handleCountryFocus = () => {
    setCountryErrorMessage("");
  };
  const handlePhoneNumberFocus = () => {
    setPhoneNumberErrorMessage("");
  };
  const handleCompanyNameFocus = () => {
    setCompanyNameErrorMessage("");
  };
  const handleAddressFocus = () => {
    setAddressErrorMessage("");
  };
  const handlePincodeFocus = () => {
    setPincodeErrorMessage("");
  };

  const handleEmailBlur = () => {
    if (!isValidEmail(email) && email.length > 0) {
      setEmailErrorMessage(ERROR_MESSAGES.EMAIL_VAILD);
    } else {
      setEmailErrorMessage("");
    }
  };

  const handleFirstNameBlur = () => {
    if (!isValidName(firstName) && firstName.length > 0) {
      setFirstNameErrorMessage(ERROR_MESSAGES.FIRST_NAME);
    } else {
      setFirstNameErrorMessage("");
    }
  };

  const handleLastNameBlur = () => {
    if (!isValidName(lastName) && lastName.length > 0) {
      setLastNameErrorMessage(ERROR_MESSAGES.LAST_NAME);
    } else {
      setLastNameErrorMessage("");
    }
  };

  const handleCountryBlur = () => {
    if (!isValidCountry(country)) {
      setCountryErrorMessage(ERROR_MESSAGES.COUNTRY);
    } else {
      setCountryErrorMessage("");
    }
  };

  const handlePhoneNumberBlur = () => {
    if (!isValidPhoneNumber(phoneNumber) && phoneNumber.length > 0) {
      setPhoneNumberErrorMessage(ERROR_MESSAGES.ENTER_VALID);
    } else {
      setPhoneNumberErrorMessage("");
    }
  };

  const handleCompanyNameBlur = () => {
    if (!isValidCompanyName(companyName) && companyName.length > 0) {
      setCompanyNameErrorMessage(ERROR_MESSAGES.COMPANY_NAME);
    } else {
      setCompanyNameErrorMessage("");
    }
  };

  const handleAddressBlur = () => {
    if (!isValidAddress(address) && address.length > 0) {
      setAddressErrorMessage(ERROR_MESSAGES.ADDRESS_MUST_BE);
    } else {
      setAddressErrorMessage("");
    }
  };

  const handlePincodeBlur = () => {
    if (!isValidPincode(pincode) && pincode.length > 0) {
      setPincodeErrorMessage(ERROR_MESSAGES.PINCODE);
    } else {
      setPincodeErrorMessage("");
    }
  };

  const handleSubmit = async () => {
    let hasError = false;

    if (!isValidEmail(email)) {
      setEmailErrorMessage(ERROR_MESSAGES.EMAIL_VAILD);
      hasError = true;
    }
    if (!isValidName(firstName)) {
      setFirstNameErrorMessage(ERROR_MESSAGES.FIRST_NAME);
      hasError = true;
    }
    if (!isValidName(lastName)) {
      setLastNameErrorMessage(ERROR_MESSAGES.LAST_NAME);
      hasError = true;
    }
    if (!isValidCountry(country)) {
      setCountryErrorMessage(ERROR_MESSAGES.COUNTRY);
      hasError = true;
    }
    if (!isValidPhoneNumber(phoneNumber)) {
      setPhoneNumberErrorMessage(ERROR_MESSAGES.ENTER_VALID);
      hasError = true;
    }
    if (!isValidCompanyName(companyName)) {
      setCompanyNameErrorMessage(ERROR_MESSAGES.COMPANY_NAME);
      hasError = true;
    }
    if (!isValidAddress(address)) {
      setAddressErrorMessage(ERROR_MESSAGES.ADDRESS_MUST_BE);
      hasError = true;
    }
    if (!isValidPincode(pincode)) {
      setPincodeErrorMessage(ERROR_MESSAGES.PINCODE);
      hasError = true;
    }

    if (hasError) {
      setSnackbarSeverity("error");
      setSuccessMessage("Please correct the highlighted errors.");
      setSnackbarOpen(true);
      return;
    }

    try {
      const storedUserData = localStorage.getItem("user");
      let userId = null;
      if (storedUserData) {
        const storedUser = JSON.parse(storedUserData);
        userId = storedUser.id;
      }
      if (!userId) {
        throw new Error(ERROR_MESSAGES.USER_ID_NOT_FOUND);
      }

      const { data } = await updateProfile({
        variables: {
          input: {
            id: userId,
            email,
            firstName,
            lastName,
            country: country?.name || "",
            phoneNumber,
            companyName,
            address,
            pincode,
          },
        },
        context: {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        },
      });

      const { updateProfile: user } = data;
      localStorage.setItem(
        "user",
        JSON.stringify({
          ...user,
          country: country?.name,
        })
      );
      // Mark session logged-in, then kick off KYC via Didit
      login();
      const launched = await startDiditVerification();
      if (!launched) {
        // Fallback to success banner + dashboard if KYC launch failed
        setSuccessMessage(TEXT.CONTACT_INFO);
        setSnackbarSeverity("success");
        setSnackbarOpen(true);
        login()
      }
    } catch (error: any) {
      const errorMessage = error.message;
      if (errorMessage.includes("email")) setEmailErrorMessage(errorMessage);
      else if (errorMessage.includes("phone"))
        setPhoneNumberErrorMessage(errorMessage);
      else if (errorMessage.includes("pincode"))
        setPincodeErrorMessage(errorMessage);
      else setSuccessMessage(errorMessage);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
    }
  };

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === "Enter") {
      handleSubmit();
    }
  };

  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
    setEmailErrorMessage("");
    setFirstNameErrorMessage("");
    setLastNameErrorMessage("");
    setCountryErrorMessage("");
    setPhoneNumberErrorMessage("");
    setCompanyNameErrorMessage("");
    setAddressErrorMessage("");
    setPincodeErrorMessage("");
    setSuccessMessage("");
    login();
    if (snackbarSeverity === "success") {
      navigate("/didit-verification");
    }
  };

  const greeting =
    firstName && firstName !== "Unknown" ? `Hi ${firstName}` : "Hi Customer";

  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        minHeight: "80vh",
        backgroundColor: "#F9FAFC",
        padding: isMobile ? "5px" : "24px",
      }}
    >
      <Container maxWidth={isMobile ? "xs" : "sm"}>
        <Paper
          elevation={3}
          sx={{
            padding: isMobile ? "10px" : "24px",
            width: "100%",
            maxWidth: isMobile ? "95%" : "600px",
            borderRadius: isMobile ? "6px" : "12px",
            margin: "auto",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Stack
            spacing={isMobile ? 16 : 24}
            direction="column"
            alignItems="center"
          >
            <Box
              component="form"
              onKeyPress={handleKeyPress}
              sx={{ width: "100%" }}
            >
              <Item>
                <Typography
                  variant={isMobile ? "h6" : "h5"}
                  sx={{
                    color: themestyle.colors.primary,
                    fontFamily: themestyle.fontFamily.lato,
                    fontWeight: 700,
                  }}
                >
                  {greeting}
                </Typography>
              </Item>
              <Item>
                <Typography
                  variant="body1"
                  sx={{
                    color: "#757575",
                    fontFamily: themestyle.fontFamily.lato,
                    fontWeight: 500,
                    fontSize: isMobile ? "14px" : "16px",
                    textAlign: "center",
                    marginBottom: "16px",
                  }}
                >
                  {TEXT.CONFIRM}
                </Typography>
              </Item>
              <Item>
                <Stack direction="column" spacing={1} width="100%">
                  <Typography
                    variant="body2"
                    sx={{
                      color: "#222222",
                      fontFamily: themestyle.fontFamily.lato,
                      fontWeight: 500,
                      textAlign: "left",
                    }}
                  >
                    {TYPOGRAPHY_TEXT.EMAIL}
                  </Typography>
                  <IntelliwealthTextField
                    id="email"
                    type="text"
                    value={email}
                    placeholder="Enter your email"
                    onChange={handleEmailChange}
                    onFocus={handleEmailFocus}
                    onBlur={handleEmailBlur}
                    error={Boolean(emailErrorMessage)}
                    helperText={emailErrorMessage}
                    fullWidth
                    disabled
                    errorMessage={emailErrorMessage}
                    setErrorMessage={setEmailErrorMessage}
                  />
                </Stack>
              </Item>
              <Item>
                <Stack
                  direction={isMobile ? "column" : "row"}
                  spacing={isMobile ? 0 : 1}
                  width="100%"
                >
                  <Stack
                    direction="column"
                    spacing={1}
                    sx={{ flex: 1, marginBottom: isMobile ? "12px" : 0 }}
                  >
                    <Typography
                      variant="body2"
                      sx={{
                        color: "#222222",
                        fontFamily: themestyle.fontFamily.lato,
                        fontWeight: 500,
                        textAlign: "left",
                      }}
                    >
                      {TYPOGRAPHY_TEXT.FIRST_NAME}
                    </Typography>
                    <IntelliwealthTextField
                      id="first-name"
                      type="text"
                      value={firstName}
                      placeholder="Enter your first name"
                      onChange={handleFirstNameChange}
                      onFocus={handleFirstNameFocus}
                      onBlur={handleFirstNameBlur}
                      error={Boolean(firstNameErrorMessage)}
                      helperText={firstNameErrorMessage}
                      fullWidth
                      errorMessage={firstNameErrorMessage}
                      setErrorMessage={setFirstNameErrorMessage}
                    />
                  </Stack>
                  <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
                    <Typography
                      variant="body2"
                      sx={{
                        color: "#222222",
                        fontFamily: themestyle.fontFamily.lato,
                        fontWeight: 500,
                        textAlign: "left",
                      }}
                    >
                      {TYPOGRAPHY_TEXT.LAST_NAME}
                    </Typography>
                    <IntelliwealthTextField
                      id="last-name"
                      type="text"
                      value={lastName}
                      placeholder="Enter your last name"
                      onChange={handleLastNameChange}
                      onFocus={handleLastNameFocus}
                      onBlur={handleLastNameBlur}
                      error={Boolean(lastNameErrorMessage)}
                      helperText={lastNameErrorMessage}
                      fullWidth
                      errorMessage={lastNameErrorMessage}
                      setErrorMessage={setLastNameErrorMessage}
                    />
                  </Stack>
                </Stack>
              </Item>
              <Item>
                <Stack
                  direction={isMobile ? "column" : "row"}
                  spacing={isMobile ? 0 : 1}
                  width="100%"
                >
                  <Stack
                    direction="column"
                    spacing={1}
                    sx={{ flex: 1, marginBottom: isMobile ? "12px" : 0 }}
                  >
                    <Typography
                      variant="body2"
                      sx={{
                        color: "#222222",
                        fontFamily: themestyle.fontFamily.lato,
                        fontWeight: 500,
                        textAlign: "left",
                      }}
                    >
                      {TYPOGRAPHY_TEXT.COMPANY_NAME}
                    </Typography>
                    <IntelliwealthTextField
                      id="company-name"
                      type="text"
                      value={companyName}
                      placeholder="Enter your company name"
                      onChange={handleCompanyNameChange}
                      onFocus={handleCompanyNameFocus}
                      onBlur={handleCompanyNameBlur}
                      error={Boolean(companyNameErrorMessage)}
                      helperText={companyNameErrorMessage}
                      fullWidth
                      errorMessage={companyNameErrorMessage}
                      setErrorMessage={setCompanyNameErrorMessage}
                    />
                  </Stack>
                  <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
                    <Typography
                      variant="body2"
                      sx={{
                        color: "#222222",
                        fontFamily: themestyle.fontFamily.lato,
                        fontWeight: 500,
                        textAlign: "left",
                      }}
                    >
                      {TYPOGRAPHY_TEXT.PHONE}
                    </Typography>
                    <IntelliwealthTextField
                      id="phone-number"
                      type="text"
                      value={phoneNumber}
                      placeholder="Enter your phone number"
                      onChange={handlePhoneNumberChange}
                      onFocus={handlePhoneNumberFocus}
                      onBlur={handlePhoneNumberBlur}
                      error={Boolean(phoneNumberErrorMessage)}
                      helperText={phoneNumberErrorMessage}
                      fullWidth
                      errorMessage={phoneNumberErrorMessage}
                      setErrorMessage={setPhoneNumberErrorMessage}
                    />
                  </Stack>
                </Stack>
              </Item>
              <Item>
                <Stack direction="column" spacing={1} width="100%">
                  <Typography
                    variant="body2"
                    sx={{
                      color: "#222222",
                      fontFamily: themestyle.fontFamily.lato,
                      fontWeight: 500,
                      textAlign: "left",
                    }}
                  >
                    {TYPOGRAPHY_TEXT.ADDRESS}
                  </Typography>
                  <TextField
                    id="address"
                    type="text"
                    value={address}
                    placeholder="Enter your address"
                    onChange={handleAddressChange}
                    onFocus={handleAddressFocus}
                    onBlur={handleAddressBlur}
                    error={Boolean(addressErrorMessage)}
                    helperText={addressErrorMessage}
                    fullWidth
                    multiline
                    rows={3}
                    sx={{
                      "& .MuiOutlinedInput-root": { borderRadius: "8px" },
                      "& .MuiInputLabel-root": { fontSize: "14px" },
                      "& .MuiInputBase-input": { fontSize: "14px" },
                    }}
                  />
                </Stack>
              </Item>
              <Item>
                <Stack
                  direction={isMobile ? "column" : "row"}
                  spacing={isMobile ? 0 : 1}
                  width="100%"
                >
                  <Stack
                    direction="column"
                    spacing={1}
                    sx={{ flex: 1, marginBottom: isMobile ? "12px" : 0 }}
                  >
                    <Typography
                      variant="body2"
                      sx={{
                        color: "#222222",
                        fontFamily: themestyle.fontFamily.lato,
                        fontWeight: 500,
                        textAlign: "left",
                      }}
                    >
                      {TYPOGRAPHY_TEXT.COUNTRY}
                    </Typography>
                    <CountrySelect
                      value={country?.name || ""}
                      onChange={handleCountrySelectChange}
                      placeHolder="Select Country"
                      showFlag={true}
                      inputClassName={
                        countryErrorMessage ? "rsc-input-error" : "rsc-input"
                      }
                    />
                    {countryErrorMessage && (
                      <Typography
                        variant="caption"
                        color="error"
                        sx={{ display: "block", mt: 0.5, ml: 1.5 }}
                      >
                        {countryErrorMessage}
                      </Typography>
                    )}
                  </Stack>
                  <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
                    <Typography
                      variant="body2"
                      sx={{
                        color: "#222222",
                        fontFamily: themestyle.fontFamily.lato,
                        fontWeight: 500,
                        textAlign: "left",
                      }}
                    >
                      {TYPOGRAPHY_TEXT.POSTCODE}
                    </Typography>
                    <IntelliwealthTextField
                      id="pincode"
                      type="text"
                      value={pincode}
                      placeholder="Enter your pincode"
                      onChange={handlePincodeChange}
                      onFocus={handlePincodeFocus}
                      onBlur={handlePincodeBlur}
                      error={Boolean(pincodeErrorMessage)}
                      helperText={pincodeErrorMessage}
                      fullWidth
                      errorMessage={pincodeErrorMessage}
                      setErrorMessage={setPincodeErrorMessage}
                    />
                  </Stack>
                </Stack>
              </Item>
              <Item>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={handleSubmit}
                  disabled={isSubmitButtonDisabled || updateLoading}
                  fullWidth
                  sx={{
                    padding: isMobile ? "8px" : "10px",
                    fontSize: isMobile ? "14px" : "16px",
                    transform: "none",
                    bgcolor: themestyle.colors.primary,
                    textTransform: "none",
                  }}
                >
                  {updateLoading ? "Updating..." : TEXT.SUBMIT}
                </Button>
              </Item>
            </Box>
          </Stack>
        </Paper>
      </Container>
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={2000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
        sx={{
          "& .MuiSnackbarContent-root": {
            borderRadius: "8px",
            backgroundColor: "#f5f5f5",
          },
        }}
      >
        <Alert
          onClose={handleSnackbarClose}
          severity={snackbarSeverity}
          sx={{
            width: isMobile ? "90%" : "100%",
            fontSize: isMobile ? "14px" : "16px",
          }}
          action={
            <IconButton
              size="small"
              aria-label="close"
              color="inherit"
              onClick={handleSnackbarClose}
            >
              <CloseIcon fontSize="small" />
            </IconButton>
          }
        >
          {successMessage ||
            emailErrorMessage ||
            firstNameErrorMessage ||
            lastNameErrorMessage ||
            countryErrorMessage ||
            phoneNumberErrorMessage ||
            companyNameErrorMessage ||
            addressErrorMessage ||
            pincodeErrorMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default ClientOnBoard;
