import { useTheme } from '@emotion/react';
import React, { useMemo } from 'react';
import type { LayoutChangeEvent, ViewProps } from 'react-native';
import {
  StyledSingleStep,
  StyledSingleStepContainer,
  StyledStep,
  StyledStepContainer,
} from './StyledStep';

export interface ProgressStepProps extends ViewProps {
  /**
   * The total number of steps.
   */
  steps: number;
  /**
   * The current step.
   */
  current: number;
  /**
   * Test ID of the component.
   */
  testID?: string;
}

type StepState = 'complete' | 'incomplete' | 'current';

export const getStepState = (current: number, index: number): StepState => {
  if (index < current) {
    return 'complete';
  }

  if (index === current) {
    return 'current';
  }

  return 'incomplete';
};

const ProgressStep = ({
  steps,
  current,
  onLayout,
  ...props
}: ProgressStepProps) => {
  const theme = useTheme();
  const [containerWidth, setContainerWidth] = React.useState(0);

  const onContainerLayout = (event: LayoutChangeEvent) => {
    setContainerWidth(event.nativeEvent.layout.width);

    onLayout?.(event);
  };

  // Calculate the width for each step
  const stepWidth = useMemo(() => {
    let width = 0;
    if (containerWidth > 0) {
      width =
        (containerWidth - (steps - 1) * theme.__hd__.progress.space.stepGap) /
        steps;
    }

    return width;
  }, [containerWidth, steps, theme]);

  if (steps === 1) {
    return (
      <StyledSingleStepContainer {...props}>
        <StyledSingleStep
          themeState={current >= steps ? 'complete' : 'incomplete'}
        />
      </StyledSingleStepContainer>
    );
  }

  return (
    <StyledStepContainer {...props} onLayout={onContainerLayout}>
      {Array.from({ length: steps }).map((_, index) => (
        <StyledStep
          themeState={getStepState(current - 1, index)}
          themeWidth={stepWidth}
        />
      ))}
    </StyledStepContainer>
  );
};

export default ProgressStep;
