import { useEffect, useState, lazy } from 'react';

// material-ui
import {
  Button,
  FormHelperText,
  Grid,
  IconButton,
  InputLabel,
  OutlinedInput,
  Stack,
  Typography,
  FormGroup,
  TextField,
  Checkbox
} from '@mui/material';
import Autocomplete from "@mui/material/Autocomplete";

// third party
import { useFormik, FormikProvider } from 'formik';
import * as yup from 'yup';

import axios from "axios";
import { POST_IAMSMART_USER_REGISTER, POST_CAPTCHA, POST_USER_EMAIL } from "utils/ApiPathConst";

import * as ComboData from "utils/ComboData";

import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));

import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
import CancelOutlinedIcon from '@mui/icons-material/CancelOutlined';
import iAmSmartICon from 'assets/images/icons/icon_iAmSmart.png';
import { EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';

import { Link, useLocation } from 'react-router-dom';
import * as HttpUtils from "../../../utils/HttpUtils";
import LoopIcon from '@mui/icons-material/Loop';
import { useTheme } from '@mui/material/styles';
import { FormattedMessage, useIntl } from "react-intl";

const IAmSmartFormWizard = (props) => {
  const location = useLocation();
  const theme = useTheme();
  const intl = useIntl();
  const { locale } = intl;

  const [iAmSmartData, setIAmSmartData] = useState({});

  const [checkUpload, setCheckUpload] = useState(false);
  const [isLoading, setLoding] = useState(true);
  const [isLoadingData, setLodingData] = useState(true);

  const [captchaImg, setCaptchaImage] = useState("");
  const [base64Url, setBase64Url] = useState("");
  const [checkCode, setCheckCode] = useState("");

  const [selectedAddress4, setSelectedAddress4] = useState(null);
  const [selectedAddress5, setSelectedAddress5] = useState(ComboData.country[0]); // usually hongKong
  const [termsAndConAccept, setTermsAndConAccept] = useState(false);
  const [termsAndConNotAccept, setTermsAndConNotAccept] = useState(false);

  const [isValid, setisValid] = useState(false);

  const [checkCountry, setCheckCountry] = useState(false);

  // email duplication
  const [checkEmail, setCheckEmail] = useState(false);

  // district validation UI
  const [checkDistrict, setCheckDistrict] = useState(false);
  const [districtErrStr, setDistrictErrStr] = useState("");

  const [showId, setshowId] = useState(false);
  const [showComId, setshowComId] = useState(false);

  const address4ComboList = ComboData.district;
  const address5ComboList = ComboData.country;

  const handleClickShowId = () => setshowId(!showId);
  const handleMouseDownId = (event) => event.preventDefault();

  const handleClickShowComId = () => setshowComId(!showComId);
  const handleMouseDownComId = (event) => event.preventDefault();

  // ===== Helpers =====
  function displayErrorMsg(errorMsg) {
    return <Typography variant="errorMessage1">{errorMsg}</Typography>;
  }

  function getRequiredErrStr(fieldname) {
    return displayErrorMsg(
      intl.formatMessage(
        { id: 'require' },
        { fieldname: fieldname ? intl.formatMessage({ id: fieldname }) : "" }
      )
    );
  }

  function getMaxErrStr(num, fieldname) {
    return displayErrorMsg(
      intl.formatMessage(
        { id: 'noMoreThenNWords' },
        { num: num, fieldname: fieldname ? intl.formatMessage({ id: fieldname }) + ": " : "" }
      )
    );
  }

  function handlePhone(phone) {
    return (phone || "").length >= 8;
  }

  function handleCaptcha(captchaField) {
    return (captchaField || "").length === 5;
  }

  function handleEmail(email) {
    const validRegex =
      /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
    return !!email?.match(validRegex);
  }

  // ===== District validation (FIX #1) =====
  const isDistrictRequired = () => selectedAddress5?.type === "hongKong";

  const validateDistrict = () => {
    setDistrictErrStr("");

    if (!isDistrictRequired()) {
      setCheckDistrict(false);
      return true;
    }

    const ok = !!selectedAddress4?.type;
    setCheckDistrict(!ok);
    setDistrictErrStr(ok ? "" : getRequiredErrStr("district"));
    return ok;
  };

  // Run district validation whenever district/country changes
  useEffect(() => {
    validateDistrict();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedAddress4, selectedAddress5]);

  // ===== Email duplication check (FIX #2) =====
  const checkEmailDuplicate = async (email) => {
    const value = (email || "").trim();
    if (!value) return false;
    if (!handleEmail(value)) return false;

    try {
      const response = await axios.post(`${POST_USER_EMAIL}`, { e1: value });
      return Number(response.data?.[0]) === 1;
    } catch (e) {
      // choose: do not block if API fails (keeps old behavior)
      return false;
    }
  };

  // ===== Captcha =====
  const onCaptchaChange = () => {
    HttpUtils.post({
      url: POST_CAPTCHA,
      params: { width: 130, height: 40, captcha: captchaImg },
      onSuccess: (responseData) => {
        props.setBase64Url(responseData.base64Url);
        setBase64Url(responseData.base64Url);
        localStorage.setItem("base64Url", responseData.base64Url);
        setCaptchaImage(localStorage.getItem('base64Url'));
      }
    });
  };

  // ===== iAM Smart data mapping =====
  const getAddressStr = (strs) => {
    let add = "";
    strs.forEach(str => {
      add += str?.trim() ? str.trim() + ", " : "";
    });
    add = add.trim();
    if (add?.slice(-1) === ",") add = add.substring(0, add.length - 1);
    return add;
  };

  const getAddressEng = (pAdd) => {
    let unit = (pAdd.Eng3dAddress?.EngUnit?.UnitDescriptor ?? "") + " " + (pAdd.Eng3dAddress?.EngUnit?.UnitNo ?? "");
    let block = (pAdd.EngBlock?.BlockDescriptor ?? "") + " " + (pAdd.EngBlock?.BlockNo ?? "");
    let floor = pAdd.Eng3dAddress?.EngFloor?.FloorNum ? pAdd.Eng3dAddress?.EngFloor?.FloorNum + "/F " : "";
    let street = (pAdd.EngStreet?.StreetName ?? "") + " " + (pAdd.EngStreet?.BuildingNoFrom ?? "");
    let buildingName = pAdd.BuildingName ?? "";
    let estate = pAdd.EngEstate?.EstateName ?? "";
    // NOTE: your original key had weird spacing; keep safe access
    let district = pAdd.EngDistrict?.["Sub - district"] ?? pAdd.EngDistrict?.["Sub-district"] ?? "";
    return getAddressStr([unit, block, floor, buildingName, estate, street, district]);
  };

  const getAddressChi = (pAdd) => {
    let unit = (pAdd.Chi3dAddress?.ChiUnit?.UnitDescriptor ?? "") + " " + (pAdd.Chi3dAddress?.ChiUnit?.UnitNo ?? "");
    let block = (pAdd.ChiBlock?.BlockDescriptor ?? "") + " " + (pAdd.ChiBlock?.BlockNo ?? "");
    let floor = pAdd.Chi3dAddress?.ChiFloor?.FloorNum ? pAdd.Chi3dAddress?.ChiFloor?.FloorNum + "樓 " : "";
    let street = (pAdd.ChiStreet?.StreetName ?? "") + " " + (pAdd.ChiStreet?.BuildingNoFrom ?? "");
    let buildingName = pAdd.BuildingName ?? "";
    let estate = pAdd.ChiEstate?.EstateName ?? "";
    let district = pAdd.ChiDistrict?.["Sub - district"] ?? pAdd.ChiDistrict?.["Sub-district"] ?? "";
    return getAddressStr([district, street, estate, buildingName, floor, block, unit]);
  };

  const responseToData = () => {
    const raw = location.state?.responseData?.data;
    if (!raw) return;

    let rd;
    try {
      rd = JSON.parse(raw);
    } catch (e) {
      return;
    }

    let data = {
      enName: rd?.enName?.UnstructuredName ?? "",
      chName: rd?.chName?.ChineseName ?? "",
      idNo: rd?.idNo?.Identification ?? "",
      checkDigit: rd?.idNo?.CheckDigit ?? "",
      email: rd?.emailAddress ?? "",
      phone: rd?.mobileNumber?.SubscriberNumber ?? "",
      phoneCountryCode: rd?.mobileNumber?.CountryCode ?? "",
      address1: ""
    };

    if (rd?.postalAddress) {
      if (rd?.postalAddress?.EngPremisesAddress) {
        data.address1 = getAddressEng(rd?.postalAddress?.EngPremisesAddress);
      } else if (rd?.postalAddress?.ChiPremisesAddress) {
        data.address1 = getAddressChi(rd?.postalAddress?.ChiPremisesAddress);
      }
    } else if (rd?.residentialAddress) {
      if (rd?.residentialAddress?.EngPremisesAddress) {
        data.address1 = getAddressEng(rd?.residentialAddress?.EngPremisesAddress);
      } else if (rd?.residentialAddress?.ChiPremisesAddress) {
        data.address1 = getAddressChi(rd?.residentialAddress?.ChiPremisesAddress);
      }
    }

    setIAmSmartData(data);
  };

  useEffect(() => {
    // redirect if no iAM Smart response
    location.state?.responseData ?? window.location.assign("/login");

    if (!captchaImg) onCaptchaChange();
    responseToData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ===== Formik =====
  const formik = useFormik({
    initialValues: {
      email: iAmSmartData.email ?? "",
      emailConfirm: iAmSmartData.email ?? "",
      address1: iAmSmartData.address1 ?? "",
      address2: '',
      address3: '',
      phone: iAmSmartData.phone ?? "",
      phoneCountryCode: iAmSmartData.phoneCountryCode ?? "852",
      submit: null,
      fax: '',
      faxCountryCode: '852',
      captchaField: ''
    },
    validationSchema: yup.object().shape({
      address1: yup.string().max(40, getMaxErrStr(40)).required(displayErrorMsg(intl.formatMessage({ id: 'validateAddressLine1' }))),
      address2: yup.string().max(40),
      address3: yup.string().max(40),
      email: yup.string().email(displayErrorMsg(intl.formatMessage({ id: 'validEmailFormat' }))).max(128, getMaxErrStr(128)).required(displayErrorMsg(intl.formatMessage({ id: 'requireEmail' }))),
      emailConfirm: yup.string().email(displayErrorMsg(intl.formatMessage({ id: 'validEmailFormat' }))).max(128, getMaxErrStr(128))
        .required(displayErrorMsg(intl.formatMessage({ id: 'requireEmail' })))
        .oneOf([yup.ref('email'), null], displayErrorMsg(intl.formatMessage({ id: 'validSameEmail' }))),
      phoneCountryCode: yup.string().min(2, displayErrorMsg(intl.formatMessage({ id: 'requireAtLeast2Number' }))).required(displayErrorMsg(intl.formatMessage({ id: 'requireDialingCode' }))),
      phone: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'requireAtLeast8Number' }))).required(displayErrorMsg(intl.formatMessage({ id: 'requireContactNumber' }))),
      captchaField: yup.string().max(5, getMaxErrStr(5)).required(displayErrorMsg(intl.formatMessage({ id: 'requireVerify' }))).min(5, displayErrorMsg(intl.formatMessage({ id: 'requireVerify' })))
    })
  });

  const { values } = formik;

  // Apply iAM Smart data to form
  useEffect(() => {
    if (iAmSmartData) {
      formik.setFieldValue("enName", iAmSmartData.enName ?? "");
      formik.setFieldValue("chName", iAmSmartData.chName ?? "");
      formik.setFieldValue("idNo", iAmSmartData.idNo ?? "");
      formik.setFieldValue("checkDigit", iAmSmartData.checkDigit ?? "");
      formik.setFieldValue("email", iAmSmartData.email ?? "");
      formik.setFieldValue("emailConfirm", iAmSmartData.email ?? "");
      formik.setFieldValue("phone", iAmSmartData.phone ?? "");
      formik.setFieldValue("phoneCountryCode", iAmSmartData.phoneCountryCode ?? "");
      formik.setFieldValue("address1", iAmSmartData.address1 ?? "");

      props.setIdNo(iAmSmartData.idNo ?? "");
      setLodingData(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [iAmSmartData]);

  // ===== Validity check (FIX #3: no stale return) =====
  const checkDataField = (data) => {
    const ok =
      data.address1 !== "" &&
      data.email !== "" &&
      data.emailConfirm !== "" &&
      data.email === data.emailConfirm &&
      data.phone !== "" &&
      data.phoneCountryCode !== "" &&
      termsAndConAccept === true &&
      handleEmail(data.email) &&
      handlePhone(data.phone) &&
      handleCaptcha(data.captchaField) &&
      validateDistrict() &&
      !checkEmail &&
      !checkDistrict;

    setisValid(ok);
    return ok;
  };

  // keep parent updated
  useEffect(() => {
    props.setUpdateValid(isValid);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isValid]);

  // re-check on relevant changes
  useEffect(() => {
    checkDataField(values);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [values, selectedAddress4, selectedAddress5, termsAndConAccept, termsAndConNotAccept, checkEmail, checkDistrict]);

  const handleCheckBoxChange = (event) => {
    if (event.target.name === 'termsAndConAccept') {
      setTermsAndConAccept(event.target.checked);
      setTermsAndConNotAccept(!event.target.checked);
    }
    if (event.target.name === 'termsAndConNotAccept') {
      setTermsAndConNotAccept(event.target.checked);
      setTermsAndConAccept(!event.target.checked);
    }
  };

  // ===== Submit (FIX #4: force email + district validation before posting) =====
  const _onSubmit = async () => {
    setLoding(true);

    // force sync validations
    const districtOk = validateDistrict();

    // force email dup check even if user never blurred
    const duplicated = await checkEmailDuplicate(values.email);
    setCheckEmail(duplicated);

    // recompute validity using latest flags
    const okNow = checkDataField(values) && districtOk && !duplicated;

    if (!okNow) {
      setLoding(false);
      return;
    }

    const userAddress = {
      addressLine1: values.address1,
      addressLine2: values.address2,
      addressLine3: values.address3,
      district: selectedAddress4?.type ? selectedAddress4.type : "",
      country: selectedAddress5?.type ? selectedAddress5.type : ""
    };

    const userFaxNo = {
      countryCode: values.faxCountryCode,
      faxNumber: values.fax
    };

    const userMobileNumber = {
      countryCode: values.phoneCountryCode,
      phoneNumber: values.phone
    };

    const tncFlag = termsAndConAccept ? true : false;

    const preferLocale = locale === 'en' ? 'en' : locale === 'zh-HK' ? 'zh_HK' : 'zh-CN';

    const formData = {
      enName: iAmSmartData.enName,
      chName: iAmSmartData.chName,
      emailAddress: values.email,
      idDocType: "HKID",
      identification: iAmSmartData.idNo,
      checkDigit: iAmSmartData.checkDigit,
      tncFlag: tncFlag,
      type: "IND",
      userFaxNo: JSON.stringify(userFaxNo),
      userMobileNumber: JSON.stringify(userMobileNumber),
      userAddress: JSON.stringify(userAddress),
      captcha: base64Url,
      checkCode: checkCode,
      preferLocale: preferLocale
    };

    try {
      await axios.post(POST_IAMSMART_USER_REGISTER, formData, {
        headers: { "Content-Type": "multipart/form-data" }
      });
      setCheckUpload(true);
    } catch (error) {
      console.error(error);
      setCheckUpload(false);
    } finally {
      setLoding(false);
    }
  };

  // Auto-submit when step reaches 2 (existing behavior)
  useEffect(() => {
    if (props.step === 2) {
      _onSubmit();
    }
    if (!captchaImg) onCaptchaChange();
    checkDataField(values);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [props.step]);

  const handleCCPChange = (e) => e.preventDefault();

  return (
    isLoadingData ? (
      <LoadingComponent />
    ) : (
      <FormikProvider value={formik}>
        <form onSubmit={(e) => e.preventDefault()}>
          {/* Input Form */}
          <FormGroup id={"inputForm"} sx={{ display: props.step === 0 ? "" : "none" }}>
            <Grid container spacing={3}>
              <Grid item xs={12} md={12}>
                <Stack direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                  <div style={{ borderBottom: "3px solid #1A4399", width: "100%", margin_right: "15px" }}>
                    <Typography display="inline" variant="h3" sx={{ color: '#1A4399' }}>
                      <FormattedMessage id="becomeNewPersonalUser" />
                    </Typography>
                  </div>

                  <Typography mt={0.25} variant="h6" sx={{ color: '#f10000' }}>
                    <FormattedMessage id="requireString" />。
                  </Typography>
                  <Stack mt={1} direction="row" style={{ alignItems: "center" }}>
                    <img src={iAmSmartICon} alt="iAM Smart" width="25" />
                    <Typography mt={0.25} variant="h6">
                      : <FormattedMessage id="MSG.providedByIAmSmart" />
                    </Typography>
                  </Stack>
                </Stack>
              </Grid>

              <Grid item xs={12} md={12}>
                <Grid container spacing={1}>
                  <Grid item xs={12} mt={1} mb={1}>
                    <Stack direction="column" justifyContent="space-between" alignItems="baseline">
                      <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                        <FormattedMessage id="yourPersonalInformation" />
                      </Typography>
                    </Stack>
                  </Grid>

                  <Grid item xs={12} md={12}>
                    <Grid container sx={{ mb: 1 }}>
                      <InputLabel htmlFor="idDocType-signup">
                        <Typography variant="h5" sx={{ mr: 1 }}>
                          <FormattedMessage id="HKIDcard" />:{" "}
                          {iAmSmartData.idNo ? <img src={iAmSmartICon} alt="iAM Smart" width="25" /> : null}
                        </Typography>

                        <Stack direction="row">
                          <Typography variant="h5">
                            {iAmSmartData?.idNo?.slice(0, 4)}
                            {showId ? iAmSmartData?.idNo?.slice(4) : "****"}
                            {showId ? '(' + iAmSmartData.checkDigit + ')' : null}
                          </Typography>
                          <IconButton
                            aria-label="toggle id visibility"
                            onClick={handleClickShowId}
                            onMouseDown={handleMouseDownId}
                            edge="end"
                            size="medium"
                          >
                            {showId ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                          </IconButton>
                        </Stack>
                      </InputLabel>
                    </Grid>
                  </Grid>

                  <Grid item xs={12} md={6}>
                    <Stack spacing={1}>
                      <InputLabel htmlFor="enName-signup">
                        <Typography variant="h5">
                          <FormattedMessage id="userEnglishName" />: {iAmSmartData.enName}
                          {iAmSmartData.enName ? <img src={iAmSmartICon} alt="iAM Smart" width="25" /> : null}
                        </Typography>
                      </InputLabel>
                    </Stack>
                  </Grid>

                  <Grid item xs={12} md={6}>
                    <Stack spacing={1}>
                      <InputLabel htmlFor="chName-signup">
                        <Typography variant="h5">
                          {intl.formatMessage({ id: 'userChineseName' })}: {iAmSmartData.chName}
                          {iAmSmartData.chName ? <img src={iAmSmartICon} alt="iAM Smart" width="25" /> : null}
                        </Typography>
                      </InputLabel>
                    </Stack>
                  </Grid>

                  <Grid item xs={12}>
                    <Stack spacing={1}>
                      <InputLabel htmlFor="address1-signup">
                        <Typography variant="h5">
                          <FormattedMessage id="formAddress" />
                          <span style={{ color: '#f10000' }}>*</span>
                        </Typography>
                      </InputLabel>

                      <Stack direction="row" justifyContent="space-between" alignItems="baseline">
                        <OutlinedInput
                          fullWidth
                          autoFocus
                          error={Boolean(formik.touched.address1 && formik.errors.address1)}
                          id="address1-signup"
                          value={formik.values.address1}
                          name="address1"
                          onChange={formik.handleChange}
                          placeholder={intl.formatMessage({ id: 'addressLine1' })}
                          onBlur={formik.handleBlur}
                          inputProps={{
                            onKeyDown: (e) => {
                              if (e.key === 'Enter') e.preventDefault();
                            }
                          }}
                        />
                        {iAmSmartData.address1 !== "" && iAmSmartData.address1 === formik.values.address1
                          ? <img src={iAmSmartICon} alt="iAM Smart" width="25" />
                          : null}
                      </Stack>

                      <Stack direction="row" justifyContent="space-between" alignItems="baseline">
                        <OutlinedInput
                          fullWidth
                          error={Boolean(formik.touched.address2 && formik.errors.address2)}
                          id="address2-signup"
                          value={formik.values.address2}
                          name="address2"
                          onBlur={formik.handleBlur}
                          onChange={formik.handleChange}
                          placeholder={intl.formatMessage({ id: 'addressLine2' })}
                          inputProps={{
                            onKeyDown: (e) => {
                              if (e.key === 'Enter') e.preventDefault();
                            }
                          }}
                        />
                      </Stack>

                      <Stack direction="row" justifyContent="space-between" alignItems="baseline">
                        <OutlinedInput
                          fullWidth
                          error={Boolean(formik.touched.address3 && formik.errors.address3)}
                          id="address3-signup"
                          value={formik.values.address3}
                          name="address3"
                          onBlur={formik.handleBlur}
                          onChange={formik.handleChange}
                          placeholder={intl.formatMessage({ id: 'addressLine3' })}
                          inputProps={{
                            onKeyDown: (e) => {
                              if (e.key === 'Enter') e.preventDefault();
                            }
                          }}
                        />
                      </Stack>

                      {/* District */}
                      <Autocomplete
                        disablePortal
                        id="address4-combo"
                        value={selectedAddress4}
                        options={address4ComboList}
                        disabled={checkCountry}
                        getOptionLabel={(option) => option.type ? intl.formatMessage({ id: option.type }) : ""}
                        onChange={(event, newValue) => {
                          setSelectedAddress4(newValue);
                        }}
                        onBlur={() => validateDistrict()}
                        sx={{
                          '& .MuiInputBase-root': { alignItems: 'center' },
                          '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                          '& .MuiOutlinedInput-root': { height: 40 }
                        }}
                        renderInput={(params) => (
                          <TextField
                            {...params}
                            error={checkDistrict}
                            placeholder={intl.formatMessage({ id: 'region' })}
                          />
                        )}
                      />

                      {/* Country */}
                      <Autocomplete
                        disablePortal
                        id="address5-combo"
                        value={selectedAddress5}
                        options={address5ComboList}
                        disabled={true}
                        getOptionLabel={(option) => option.type ? intl.formatMessage({ id: option.type }) : ""}
                        onChange={(event, newValue) => {
                          if (newValue !== null) {
                            setSelectedAddress5(newValue);
                            if (newValue.type === 'hongKong') {
                              setCheckCountry(false);
                            } else {
                              setSelectedAddress4(null);
                              setCheckCountry(true);
                            }
                          } else {
                            setSelectedAddress4(null);
                            setCheckCountry(true);
                          }
                        }}
                        sx={{
                          '& .MuiInputBase-root': { alignItems: 'center' },
                          '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                          '& .MuiOutlinedInput-root': { height: 40 }
                        }}
                        renderInput={(params) => (
                          <TextField {...params} placeholder={intl.formatMessage({ id: 'regionOrCountry' })} />
                        )}
                      />

                      {formik.touched.address1 && formik.errors.address1 && (
                        <FormHelperText error id="helper-text-address1-signup">
                          {formik.errors.address1}
                        </FormHelperText>
                      )}
                      {formik.touched.address2 && formik.errors.address2 && (
                        <FormHelperText error id="helper-text-address2-signup">
                          {formik.errors.address2}
                        </FormHelperText>
                      )}
                      {formik.touched.address3 && formik.errors.address3 && (
                        <FormHelperText error id="helper-text-address3-signup">
                          {formik.errors.address3}
                        </FormHelperText>
                      )}
                      {checkDistrict && (
                        <FormHelperText error>
                          {districtErrStr}
                        </FormHelperText>
                      )}
                    </Stack>
                  </Grid>

                  {/* Contact */}
                  <Grid item xs={12} mt={1} mb={1}>
                    <Stack direction="column" justifyContent="space-between" alignItems="baseline">
                      <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                        <FormattedMessage id="yourContact" />
                      </Typography>
                    </Stack>
                  </Grid>

                  <Grid item xs={12} md={12}>
                    <Grid container>
                      <Grid item xs={12} md={6}>
                        <Stack spacing={1} sx={{ mr: { md: 1 }, mb: 1 }}>
                          <InputLabel htmlFor="email-signup">
                            <Typography variant="h5">
                              <FormattedMessage id="userContactEmail" />
                              <span style={{ color: '#f10000' }}>*</span>
                            </Typography>
                          </InputLabel>

                          <Stack direction="row" justifyContent="space-between" alignItems="baseline">
                            <OutlinedInput
                              fullWidth
                              error={Boolean((formik.touched.email && formik.errors.email) || checkEmail)}
                              id="email-login"
                              type="email"
                              value={formik.values.email.trim()}
                              name="email"
                              onChange={(e) => {
                                setCheckEmail(false);
                                formik.handleChange(e);
                              }}
                              placeholder={intl.formatMessage({ id: 'userContactEmail' })}
                              onBlur={async (e) => {
                                formik.handleBlur(e);
                                const dup = await checkEmailDuplicate(formik.values.email);
                                setCheckEmail(dup);
                              }}
                              inputProps={{
                                onKeyDown: (e) => {
                                  if (e.key === 'Enter') e.preventDefault();
                                }
                              }}
                            />
                            {iAmSmartData.email && iAmSmartData.email === formik.values.email
                              ? <img src={iAmSmartICon} alt="iAM Smart" width="25" />
                              : null}
                          </Stack>

                          {formik.touched.email && formik.errors.email && (
                            <FormHelperText error id="helper-text-email-signup">
                              {formik.errors.email}
                            </FormHelperText>
                          )}
                          {checkEmail && (
                            <FormHelperText error id="helper-text-email-dup">
                              <FormattedMessage id="emailUsed" />
                            </FormHelperText>
                          )}
                        </Stack>
                      </Grid>

                      <Grid item xs={12} md={6}>
                        <Stack spacing={1}>
                          <InputLabel htmlFor="emailConfirm-signup">
                            <Typography variant="h5">
                              <FormattedMessage id="confirmEmail" />
                              <span style={{ color: '#f10000' }}>*</span>
                            </Typography>
                          </InputLabel>

                          <Stack direction="row" justifyContent="space-between" alignItems="baseline">
                            <OutlinedInput
                              fullWidth
                              error={Boolean(formik.touched.emailConfirm && formik.errors.emailConfirm)}
                              id="emailConfirm-login"
                              type="email"
                              value={formik.values.emailConfirm}
                              name="emailConfirm"
                              onChange={formik.handleChange}
                              placeholder={intl.formatMessage({ id: 'confirmEmail' })}
                              onBlur={formik.handleBlur}
                              onCut={handleCCPChange}
                              onCopy={handleCCPChange}
                              onPaste={handleCCPChange}
                              inputProps={{
                                onKeyDown: (e) => {
                                  if (e.key === 'Enter') e.preventDefault();
                                }
                              }}
                            />
                            {iAmSmartData.email && iAmSmartData.email === formik.values.emailConfirm
                              ? <img src={iAmSmartICon} alt="iAM Smart" width="25" />
                              : null}
                          </Stack>

                          {formik.touched.emailConfirm && formik.errors.emailConfirm && (
                            <FormHelperText error id="helper-text-emailConfirm-signup">
                              {formik.errors.emailConfirm}
                            </FormHelperText>
                          )}
                        </Stack>
                      </Grid>
                    </Grid>
                  </Grid>

                  {/* Phone/Fax */}
                  <Grid item xs={12} md={12}>
                    <Grid container>
                      <Grid item xs={12} md={6}>
                        <Stack direction="column" spacing={1} sx={{ mr: { md: 1 }, mb: 1 }}>
                          <InputLabel htmlFor="phone-signup">
                            <Typography variant="h5">
                              <FormattedMessage id="userContactNumber" />
                              <span style={{ color: '#f10000' }}>*</span>
                            </Typography>
                          </InputLabel>

                          <Stack direction="row" alignItems="baseline">
                            <OutlinedInput
                              id="phoneCountryCode-login"
                              type="text"
                              value={formik.values.phoneCountryCode.trim()}
                              name="phoneCountryCode"
                              onChange={(event) => {
                                const value = event.target.value;
                                if (value.match(/[^0-9]/)) return event.preventDefault();
                                formik.setFieldValue("phoneCountryCode", value);
                              }}
                              placeholder={intl.formatMessage({ id: 'dialingCode' })}
                              error={Boolean(formik.touched.phone && formik.errors.phone)}
                              onBlur={formik.handleBlur}
                              inputProps={{
                                maxLength: 3,
                                onKeyDown: (e) => {
                                  if (e.key === 'Enter') e.preventDefault();
                                }
                              }}
                              sx={{ width: '25%' }}
                            />
                            <OutlinedInput
                              id="phone-login"
                              type="text"
                              value={formik.values.phone.trim()}
                              name="phone"
                              onChange={(event) => {
                                const value = event.target.value;
                                if (value.match(/[^0-9]/)) return event.preventDefault();
                                formik.setFieldValue("phone", value);
                              }}
                              placeholder={intl.formatMessage({ id: 'userContactNumber' })}
                              error={Boolean(formik.touched.phone && formik.errors.phone)}
                              onBlur={formik.handleBlur}
                              inputProps={{
                                maxLength: 11,
                                onKeyDown: (e) => {
                                  if (e.key === 'Enter') e.preventDefault();
                                }
                              }}
                              fullWidth
                            />
                            {iAmSmartData.phone && iAmSmartData.phone === formik.values.phone && iAmSmartData.phoneCountryCode === formik.values.phoneCountryCode
                              ? <img src={iAmSmartICon} alt="iAM Smart" width="25" />
                              : null}
                          </Stack>

                          {formik.touched.phone && formik.errors.phone && (
                            <FormHelperText error id="helper-text-phone-signup">
                              {formik.errors.phone}
                            </FormHelperText>
                          )}
                        </Stack>
                      </Grid>

                      <Grid item xs={12} md={6}>
                        <Stack spacing={1} direction="column">
                          <InputLabel htmlFor="fax-signup">
                            <Typography variant="h5">
                              <FormattedMessage id="userFaxNumber" />
                            </Typography>
                          </InputLabel>

                          <Stack direction="row" alignItems="baseline">
                            <OutlinedInput
                              error={Boolean(formik.touched.fax && formik.errors.fax)}
                              id="faxCountryCode-login"
                              type="text"
                              value={formik.values.faxCountryCode.trim()}
                              name="faxCountryCode"
                              onChange={(event) => {
                                const value = event.target.value;
                                if (value.match(/[^0-9]/)) return event.preventDefault();
                                formik.setFieldValue("faxCountryCode", value);
                              }}
                              placeholder={intl.formatMessage({ id: 'dialingCode' })}
                              onBlur={formik.handleBlur}
                              inputProps={{
                                maxLength: 3,
                                onKeyDown: (e) => {
                                  if (e.key === 'Enter') e.preventDefault();
                                }
                              }}
                              sx={{ width: '25%' }}
                            />
                            <OutlinedInput
                              id="fax-login"
                              type="text"
                              value={formik.values.fax.trim()}
                              name="fax"
                              onBlur={formik.handleBlur}
                              onChange={(event) => {
                                const value = event.target.value;
                                if (value.match(/[^0-9]/)) return event.preventDefault();
                                formik.setFieldValue("fax", value);
                              }}
                              placeholder={intl.formatMessage({ id: 'userFaxNumber' })}
                              inputProps={{
                                maxLength: 8,
                                onKeyDown: (e) => {
                                  if (e.key === 'Enter') e.preventDefault();
                                }
                              }}
                              sx={{ width: '75%' }}
                            />
                          </Stack>
                        </Stack>
                      </Grid>
                    </Grid>
                  </Grid>

                  {/* Terms */}
                  <Grid item xs={12} md={12}>
                    <Grid container>
                      <Grid item xs={12} md={12}>
                        <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                          <FormattedMessage id="termsAndCondition" />
                          <span style={{ color: '#f10000' }}>*</span>
                        </Typography>
                      </Grid>

                      <Grid item xs={12} md={12}>
                        <Typography variant="h5" sx={{ textAlign: "left", borderRadius: "inherit", borderStyle: "solid", borderWidth: "1px", borderColor: "#0C489E" }}>
                          <div style={{ padding: 12 }} dangerouslySetInnerHTML={{ __html: intl.formatMessage({ id: "termsAndCon" }) }} />
                        </Typography>

                        <Grid item xs={12} md={12}>
                          <Grid container>
                            <Grid item sx={{ display: 'flex', alignItems: 'center' }}>
                              <Checkbox
                                checked={termsAndConAccept}
                                onChange={handleCheckBoxChange}
                                name="termsAndConAccept"
                                color="primary"
                                size="small"
                              />
                              <Typography variant="h5">
                                <FormattedMessage id="iConfirm" />
                              </Typography>
                            </Grid>
                          </Grid>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Grid>

                  {/* Captcha */}
                  <Grid item xs={12} lg={12}>
                    <Grid container>
                      <Stack direction="column">
                        <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                          <FormattedMessage id="verify" />
                          <span style={{ color: '#f10000' }}>*</span>
                        </Typography>

                        <Stack spacing={1} direction="row">
                          <Grid item xs={5} lg={5} style={{ border: "1px solid black" }}>
                            <img src={captchaImg} alt="" />
                          </Grid>
                          <Grid item xs={1} lg={1}>
                            <IconButton aria-label="refrashCaptcha" size="large" onClick={() => { onCaptchaChange(); }}>
                              <LoopIcon fontSize="inherit" />
                            </IconButton>
                          </Grid>
                          <Grid item xs={6} lg={6}>
                            <OutlinedInput
                              fullWidth
                              id="captchaField"
                              type="text"
                              value={formik.values.captchaField.trim()}
                              onBlur={formik.handleBlur}
                              error={Boolean(formik.touched.captchaField && formik.errors.captchaField)}
                              name="captchaField"
                              onChange={(event) => {
                                const value = event.target.value;
                                props.setCheckCode(value);
                                setCheckCode(value);
                                formik.setFieldValue("captchaField", value);
                              }}
                              sx={{ width: '75%' }}
                            />
                          </Grid>
                        </Stack>

                        {formik.touched.captchaField && formik.errors.captchaField && (
                          <FormHelperText error id="helper-text-captcha-signup">
                            {formik.errors.captchaField}
                          </FormHelperText>
                        )}
                      </Stack>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </Grid>
          </FormGroup>

          {/* Preview Form */}
          <FormGroup id={"previewForm"} sx={{ display: props.step === 1 ? "" : "none" }}>
            <Grid container spacing={3}>
              <Grid item xs={12} md={12}>
                <Stack direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                  <div style={{ borderBottom: "3px solid #1A4399", width: "100%", margin_right: "15px" }}>
                    <Typography display="inline" variant="h3" sx={{ color: '#1A4399' }}>
                      <FormattedMessage id="becomeNewPersonalUser" />
                    </Typography>
                  </div>
                </Stack>
              </Grid>

              <Grid item xs={12} md={12}>
                <Grid container spacing={2}>
                  <Grid item xs={12} md={12}>
                    <Stack direction="row">
                      <Typography variant="h5" color={theme.palette.grey[600]} sx={{ mr: 1 }}>
                        <FormattedMessage id="userIdDoc" />
                      </Typography>
                      <Typography variant="h5">
                        {iAmSmartData?.idNo?.slice(0, 4)}
                      </Typography>
                      <Typography variant="h5">
                        {showComId ? iAmSmartData?.idNo?.slice(4) : "****"}
                        {showComId ? '(' + iAmSmartData.checkDigit + ')' : null}
                      </Typography>

                      <IconButton
                        aria-label="toggle id visibility"
                        onClick={handleClickShowComId}
                        onMouseDown={handleMouseDownComId}
                        edge="end"
                        size="medium"
                      >
                        {showComId ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                      </IconButton>
                    </Stack>
                  </Grid>

                  <Grid item xs={12} md={6}>
                    <Stack spacing={1} direction="row">
                      <Typography variant="h5" color={theme.palette.grey[600]}>
                        <FormattedMessage id="userEnglishName" />:
                      </Typography>
                      <Typography variant="h5">
                        {iAmSmartData.enName}
                      </Typography>
                      {iAmSmartData.enName ? <img src={iAmSmartICon} alt="iAM Smart" width="25" /> : null}
                    </Stack>
                  </Grid>

                  <Grid item xs={12} md={6}>
                    <Stack spacing={1} direction="row">
                      <Typography variant="h5" color={theme.palette.grey[600]}>
                        <FormattedMessage id="userChineseName" />:
                      </Typography>
                      <Typography variant="h5">
                        {iAmSmartData.chName}
                      </Typography>
                    </Stack>
                  </Grid>

                  <Grid item xs={12}>
                    <Stack spacing={1} direction="column">
                      <Typography variant="h5" color={theme.palette.grey[600]}>
                        <FormattedMessage id="formAddress" />:
                      </Typography>
                      <Stack spacing={1} direction="column">
                        <Typography variant="h5">{formik.values.address1}</Typography>
                        {formik.values.address2 ? <Typography variant="h5">{formik.values.address2}</Typography> : null}
                        {formik.values.address3 ? <Typography variant="h5">{formik.values.address3}</Typography> : null}

                        {selectedAddress5.type === "hongKong" ? (
                          <Typography variant="h5">
                            {!selectedAddress4 ? "" : intl.formatMessage({ id: selectedAddress4.type })}
                          </Typography>
                        ) : null}

                        <Typography variant="h5">
                          {intl.formatMessage({ id: selectedAddress5.type })}
                        </Typography>
                      </Stack>
                    </Stack>
                  </Grid>

                  <Grid item xs={12} mt={1} mb={1}>
                    <Stack direction="column" justifyContent="space-between" alignItems="baseline">
                      <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                        <FormattedMessage id="yourContact" />
                      </Typography>
                    </Stack>
                  </Grid>

                  <Grid item xs={12} md={12}>
                    <Stack spacing={1} direction="row">
                      <Typography variant="h5" color={theme.palette.grey[600]}>
                        <FormattedMessage id="userContactEmail" />:
                      </Typography>
                      <Typography variant="h5">{formik.values.email}</Typography>
                    </Stack>
                  </Grid>

                  <Grid item xs={12} md={6}>
                    <Stack spacing={1} direction="row">
                      <Typography variant="h5" color={theme.palette.grey[600]}>
                        <FormattedMessage id="userContactNumber" />:
                      </Typography>
                      <Typography variant="h5">
                        +{formik.values.phoneCountryCode} {formik.values.phone}
                      </Typography>
                    </Stack>
                  </Grid>

                  {formik.values.faxCountryCode && formik.values.fax ? (
                    <Grid item xs={12} md={6}>
                      <Stack spacing={1} direction="row">
                        <Typography variant="h5" color={theme.palette.grey[600]}>
                          <FormattedMessage id="userFaxNumber" />:
                        </Typography>
                        <Typography variant="h5">
                          +{formik.values.faxCountryCode} {formik.values.fax}
                        </Typography>
                      </Stack>
                    </Grid>
                  ) : null}
                </Grid>
              </Grid>
            </Grid>
          </FormGroup>

          {/* Submit page */}
          <FormGroup id={"submitForm"} sx={{ display: props.step === 2 ? "" : "none" }}>
            <Grid container spacing={3}>
              {isLoading ? (
                <LoadingComponent />
              ) : (
                <Grid item xs={12}>
                  {checkUpload ? (
                    <Stack mt={1} direction="column" justifyContent="flex-start" alignItems="center" spacing={2}>
                      <CheckCircleOutlineIcon color="success" sx={{ width: "200px", height: "200px" }} />
                      <Typography display="inline" variant="h4">
                        <FormattedMessage id="registerSubmitted" />
                      </Typography>
                      <Typography display="inline" variant="h4">
                        <FormattedMessage id="emailSent" />
                      </Typography>
                      <Button variant="outlined" component={Link} to="/login">
                        <Typography variant="h5">
                          <FormattedMessage id="backToLogin" />
                        </Typography>
                      </Button>
                    </Stack>
                  ) : (
                    <Stack mt={1} direction="column" justifyContent="flex-start" alignItems="center" spacing={2}>
                      <CancelOutlinedIcon color="error" sx={{ width: "200px", height: "200px" }} />
                      <Typography display="inline" variant="h4">
                        <FormattedMessage id="registerFail" />
                      </Typography>
                      <Button color="error" variant="outlined" component={Link} to="/login">
                        <Typography variant="h5">
                          <FormattedMessage id="backToLogin" />
                        </Typography>
                      </Button>
                    </Stack>
                  )}
                </Grid>
              )}
            </Grid>
          </FormGroup>
        </form>
      </FormikProvider>
    )
  );
};

export default IAmSmartFormWizard;
