// template/src/components/PillCarousell/index.tsx
import React, { useRef, useEffect } from 'react';
import {
  View,
  ScrollView,
  TouchableOpacity,
  Animated
} from 'react-native';
import { CarouselSection } from '../../modules/core/combined-auth/data/carouselSections';
import { pillCarouselStyles } from './styles';
import { useTheme } from 'theme/ThemeProvider';
import { ThemedText } from '@components/ThemedText';


interface PillCarouselProps {
  sections: CarouselSection[];
  activeSection: number;
  scrollProgress: number;
  onSectionPress: (index: number) => void;
  screenWidth: number;
  isDragging?: boolean;
}

const PillCarousel: React.FC<PillCarouselProps> = ({
  sections,
  activeSection,
  scrollProgress,
  onSectionPress,
  screenWidth,
  isDragging = false
}) => {
  // Constants for pill dimensions
  const PILL_WIDTH = 120;
  const PILL_SPACING = 16;
  const TOTAL_PILL_WIDTH = PILL_WIDTH + PILL_SPACING;
  const PILL_HEIGHT = 32;
  const PILL_BORDER_RADIUS = 12;

  const backgroundPosition = useRef(new Animated.Value(0)).current;
  const pillScrollViewRef = useRef<ScrollView>(null);

  const { theme, themeName } = useTheme();
  const styles = pillCarouselStyles(theme);

  // Use your theme system instead of useColorScheme
  const isDarkMode = themeName === 'dark';
  const movingBackgroundColor = isDarkMode ? theme.colors.accent : '#000000';
  const movingTextColor = isDarkMode ? '#000000' : '#ffffff'; // Black text on green accent, white text on black background

  console.log('PillCarousel - themeName:', themeName, 'isDarkMode:', isDarkMode, 'movingBackgroundColor:', movingBackgroundColor);

  // Handle background position updates
  useEffect(() => {
    if (isDragging) {
      const targetPosition = scrollProgress * TOTAL_PILL_WIDTH;
      backgroundPosition.setValue(targetPosition);
    } else {
      const targetPosition = activeSection * TOTAL_PILL_WIDTH;
      Animated.timing(backgroundPosition, {
        toValue: targetPosition,
        duration: 0,
        useNativeDriver: false,
      }).start();
    }
  }, [scrollProgress, activeSection, isDragging]);

  // Handle pill scrolling only when activeSection changes and not dragging
  useEffect(() => {
    if (!isDragging) {
      scrollPillsToCenter(activeSection);
    }
  }, [activeSection]); // Only watch activeSection changes

  const scrollPillsToCenter = (index: number) => {
    console.log('scrollPillsToCenter called for index:', index);

    const centerOffset = (screenWidth / 2) - (PILL_WIDTH / 2);
    const scrollToX = Math.max(0, (index * TOTAL_PILL_WIDTH) - centerOffset + 16);

    console.log('Calculated scrollToX:', scrollToX);
    console.log('ScrollView ref exists:', !!pillScrollViewRef.current);

    pillScrollViewRef.current?.scrollTo({
      x: scrollToX,
      animated: true,
    });
  };

  return (
    <View style={styles.topNav}>
      <ScrollView
        ref={pillScrollViewRef}
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={{
          paddingHorizontal: 0, // Remove left padding
          paddingRight: 0, // Keep some right padding for scrolling past the last pill
        }}
        style={styles.pillScrollView}
      >
        <View style={[styles.pillContainer, { width: sections.length * TOTAL_PILL_WIDTH }]}>
          {/* Layer 1: Static grey text */}
          {sections.map((section, index) => (
            <View key={`grey-${section.id}`} style={[
              styles.textLayer,
              {
                left: index * TOTAL_PILL_WIDTH,
                width: PILL_WIDTH,
                height: PILL_HEIGHT,
                borderRadius: PILL_BORDER_RADIUS,
                backgroundColor: isDarkMode ? theme.colors.surface : '#f0f0f0', // Dark background in dark mode
                borderColor: isDarkMode ? theme.colors.border : '#e0e0e0', // Dark border in dark mode
              }
            ]}>
              {/* <Text style={[styles.greyText, { color: isDarkMode ? theme.colors.textSecondary : '#666' }]}>{section.title}</Text> */}
              <ThemedText style={[styles.greyText, { color: isDarkMode ? '#fff' : '#666' }]}>{section.title}</ThemedText>
            </View>
          ))}

          {/* Pill-shaped mask containers */}
          {sections.map((section, index) => (
            <View
              key={`mask-${section.id}`}
              style={[
                styles.pillMask,
                {
                  left: index * TOTAL_PILL_WIDTH,
                  width: PILL_WIDTH,
                  height: PILL_HEIGHT,
                  borderRadius: PILL_BORDER_RADIUS
                }
              ]}
            >
              {/* Moving green background and white text */}
              <Animated.View
                style={[
                  styles.movingGreenBackground,
                  {
                    width: PILL_WIDTH,
                    height: PILL_HEIGHT,
                    borderRadius: 0, // Square shape as requested
                    backgroundColor: movingBackgroundColor, // Black in light mode, accent in dark mode
                    transform: [{
                      translateX: backgroundPosition.interpolate({
                        inputRange: [0, 1000],
                        outputRange: [-index * TOTAL_PILL_WIDTH, 1000 - index * TOTAL_PILL_WIDTH],
                        extrapolate: 'clamp'
                      })
                    }]
                  }
                ]}
              >
                <Animated.View style={[
                  styles.whiteTextInside,
                  {
                    width: PILL_WIDTH,
                    height: PILL_HEIGHT,
                    transform: [{
                      translateX: backgroundPosition.interpolate({
                        inputRange: [0, 1000],
                        outputRange: [index * TOTAL_PILL_WIDTH, -1000 + index * TOTAL_PILL_WIDTH],
                        extrapolate: 'clamp'
                      })
                    }]
                  }
                ]}>
                  <ThemedText style={[styles.whiteText, { color: movingTextColor }]}>{section.title}</ThemedText>
                </Animated.View>
              </Animated.View>
            </View>
          ))}

          {/* Touch targets */}
          {sections.map((section, index) => (
            <TouchableOpacity
              key={`touch-${section.id}`}
              style={[
                styles.touchTarget,
                {
                  left: index * TOTAL_PILL_WIDTH,
                  width: PILL_WIDTH,
                  height: PILL_HEIGHT,
                  borderRadius: PILL_BORDER_RADIUS
                }
              ]}
              onPress={() => onSectionPress(index)}
            />
          ))}
        </View>
      </ScrollView>
    </View>
  );
};

export default PillCarousel;