import { Stack } from '@mui/material';

import Step from './components/Step';
import { type StepperProps } from './types';

const Stepper = ({
  steps,
  currentStep = 0,
  completedSteps = [],
  errorSteps = [],
  completeBeforeCurrent = true,
  sx = {},
}: StepperProps) => {
  const lastStep = steps.length - 1;

  if (!steps?.length) return null;

  return (
    <Stack
      sx={{
        flexDirection: 'row',
        alignItems: 'start',
        overflow: 'auto',
        ...sx,
      }}
    >
      {steps?.map((step, index) => {
        const isCurrent = index === currentStep;
        const isBeforeCurrent = index < currentStep;
        const isCompletedStep =
          Array.isArray(completedSteps) && completedSteps?.includes(index);
        const hasError =
          Array.isArray(errorSteps) && errorSteps?.includes(index);

        return (
          <Step
            hasError={hasError}
            id={step.id}
            isCompleted={
              (completeBeforeCurrent && isBeforeCurrent) || isCompletedStep
            }
            isCurrent={isCurrent}
            isLast={index === lastStep}
            key={step.id}
            number={step.number || index + 1}
            subtitle={step.subtitle}
            title={step.title}
          />
        );
      })}
    </Stack>
  );
};

export type { StepperProps };

export default Stepper;
