import { useState } from 'react';
import Box from '@mui/material/Box';
import Stepper from '@mui/material/Stepper';
import Step from '@mui/material/Step';
import StepLabel from '@mui/material/StepLabel';
import Button from '@mui/material/Button';
import Tooltip from '@mui/material/Tooltip';

export default function StepperWizard({ steps }) {
  const [filters, setFilters] = useState({});
  const [activeStep, setActiveStep] = useState(0);
  const [nextDisabled, setNextDisabled] = useState(true);
  const [redirectBack, setRedirectBack] = useState(false);

  const resetStepState = () => {
    setNextDisabled(true);
    setRedirectBack(false);
  }

  const handleNext = () => {
    if (redirectBack) {
      setActiveStep((prevActiveStep) => prevActiveStep - 1);
    } else {
      setActiveStep((prevActiveStep) => prevActiveStep + 1);
    }
    resetStepState();
  };

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

  const handleReset = () => {
    setActiveStep(0);
    resetStepState();
    setFilters({});
  };

  const updateFilterState = (newFilters) => {
    setFilters(f => ({...f, ...newFilters}));
  };

  let CurrentStep = activeStep >= steps.length ? steps[steps.length - 1].component : steps[activeStep].component;

  return (
    <Box sx={{ width: '100%', height: '100%', display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <Stepper activeStep={activeStep} sx={{ paddingRight: '3vw', paddingLeft: '3vw', marginBottom: '2vw' }}>
        {steps.map((step) => {
          return (
            <Tooltip title={step.tooltip}>
              <Step key={step.label}>
                <StepLabel>{step.label}</StepLabel>
              </Step>
            </Tooltip>
          );
        })}
      </Stepper>
      <>
        <CurrentStep
          filters={filters}
          updateFilterState={updateFilterState}
          resetFilterState={() => setFilters({})}
          setNextDisabled={setNextDisabled}
          setRedirectBack={setRedirectBack}
        />
        <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2, pb: 2, paddingRight: '3vw', paddingLeft: '3vw' }}>
          <Button
            color="inherit"
            disabled={activeStep === 0}
            onClick={handleBack}
            sx={{ mr: 1 }}
          >
            Back
          </Button>
          <Box sx={{ flex: '1 1 auto' }} />
          {activeStep === steps.length - 1 ?
            <Button onClick={handleReset}>Reset</Button> : <Button onClick={handleNext} disabled={nextDisabled}>Next</Button>}
        </Box>
      </>
    </Box>
  );
}
