import React from 'react';
import { View, StyleSheet } from 'react-native';
import Animated, {
  useAnimatedStyle,
  withTiming,
} from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, radii } from '../../theme/tokens';
import { Caption } from './Typography';

interface StepperProps {
  currentStep: number;
  totalSteps: number;
  labels?: string[];
}

function StepDot({
  index,
  currentStep,
  label,
}: {
  index: number;
  currentStep: number;
  label?: string;
}) {
  const isCompleted = index < currentStep;
  const isCurrent = index === currentStep;

  const dotStyle = useAnimatedStyle(() => ({
    backgroundColor: withTiming(
      isCompleted
        ? colors.secondary[500]
        : isCurrent
        ? colors.primary[500]
        : colors.neutral[200],
      { duration: 300 }
    ),
    transform: [{ scale: withTiming(isCurrent ? 1.15 : 1, { duration: 300 }) }],
  }));

  return (
    <View style={styles.stepContainer}>
      <Animated.View
        style={[styles.dot, dotStyle]}
        accessibilityRole="progressbar"
        accessibilityLabel={`Step ${index + 1}${isCompleted ? ', completed' : isCurrent ? ', current' : ''}`}
      >
        {isCompleted && (
          <Ionicons name="checkmark" size={14} color="#FFF" />
        )}
      </Animated.View>
      {label && (
        <Caption
          style={[
            styles.label,
            (isCurrent || isCompleted) && styles.labelActive,
          ]}
          numberOfLines={1}
        >
          {label}
        </Caption>
      )}
    </View>
  );
}

function ConnectorLine({ isCompleted }: { isCompleted: boolean }) {
  const lineStyle = useAnimatedStyle(() => ({
    backgroundColor: withTiming(
      isCompleted ? colors.secondary[500] : colors.neutral[200],
      { duration: 300 }
    ),
  }));

  return <Animated.View style={[styles.line, lineStyle]} />;
}

export function Stepper({ currentStep, totalSteps, labels }: StepperProps) {
  return (
    <View style={styles.container}>
      {Array.from({ length: totalSteps }).map((_, i) => (
        <React.Fragment key={i}>
          <StepDot
            index={i}
            currentStep={currentStep}
            label={labels?.[i]}
          />
          {i < totalSteps - 1 && <ConnectorLine isCompleted={i < currentStep} />}
        </React.Fragment>
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: spacing.md,
  },
  stepContainer: {
    alignItems: 'center',
    width: 48,
  },
  dot: {
    width: 28,
    height: 28,
    borderRadius: radii.full,
    alignItems: 'center',
    justifyContent: 'center',
  },
  line: {
    flex: 1,
    height: 2,
    borderRadius: 1,
    marginHorizontal: spacing.xs,
  },
  label: {
    marginTop: spacing.xs,
    fontSize: 10,
    textAlign: 'center',
  },
  labelActive: {
    color: colors.primary[500],
  },
});
