import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import React, { useContext } from 'react';
import Carousel from 'react-native-reanimated-carousel';
import MaterialComIcon from 'react-native-vector-icons/MaterialCommunityIcons';
import { navigateToArticle, navigateToListViewPage, useConstructor } from '../../../constants/functions';
import fonts from '../../../constants/fonts';
import colors from '../../../constants/colors';
import ImageBGCard from '../../molecules/Cards/ImageBGCard';
import {
  moderateScale,
  screenHeight,
  screenWidth,
} from '../../../constants/metrics';
import SectionHeader from '../../molecules/Header/SectionHeader';
import { ThemeContext } from '../../../context/theme.context';
import { getTrendingNews } from '../../../api/data';
import LoadingScreen from './LoadingScreen';
import { PAGINATE_BY } from '../../../api/urls';


const TrendingSection = props => {

  const ITEM_WIDTH = Math.round(screenWidth * 1);
  const ITEM_HEIGHT = Math.round(screenHeight * (1 / 3.25));

  const {
    navigation
  } = props

  const theme = useContext(ThemeContext);
  const currentTheme = theme.state.theme;

  const [currentCardIndex, setCurrentCardIndex] = React.useState(0);
  const updateCurrentIndex = index => {
    console.log('current index:', index);
    setCurrentCardIndex(index);
  };

  const [posts, setPosts] = React.useState([]);
  const [isLoading, setLoading] = React.useState(true);

  const fetchPosts = () => {
    getTrendingNews()
      .then(res => {
        console.log(res.data)
        setPosts(res.data.body.results.slice(0, PAGINATE_BY));
        setLoading(false)
      })
      .catch(error => console.log(error));
  };

  useConstructor(function () {
    fetchPosts();
  });

  const styles = StyleSheet.create({
    recentHeader: {
      paddingHorizontal: 16,
    },
    recentHeaderText: {
      fontFamily: fonts.type.semibold,
      fontSize: moderateScale(16),
      color: colors().recessive,
    },
    seeAllText: {
      fontFamily: fonts.type.semibold,
      color: colors().primaryColor,
      paddingRight: 16,
      alignSelf: 'stretch',
    },
    recentHeaderIcon: {},
    recentCardContainer: {
      alignItems: 'center',
      paddingHorizontal: 8,
      minWidth: screenHeight,
      width: '100%',
      backgroundColor: colors().dominant,
    },
    paginationContainer: {
      justifyContent: 'center',
      alignItems: 'center',
      paddingHorizontal: 16,
      paddingTop: 8,
      paddingBottom: 8,
      flexDirection: 'row',
      gap: 2,
      backgroundColor: colors().dominant,
    },
  });


  return (
    <View>
      <SectionHeader label={'Trending'} onPress={() => navigateToListViewPage(navigation,"normal","Trending")}/>
      <View style={styles.recentCardContainer}>
        {isLoading === true ? (
          <LoadingScreen containerHeight={ITEM_HEIGHT} containerWidth={ITEM_WIDTH} />
        ) : (
          <Carousel
            loop
            width={ITEM_WIDTH}
            height={ITEM_HEIGHT}
            style={styles.recentCardContainer}
            autoPlay={true}
            data={posts}
            scrollAnimationDuration={2000}
            mode="parallax"
            modeConfig={{
              parallaxScrollingScale: 1,
              parallaxScrollingOffset: 1,
            }}
            onSnapToItem={index => updateCurrentIndex(index)}
            renderItem={({ index, item }) => (
              <View style={{ paddingHorizontal: 16 }}>
                <ImageBGCard
                  image={{ uri: item.articles[0].cover_image }}
                  author={item.articles[0].author}
                  headline={item.articles[0].title}
                  onPress={() => navigateToArticle(navigation, item.articles[0].id, item.articles[0].slug)}
                />
              </View>
            )}
          />
        )}
      </View>
      <View style={styles.paginationContainer}>
        {isLoading === true ? <></> : posts.map((item, index) => {
          return (
            <MaterialComIcon
              key={`dot_${index}`}
              name={'checkbox-blank-circle'}
              color={
                currentCardIndex === index
                  ? colors().secondaryColor
                  : colors().white_variant
              }
              size={8}
            />
          );
        })}
      </View>
    </View>
  );
};

export default TrendingSection;
