// 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 VisibilityIcon from '@mui/icons-material/Visibility';

// project import
import Loadable from 'components/Loadable';
import { lazy } from 'react';
import { notifyActionError } from 'utils/CommonFunction';
const CustomFormWizard = Loadable(lazy(() => import('./auth-forms/BusCustomFormWizard')));
const AuthWrapper = Loadable(lazy(() => import('./AuthWrapperCustom')));
import axios from "axios";
import { POST_USERNAME, POST_VERIFY_CAPTCHA } from "utils/ApiPathConst";
import {FormattedMessage, useIntl} from "react-intl";
// import CustomFormWizard from './auth-forms/BusCustomFormWizard';
// import AuthWrapper from './AuthWrapperCustom';

// ================================|| REGISTER ||================================ //
const BusRegister = () => {
  const [activeStep, setActiveStep] = useState(0);
  const [completed, setCompleted] = useState([false]);
  const [updateValid, setUpdateValid] = useState(false);
  const step0GuardRef = useRef(null);
  const nextBusyRef = useRef(false);
  const [username, setUsername] = useState("")
  const [base64Url, setBase64Url] = useState("")
  const [checkCode, setCheckCode] = useState("")
  const [isNextBusy, setIsNextBusy] = useState(false);
  const intl = useIntl();
  const steps = [
    intl.formatMessage({id: 'personalInformation'}),
    intl.formatMessage({id: 'preview'}),
    intl.formatMessage({id: 'finishSubmission'})
  ];

  const stepStyle = {
    width: { lg: "40%", md: "70%", xs: "100%" },
    boxShadow: 1,
    backgroundColor: "#FFFFFF",
    padding: 2,

    /* Inactive (default) */
    "& .MuiStepIcon-root": { color: "#757575", fontSize: "2rem" },          // darker grey
    "& .MuiStepLabel-label": { color: "#424242" },                           // label darker
    "& .MuiStepConnector-line": { borderColor: "#9E9E9E" },                  // connector darker

    /* Active */
    "& .Mui-active": {
      "&.MuiStepIcon-root": { color: "warning.main", fontSize: "2rem" },
      "& .MuiStepConnector-line": { borderColor: "warning.main" }
    },

    /* Completed */
    "& .Mui-completed": {
      "&.MuiStepIcon-root": { color: "#0C489E", fontSize: "2rem" },           // use your strong blue
      "& .MuiStepConnector-line": { borderColor: "#0C489E" }
    }
  };

  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({});
  };

  return (
    // <AuthWrapper>
    <Stack sx={{ width: '100%', fontSize: '2rem', paddingTop: '35px', bgcolor: 'backgroundColor.default' }} alignItems="center">
      <Stepper activeStep={activeStep} sx={stepStyle}>
        {steps.map((label, index) => (
          <Step key={label} completed={completed[index]} readOnly={true}>
            {index < 2 ? (
              <StepButton
                aria-current={activeStep === index ? "step" : undefined}
                // onClick={handleStep(index)}
              >
                <StepLabel
                  sx={{
                    flexDirection: "column",
                    "& .MuiStepLabel-iconContainer": { paddingRight: 0 },
                  }}
                >
                  <Typography variant="step1">{label}</Typography>
                </StepLabel>
              </StepButton>
            ) : (
              <StepButton
                aria-current={activeStep === index ? "step" : undefined}
                sx={
                  activeStep === 2
                    ? { "& .MuiSvgIcon-root": { color: "warning.main", fontSize: "2rem" } }
                    : allStepsCompleted()
                      ? { "& .MuiSvgIcon-root": { color: "#0C489E", fontSize: "2rem" } }
                      : { color: "rgba(0,0,0,0.6)" }
                }
                icon={<VisibilityIcon />}
                // onClick={handleStep(index)}
              >
                <StepLabel
                  sx={{
                    flexDirection: "column",
                    "& .MuiStepLabel-iconContainer": { paddingRight: 0 },
                  }}
                >
                  <Typography variant="step1">{label}</Typography>
                </StepLabel>
              </StepButton>
            )}
          </Step>
        ))}
      </Stepper>
      {allStepsCompleted() ? (
        <React.Fragment>
          <Typography variant="h4" sx={{ mt: 2, mb: 1 }}>
            All steps completed - you&apos;re finished
          </Typography>
          <Stack direction="row" sx={{ pb: 2 }}>
            <Stack sx={{ flex: '1 1 auto' }} />
            <Button variant="h5" onClick={handleReset}>Reset</Button>
          </Stack>
        </React.Fragment>
      ) : (
        <React.Fragment>
          <AuthWrapper>
            <CustomFormWizard
              setUpdateValid={setUpdateValid}
              step0GuardRef={step0GuardRef}
              step={activeStep}
              setUsername={setUsername}
              setBase64Url={setBase64Url}
              setCheckCode={setCheckCode}
            />
            {/* <CustomFormWizard step={activeStep} /> */}
          </AuthWrapper>
          <Stack direction="row" sx={{ pb: 2, mt:-4, mb:2 }}>
            {activeStep === totalSteps() - 1 ? (
              <Button
                color="inherit"
                disabled={true}
                onClick={handleBack}
                sx={{ mr: 1 }}
                variant="h5"
              >
                <Typography variant="h5">
                  <FormattedMessage id="back"/>
                </Typography>
              </Button>
            ) : (
              <Button
                color="inherit"
                disabled={activeStep === 0 || isNextBusy}
                onClick={handleBack}
                sx={{ mr: 1 }}
                variant="h5"
              >
                <Typography variant="h5">
                  <FormattedMessage id="back"/>
                </Typography>
              </Button>
            )
            }
            <Stack sx={{ flex: '1 1 auto' }} />
            {activeStep === totalSteps() - 2 ?
              (
                <Button
                  variant="outlined"
                  disabled={isNextBusy}
                  onClick={handleNext}
                  aria-busy={isNextBusy}
                  sx={{ mr: 1, minWidth: 120 }}
                >
                  {isNextBusy ? (
                    <CircularProgress size={22} color="inherit" aria-hidden />
                  ) : (
                    <Typography variant="h5">
                      <FormattedMessage id="submit"/>
                    </Typography>
                  )}
                </Button>
              ) : (activeStep === totalSteps() - 1 ?
                (
                  <Button variant="outlined" color="inherit"
                    disabled={true} sx={{ mr: 1 }}>
                    <Typography variant="h5">
                      <FormattedMessage id="submit"/>
                    </Typography>
                  </Button>
                ) :
                (
                  // <Button disabled={updateValid} variant="outlined" onClick={handleNext} sx={{ mr: 1 }}>
                  <Button disabled={!updateValid || isNextBusy} variant="outlined" onClick={handleNext} sx={{ mr: 1 }}>
                    <Typography variant="h5">
                      <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 BusRegister;
