import React, { useRef, useEffect } from 'react';
import {
  View,
  ScrollView,
  Text,
  TouchableOpacity,
  Animated
} from 'react-native';
import { CarouselSection } from '../../data/carouselSections';
import { pillCarouselStyles as styles } from './styles';

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
}) => {
  const backgroundPosition = useRef(new Animated.Value(0)).current;
  const pillScrollViewRef = useRef<ScrollView>(null);

  // Handle background position updates
  useEffect(() => {
    const pillWidth = 100;
    const pillSpacing = 8;

    if (isDragging) {
      const targetPosition = scrollProgress * (pillWidth + pillSpacing);
      backgroundPosition.setValue(targetPosition);
    } else {
      const targetPosition = activeSection * (pillWidth + pillSpacing);
      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 pillWidth = 100;
    const pillSpacing = 8;
    const totalPillWidth = pillWidth + pillSpacing;
    const centerOffset = (screenWidth / 2) - (pillWidth / 2);
    const scrollToX = Math.max(0, (index * totalPillWidth) - 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 * 108 }]}>
          {/* Layer 1: Static grey text */}
          {sections.map((section, index) => (
            <View key={`grey-${section.id}`} style={[styles.textLayer, { left: index * 108 }]}>
              <Text style={styles.greyText}>{section.title}</Text>
            </View>
          ))}

          {/* Pill-shaped mask containers */}
          {sections.map((section, index) => (
            <View
              key={`mask-${section.id}`}
              style={[styles.pillMask, { left: index * 108 }]}
            >
              {/* Moving green background and white text */}
              <Animated.View
                style={[
                  styles.movingGreenBackground,
                  {
                    transform: [{
                      translateX: backgroundPosition.interpolate({
                        inputRange: [0, 1000],
                        outputRange: [-index * 108, 1000 - index * 108],
                        extrapolate: 'clamp'
                      })
                    }]
                  }
                ]}
              >
                <Animated.View style={[
                  styles.whiteTextInside,
                  {
                    transform: [{
                      translateX: backgroundPosition.interpolate({
                        inputRange: [0, 1000],
                        outputRange: [index * 108, -1000 + index * 108],
                        extrapolate: 'clamp'
                      })
                    }]
                  }
                ]}>
                  <Text style={styles.whiteText}>{section.title}</Text>
                </Animated.View>
              </Animated.View>
            </View>
          ))}

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

export default PillCarousel;