// import { Link } from 'react-router-dom';
import React, {
  useState,
  useRef,
} from 'react';

// material-ui
import {
  Stepper,
  Step,
  StepButton,
  // Grid, 
  Stack,
  Typography,
  Button, StepLabel,
  CircularProgress,
} from '@mui/material';
import { POST_USERNAME, POST_VERIFY_CAPTCHA  } from "utils/ApiPathConst";
import RegisterStepIcon, { registerStepStyle } from 'components/RegisterStepIcon';

// project import
import Loadable from 'components/Loadable';
import { lazy } from 'react';
import { notifyActionError } from 'utils/CommonFunction';
import axios from "axios";
import {FormattedMessage, useIntl} from "react-intl";
import usePageTitle from "components/usePageTitle";
import { PRIMARY_CONTAINED_BUTTON_SX } from "themes/colorConst";
const CustomFormWizard = Loadable(lazy(() => import('./auth-forms/CustomFormWizard')));
const AuthWrapper = Loadable(lazy(() => import('./AuthWrapperCustom')));
// ================================|| REGISTER ||================================ //

const Register = () => {
  const [activeStep, setActiveStep] = useState(0);
  const [completed, setCompleted] = useState([false]);
  const [updateValid, setUpdateValid] = useState(false);
  const step0GuardRef = useRef(null);
  const [username, setUsername] = useState("");
  const [base64Url, setBase64Url] = useState("")
  const [checkCode, setCheckCode] = useState("")
  const [isNextBusy, setIsNextBusy] = useState(false);
  const [registrationComplete, setRegistrationComplete] = useState(false);
  const nextBusyRef = useRef(false);
  const intl = useIntl();
  // Localized document title/meta for register flow
  usePageTitle("register");
  const steps = [
    intl.formatMessage({id: 'personalInformation'}),
    intl.formatMessage({id: 'preview'}),
    intl.formatMessage({id: 'finishSubmission'})
  ];

  const totalSteps = () => {
    return steps.length;
  };

  const completedSteps = () => {
    return Object.keys(completed).length;
  };

  const isLastStep = () => {
    return activeStep === totalSteps() - 1;
  };

  const allStepsCompleted = () => {
    return completedSteps() === totalSteps();
  };

  const handleCheckUsername = async () => {
    const response = await axios.post(`${POST_USERNAME}`, {
      u1: username,
    })
    return Number(response.data[0]) > 0
  }

  const handleCaptcha = async () => {
    const response = await axios.post(`${POST_VERIFY_CAPTCHA}`, {
        captcha: base64Url,
        checkCode: checkCode,
    })
    return Boolean(response.data["success"]);
  }


  const handleNext = async () => {
    if (nextBusyRef.current) return;
    nextBusyRef.current = true;
    setIsNextBusy(true);
    try {
      if (activeStep === 0 && step0GuardRef.current) {
        const step0Ok = await Promise.resolve(step0GuardRef.current());
        if (!step0Ok) {
          return;
        }
      }

      const captchaTest = await handleCaptcha();
      if (!captchaTest) {
        notifyActionError(intl.formatMessage({id: 'validVerify'}))
        return;
      }

      const test = await handleCheckUsername()
      if (test) {
        notifyActionError(intl.formatMessage({id: 'usernameTaken'}))
      } else {
        const newActiveStep =
          isLastStep() && !allStepsCompleted()
            ? // It's the last step, but not all steps have been completed,
            // find the first step that has been completed
            steps.findIndex((step, i) => !(i in completed))
            : activeStep + 1;
        setActiveStep(newActiveStep);
        scrollToTop();
      }
    } finally {
      nextBusyRef.current = false;
      setIsNextBusy(false);
    }
  };

  const handleBack = () => {
    scrollToTop();
    setActiveStep((prevActiveStep) => prevActiveStep - 1);
  };

  const scrollToTop = () => {
    window.scrollTo(0, 0);
  };

  const handleReset = () => {
    setActiveStep(0);
    setCompleted({});
    setRegistrationComplete(false);
  };

  const isStepCompleted = (index) => index < activeStep || registrationComplete;

  return (
    // <AuthWrapper>
    <Stack sx={{ width: '100%', fontSize: '2rem', paddingTop: '35px', bgcolor: 'backgroundColor.default' }} alignItems="center">
      <Stepper activeStep={activeStep} sx={registerStepStyle}>
        {steps.map((label, index) => (
          <Step key={label} completed={isStepCompleted(index)} readOnly={true}>
            <StepButton
              aria-current={activeStep === index ? 'step' : undefined}
            >
              <StepLabel
                StepIconComponent={RegisterStepIcon}
                sx={{
                  flexDirection: 'column',
                  "& .MuiStepLabel-iconContainer": { paddingRight: 0 }
                }}
              >
                <Typography variant="step1">{label}</Typography>
              </StepLabel>
            </StepButton>
          </Step>
        ))}
      </Stepper>
      {allStepsCompleted() ? (
        <React.Fragment>
          <Typography component="span" variant="h4" sx={{ mt: 2, mb: 1, display: 'block' }}>
            All steps completed - you&apos;re finished
          </Typography>
          <Stack direction="row" sx={{ pt: 2 }}>
            <Stack sx={{ flex: '1 1 auto' }} />
            <Button onClick={handleReset}><Typography component="span" variant="h5">Reset</Typography></Button>
          </Stack>
        </React.Fragment>
      ) : (
        <React.Fragment>
          <AuthWrapper>
            <CustomFormWizard
              setUpdateValid={setUpdateValid}
              step0GuardRef={step0GuardRef}
              step={activeStep}
              setUsername={setUsername}
              setBase64Url={setBase64Url}
              setCheckCode={setCheckCode}
              onRegistrationComplete={() => setRegistrationComplete(true)}
            />
            {/* <CustomFormWizard step={activeStep} /> */}
          </AuthWrapper>
          <Stack direction="row" sx={{ pb: 2, mt:-4, mb:2 }}>
            {activeStep === 2 || activeStep === 0 ? (
              <Button
                color="inherit"
                disabled={true}
                onClick={handleBack}
                sx={{ mr: 1 }}
                variant="h5"
              >
                <Typography component="span" variant="h5">
                  <FormattedMessage id="back"/>
                </Typography>
              </Button>
            ) : (
              <Button
                color="inherit"
                disabled={activeStep === 0 || isNextBusy}
                onClick={handleBack}
                sx={{ mr: 1 }}
                variant="h5"
              >
                <Typography component="span" variant="h5">
                  <FormattedMessage id="back"/>
                </Typography>
              </Button>
            )
            }
            <Stack sx={{ flex: '1 1 auto' }} />
            {activeStep === totalSteps() - 2 ?
              (
                <Button
                  variant="contained"
                  disabled={isNextBusy}
                  onClick={handleNext}
                  aria-busy={isNextBusy}
                  sx={{ mr: 1, minWidth: 120, ...PRIMARY_CONTAINED_BUTTON_SX }}
                >
                  {isNextBusy ? (
                    <CircularProgress size={22} color="inherit" aria-hidden />
                  ) : (
                    <Typography component="span" variant="h5" sx={{ color: 'inherit' }}>
                      <FormattedMessage id="submit"/>
                    </Typography>
                  )}
                </Button>
              ) : (activeStep === totalSteps() - 1 ?
                (
                  <Button variant="contained" color="inherit"
                    disabled={true} sx={{ mr: 1, ...PRIMARY_CONTAINED_BUTTON_SX }}>
                    <Typography component="span" variant="h5" sx={{ color: 'inherit' }}>
                      <FormattedMessage id="submit"/>
                    </Typography>
                  </Button>
                ) :
                (
                  // <Button disabled={updateValid} variant="outlined" onClick={handleNext} sx={{ mr: 1 }}>
                  <Button disabled={!updateValid || isNextBusy} variant="contained" onClick={handleNext} sx={{ mr: 1, ...PRIMARY_CONTAINED_BUTTON_SX }}>
                    <Typography component="span" variant="h5" sx={{ color: 'inherit' }}>
                      <FormattedMessage id="continue"/>
                    </Typography>
                  </Button>
                )
              )}
            {/* {activeStep !== steps.length &&
                (completed[activeStep] ? (
                  <Typography variant="caption" sx={{ display: 'inline-block' }}>
                    Step {activeStep + 1} already completed
                  </Typography>
                ) : (
                  <Button onClick={handleComplete}>
                    {completedSteps() === totalSteps() - 1
                      ? 'Finish'
                      : 'Complete Step'}
                  </Button>
                ))} */}
          </Stack>
        </React.Fragment>
      )}
    </Stack >
    // </AuthWrapper>
  );
};

export default Register;
