import React, { useState } from 'react';
import styled from 'styled-components';
import { uiColors } from '../constants/uiColors';
import SelectArrow from './Arrow/SelectArrow';
import { Button, ButtonTypes } from './Button';

interface IStep {
  component: React.ReactNode;
  id: number;
  validate?: () => boolean | Promise<boolean>;
  errorMessage?: string;
}

interface IStepperProps {
  steps: IStep[];
  finalCTAButton?: {
    label: string;
    onClick: (() => void) | (() => Promise<void>) | ((e: any) => Promise<void>);
  };
  onError?: (message: string) => void;
  useSideArrows?: boolean; // New prop to control arrow position
  styles?: {
    stepperProgressColor?: string;
  };
}

export const Stepper: React.FC<IStepperProps> = ({
  steps,
  finalCTAButton,
  onError,
  useSideArrows = false, // Default to false for backwards compatibility
  styles,
}) => {
  const [currentStep, setCurrentStep] = useState(0);

  const currentComponent = steps[currentStep]?.component;

  const totalSteps = steps.length;

  const onStepChange = async (step: number) => {
    if (steps[currentStep]?.validate) {
      try {
        const isValid = await steps[currentStep].validate!();
        if (!isValid) {
          if (onError) {
            onError(
              steps[currentStep].errorMessage ||
                `Validation failed on step ${currentStep + 1}`
            );
          }
          return;
        }
      } catch (error) {
        if (onError) {
          onError(
            `An error occurred during validation on step ${currentStep + 1}`
          );
        }
        return;
      }
    }
    setCurrentStep(step);
  };

  const renderArrows = () => {
    const leftArrow = (
      <SelectArrow
        direction="left"
        onPointerDown={() => onStepChange(Math.max(0, currentStep - 1))}
      />
    );

    const rightArrow = (
      <SelectArrow
        direction="right"
        onPointerDown={() =>
          onStepChange(Math.min(totalSteps - 1, currentStep + 1))
        }
      />
    );

    if (useSideArrows) {
      return (
        <>
          {currentStep > 0 && <ArrowContainer left>{leftArrow}</ArrowContainer>}
          {currentStep < totalSteps - 1 && (
            <ArrowContainer right>{rightArrow}</ArrowContainer>
          )}
        </>
      );
    } else {
      return (
        <>
          {currentStep > 0 && leftArrow}
          {currentStep < totalSteps - 1 && rightArrow}
        </>
      );
    }
  };

  return (
    <StepperContainer className="stepper-container">
      <StepperTop>
        {Array.from({ length: totalSteps }, (_, i) => (
          <ProgressIndicator
            key={i}
            isActive={i <= currentStep}
            stepperProgressColor={styles?.stepperProgressColor}
            onClick={() => onStepChange(i)}
          />
        ))}
      </StepperTop>

      <StepperBodyContainer>
        {useSideArrows && renderArrows()}
        <StepperBody>{currentComponent}</StepperBody>
      </StepperBodyContainer>

      {(!useSideArrows ||
        (currentStep === totalSteps - 1 && finalCTAButton)) && (
        <StepperFooter>
          {!useSideArrows && renderArrows()}
          {currentStep === totalSteps - 1 && finalCTAButton && (
            <Button
              buttonType={ButtonTypes.RPGUIButton}
              onClick={finalCTAButton.onClick}
            >
              {finalCTAButton.label}
            </Button>
          )}
        </StepperFooter>
      )}
    </StepperContainer>
  );
};

const StepperContainer = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
`;

const StepperTop = styled.div`
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  margin-bottom: 1rem;
`;

const StepperBodyContainer = styled.div`
  flex: 8;
  display: flex;
  align-items: center;
  position: relative;
  height: 100%; /* Ensure full height */
`;

const StepperBody = styled.div`
  flex: 1;
  min-height: 200px; /* Set an appropriate minimum height */
  transition: height 0.3s ease-in-out; /* Smooth height transition */
`;

const ArrowContainer = styled.div<{ left?: boolean; right?: boolean }>`
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  ${props => props.left && 'left: -30px;'}
  ${props => props.right && 'right: -30px;'}
`;

const StepperFooter = styled.div`
  margin-top: 1rem;
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
`;

const ProgressIndicator = styled.div<{
  isActive: boolean;
  stepperProgressColor?: string;
}>`
  width: 20px;
  height: 20px;
  background-color: ${({ isActive, stepperProgressColor }) =>
    isActive ? stepperProgressColor || uiColors.orange : uiColors.lightGray};
  margin: 0 5px;
  transition: background-color 0.3s;
  opacity: ${({ isActive }) => (isActive ? 1 : 0.25)};
  border: 1px solid ${uiColors.raisinBlack};
  cursor: pointer;
  clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
  /* Create a diamond shape */
  box-shadow: ${({ isActive }) =>
    isActive
      ? '0 0 0 1px black, 1px 1px 0 1px black, 2px 2px 0 1px black, -1px -1px 0 1px black'
      : '0 0 0 1px black, 1px 1px 0 1px gray, 2px 2px 0 1px gray, -1px -1px 0 1px gray'};
  /* Add pixel art border effect */
  border-radius: 0;
  /* Remove border-radius to make it square */
`;
