import React, {useEffect, useRef, useState} from 'react';
import {
  Dimensions,
  FlatList,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  ViewToken,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import {MetaPreview} from '../../api/addonTypes';
import {colors, typography} from '../../utils/colors';

const {width: SW, height: SH} = Dimensions.get('window');
const HERO_HEIGHT = SH * 0.50;
const AUTO_SCROLL_INTERVAL = 5000;

interface Props {
  items: MetaPreview[];
  onPress: (item: MetaPreview) => void;
  onPressPlay: (item: MetaPreview) => void;
}

export default function HeroCarousel({items, onPress, onPressPlay}: Props) {
  const [activeIdx, setActiveIdx] = useState(0);
  const listRef = useRef<FlatList>(null);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const displayed = items.slice(0, 6);

  useEffect(() => {
    if (displayed.length < 2) return;
    timerRef.current = setInterval(() => {
      setActiveIdx(prev => {
        const next = (prev + 1) % displayed.length;
        listRef.current?.scrollToIndex({index: next, animated: true});
        return next;
      });
    }, AUTO_SCROLL_INTERVAL);
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [displayed.length]);

  const onViewRef = useRef(
    ({viewableItems}: {viewableItems: ViewToken[]}) => {
      if (viewableItems.length > 0 && viewableItems[0].index != null) {
        setActiveIdx(viewableItems[0].index);
      }
    },
  );

  if (displayed.length === 0) return null;

  return (
    <View style={styles.container}>
      <FlatList
        ref={listRef}
        data={displayed}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        keyExtractor={item => item.id}
        onViewableItemsChanged={onViewRef.current}
        viewabilityConfig={{viewAreaCoveragePercentThreshold: 50}}
        renderItem={({item}) => (
          <TouchableOpacity
            style={styles.slide}
            onPress={() => onPress(item)}
            activeOpacity={0.95}>
            {/* Backdrop */}
            <Image
              style={styles.backdrop}
              source={{uri: item.background || item.poster}}
              resizeMode="cover"
            />
            {/* Multi-layer gradient for depth */}
            <LinearGradient
              colors={['rgba(6,11,20,0.15)', 'rgba(6,11,20,0.55)', '#060B14']}
              locations={[0, 0.55, 1]}
              style={StyleSheet.absoluteFillObject}
            />
            {/* Side vignette */}
            <LinearGradient
              colors={['#060B14', 'transparent', '#060B14']}
              start={{x: 0, y: 0.5}}
              end={{x: 1, y: 0.5}}
              locations={[0, 0.12, 1]}
              style={StyleSheet.absoluteFillObject}
            />

            {/* Content */}
            <View style={styles.info}>
              {item.genres && item.genres.length > 0 && (
                <View style={styles.genreRow}>
                  {item.genres.slice(0, 2).map(g => (
                    <View key={g} style={styles.genreTag}>
                      <Text style={styles.genreText}>{g}</Text>
                    </View>
                  ))}
                </View>
              )}
              <Text style={styles.title} numberOfLines={2}>
                {item.name}
              </Text>
              {item.description && (
                <Text style={styles.desc} numberOfLines={2}>
                  {item.description}
                </Text>
              )}
              <View style={styles.actions}>
                <TouchableOpacity
                  style={styles.playButton}
                  onPress={() => onPressPlay(item)}
                  activeOpacity={0.85}>
                  <Text style={styles.playIcon}>▶</Text>
                  <Text style={styles.playText}>Play</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.moreButton}
                  onPress={() => onPress(item)}
                  activeOpacity={0.85}>
                  <Text style={styles.moreText}>More Info</Text>
                </TouchableOpacity>
              </View>
            </View>
          </TouchableOpacity>
        )}
      />

      {/* Dot indicators */}
      <View style={styles.dots}>
        {displayed.map((_, i) => (
          <View
            key={i}
            style={[styles.dot, i === activeIdx && styles.dotActive]}
          />
        ))}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    height: HERO_HEIGHT + 28,
    marginBottom: 4,
  },
  slide: {
    width: SW,
    height: HERO_HEIGHT,
  },
  backdrop: {
    ...StyleSheet.absoluteFillObject,
  },
  info: {
    position: 'absolute',
    bottom: 16,
    left: 18,
    right: 18,
  },
  genreRow: {
    flexDirection: 'row',
    gap: 6,
    marginBottom: 8,
  },
  genreTag: {
    backgroundColor: 'rgba(108,79,240,0.35)',
    borderWidth: 1,
    borderColor: colors.primary + '70',
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 4,
  },
  genreText: {
    fontSize: 10,
    fontWeight: '700',
    color: colors.primaryLight,
    textTransform: 'uppercase',
    letterSpacing: 0.5,
  },
  title: {
    ...typography.hero,
    color: colors.textPrimary,
    marginBottom: 6,
    textShadowColor: 'rgba(0,0,0,0.9)',
    textShadowOffset: {width: 0, height: 2},
    textShadowRadius: 6,
  },
  desc: {
    ...typography.body,
    color: colors.textSecondary,
    marginBottom: 16,
    lineHeight: 20,
  },
  actions: {
    flexDirection: 'row',
    gap: 10,
    alignItems: 'center',
  },
  playButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.primary,
    paddingHorizontal: 22,
    paddingVertical: 10,
    borderRadius: 8,
    gap: 8,
    elevation: 4,
    shadowColor: colors.primary,
    shadowOffset: {width: 0, height: 4},
    shadowOpacity: 0.5,
    shadowRadius: 8,
  },
  playIcon: {color: '#fff', fontSize: 13},
  playText: {
    color: '#fff',
    fontSize: 15,
    fontWeight: '700',
  },
  moreButton: {
    paddingHorizontal: 18,
    paddingVertical: 10,
    borderRadius: 8,
    backgroundColor: 'rgba(255,255,255,0.12)',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.15)',
  },
  moreText: {
    color: colors.textPrimary,
    fontSize: 14,
    fontWeight: '600',
  },
  dots: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
    gap: 5,
  },
  dot: {
    width: 5,
    height: 5,
    borderRadius: 2.5,
    backgroundColor: colors.textMuted,
  },
  dotActive: {
    width: 20,
    height: 5,
    borderRadius: 2.5,
    backgroundColor: colors.primary,
  },
});
