/**
 * TabataFit OnboardingStep
 * Reusable wrapper for each onboarding screen — progress bar, animation, layout
 *
 * Revamped: fade-up entrance, segmented progress, generous spacing
 */

import { useRef, useEffect, useMemo } from 'react'
import { View, StyleSheet, Animated, Pressable } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { Icon } from './Icon'
import { useThemeColors } from '../theme'
import type { ThemeColors } from '../theme/types'
import { SPACING, LAYOUT } from '../constants/spacing'
import { RADIUS } from '../constants/borderRadius'
import { DURATION, EASE, SPRING } from '../constants/animations'
import { GREEN } from '../constants/colors'

interface OnboardingStepProps {
  step: number
  totalSteps: number
  children: React.ReactNode
  onBack?: () => void
}

export function OnboardingStep({ step, totalSteps, children, onBack }: OnboardingStepProps) {
  const colors = useThemeColors()
  const styles = useMemo(() => createStyles(colors), [colors])
  const insets = useSafeAreaInsets()
  const fadeAnim = useRef(new Animated.Value(0)).current
  const slideAnim = useRef(new Animated.Value(24)).current
  const progressAnims = useRef(
    Array.from({ length: totalSteps }, () => new Animated.Value(0))
  ).current

  useEffect(() => {
    // Reset for new step — fade up instead of slide right
    fadeAnim.setValue(0)
    slideAnim.setValue(24)

    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: DURATION.NORMAL,
        easing: EASE.EASE_OUT,
        useNativeDriver: true,
      }),
      Animated.spring(slideAnim, {
        toValue: 0,
        ...SPRING.GENTLE,
        useNativeDriver: true,
      }),
    ]).start()

    // Animate progress segments
    progressAnims.forEach((anim, i) => {
      Animated.spring(anim, {
        toValue: i < step ? 1 : 0,
        ...SPRING.SNAPPY,
        useNativeDriver: false,
      }).start()
    })
  }, [step])

  return (
    <View style={[styles.container, { paddingTop: insets.top + SPACING[4] }]}>
      {/* Segmented progress bar */}
      <View style={styles.progressRow}>
        {progressAnims.map((anim, i) => (
          <View key={i} style={styles.segmentTrack}>
            <Animated.View
              style={[
                styles.segmentFill,
                {
                  width: anim.interpolate({
                    inputRange: [0, 1],
                    outputRange: ['0%', '100%'],
                  }),
                },
              ]}
            />
          </View>
        ))}
      </View>

      {/* Back button — visible on steps 2+ */}
      {onBack && step > 1 ? (
        <Pressable
          style={styles.backButton}
          onPress={onBack}
          hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
          testID="onboarding-back-button"
        >
          <Icon name="chevron.left" size={22} tintColor={colors.text.secondary} />
        </Pressable>
      ) : (
        <View style={styles.backSpacer} />
      )}

      {/* Step content */}
      <Animated.View
        style={[
          styles.content,
          {
            transform: [{ translateY: slideAnim }],
            opacity: fadeAnim,
          },
          { paddingBottom: insets.bottom + SPACING[8] },
        ]}
      >
        {children}
      </Animated.View>
    </View>
  )
}

function createStyles(colors: ThemeColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.bg.base,
    },
    progressRow: {
      flexDirection: 'row',
      gap: SPACING[1],
      marginHorizontal: LAYOUT.SCREEN_PADDING,
    },
    segmentTrack: {
      flex: 1,
      height: 4,
      backgroundColor: colors.bg.overlay2,
      borderRadius: RADIUS.PILL,
      overflow: 'hidden',
    },
    segmentFill: {
      height: '100%',
      backgroundColor: GREEN[500],
      borderRadius: RADIUS.PILL,
    },
    backButton: {
      marginTop: SPACING[3],
      marginLeft: SPACING[2],
      width: LAYOUT.TOUCH_TARGET,
      height: LAYOUT.TOUCH_TARGET,
      alignItems: 'center',
      justifyContent: 'center',
    },
    backSpacer: {
      height: SPACING[3] + LAYOUT.TOUCH_TARGET,
    },
    content: {
      flex: 1,
      paddingHorizontal: LAYOUT.SCREEN_PADDING,
    },
  })
}
