import React, { useEffect, useRef, useState } from 'react';
import { 
    View, 
    FlatList, 
    Text,
    Image,
    StyleSheet, 
    Dimensions, 
    Animated, 
    NativeScrollEvent, 
    NativeSyntheticEvent 
} from 'react-native';
import { Colors, Fonts } from '../../constants/theme';

const { width: SCREEN_WIDTH } = Dimensions.get('window');
const CAROUSEL_HEIGHT = 180; 

const ADS = [
  {
    id: '1',
    image: 'https://images.unsplash.com/photo-1581094794329-c8112a89af12?q=80&w=1200&auto=format&fit=crop', 
    title: 'Sua Casa em Boas Mãos',
    subtitle: 'Suporte Técnico Especializado'
  },
  {
    id: '2',
    image: 'https://images.unsplash.com/photo-1621905251189-08b45d6a269e?q=80&w=1200&auto=format&fit=crop',
    title: 'Manutenção Profissional',
    subtitle: 'Rápido, Seguro e Eficiente'
  },
  {
    id: '3',
    image: require('../../assets/images/banner_bg.png'),
    title: 'Resolvemos a tempo e hora',
    subtitle: 'Excelência em cada detalhe',
    isBanner: true
  }
];

export const AdCarousel = () => {
  const [activeIndex, setActiveIndex] = useState(0);
  const flatListRef = useRef<FlatList>(null);
  const scrollX = useRef(new Animated.Value(0)).current;

  // Auto-scroll logic
  useEffect(() => {
    let interval = setInterval(() => {
      const nextIndex = activeIndex < ADS.length - 1 ? activeIndex + 1 : 0;
      flatListRef.current?.scrollToIndex({
        index: nextIndex,
        animated: true,
      });
      setActiveIndex(nextIndex);
    }, 5000);

    return () => clearInterval(interval);
  }, [activeIndex]);

  const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
    const contentOffsetX = event.nativeEvent.contentOffset.x;
    const currentIndex = Math.round(contentOffsetX / SCREEN_WIDTH);
    if (currentIndex !== activeIndex) {
      setActiveIndex(currentIndex);
    }
    // Update scrollX manually since we're not using Animated.event
    scrollX.setValue(contentOffsetX);
  };

  const renderItem = ({ item }: { item: any }) => (
    <View style={styles.cardContainer}>
      <Image 
        source={typeof item.image === 'string' ? { uri: item.image } : item.image} 
        style={styles.image} 
        resizeMode="cover" 
      />
      <View style={[styles.overlay, item.isBanner && styles.bannerOverlay]}>
        <View style={styles.textContainer}>
          <Text style={styles.title}>{item.title}</Text>
          {item.subtitle && <Text style={styles.subtitle}>{item.subtitle}</Text>}
        </View>
      </View>
    </View>
  );

  return (
    <View style={styles.container}>
      <FlatList
        ref={flatListRef}
        data={ADS}
        renderItem={renderItem}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        onScroll={handleScroll}
        scrollEventThrottle={16}
        keyExtractor={(item) => item.id}
      />
      
      <View style={styles.pagination}>
        {ADS.map((_, i) => {
          const opacity = scrollX.interpolate({
            inputRange: [(i - 1) * SCREEN_WIDTH, i * SCREEN_WIDTH, (i + 1) * SCREEN_WIDTH],
            outputRange: [0.3, 1, 0.3],
            extrapolate: 'clamp',
          });
          return (
            <Animated.View
              key={i}
              style={[styles.dot, { opacity, width: activeIndex === i ? 20 : 8 }]}
            />
          );
        })}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    height: CAROUSEL_HEIGHT,
    backgroundColor: 'transparent',
    marginVertical: 15,
  },
  cardContainer: {
    width: SCREEN_WIDTH,
    height: CAROUSEL_HEIGHT,
    paddingHorizontal: 20,
  },
  image: {
    width: '100%',
    height: '100%',
    borderRadius: 24,
    backgroundColor: '#f1f5f9',
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.3)',
    marginHorizontal: 20,
    borderRadius: 24,
    padding: 20,
    justifyContent: 'flex-end',
  },
  bannerOverlay: {
    backgroundColor: 'rgba(0,0,0,0.4)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  textContainer: {
    width: '100%',
  },
  title: {
    color: '#fff',
    fontSize: 22,
    fontWeight: '900',
    letterSpacing: -0.5,
    textShadowColor: 'rgba(0, 0, 0, 0.75)',
    textShadowOffset: { width: -1, height: 1 },
    textShadowRadius: 10,
  },
  subtitle: {
    color: 'rgba(255,255,255,0.8)',
    fontSize: 14,
    fontWeight: '600',
    marginTop: 4,
  },
  pagination: {
    flexDirection: 'row',
    position: 'absolute',
    bottom: 15,
    alignSelf: 'center',
  },
  dot: {
    height: 6,
    borderRadius: 3,
    backgroundColor: '#fff',
    marginHorizontal: 4,
  },
});
