import { StyleSheet, Text, TouchableOpacity, View } from 'react-native'
import React from 'react'
import fonts from '../../../theme/fonts'
import colors from '../../../theme/colors'
import ImageBGCard from '../Cards/ImageBGCard'
import images from '../../../assets/images/images'
import SectionHeader from '../Headers/SectionHeader'
import metrics from '../../../theme/metrics'
import Carousel from 'react-native-reanimated-carousel';
import MaterialComIcon from 'react-native-vector-icons/MaterialCommunityIcons'
import { useConstructor } from '../../../utils/Constants/functions'
import { PAGINATE_BY } from '../../../utils/Constants/constants'

// import {Q} from '@nozbe/watermelondb';
// import withObservables from '@nozbe/with-observables';


const ITEM_WIDTH = Math.round(metrics.screenWidth * 0.9);
const ITEM_HEIGHT = Math.round(ITEM_WIDTH * 3 / 4);

/*
   Enhanced News Card
*/

// const EnhancedImageBGCard = withObservables(['recent_news'], ({news}) => ({
//   news: news.observe(),
// }))(ImageBGCard);


const RecentNewsSection = () => {

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

  const [posts,setPosts] = React.useState([{},{},{},{},{}])

  const fetchPosts = () => {
    fetch("http://www.newscout.in/api/v1/trending?domain=newscout")
    .then((res) => res.json())
    .then((json) => {
      let postData = json.body.results
      // const finalPostData = postData.slice(0,5).map((item)=> ({
      //   image:item.cover_image,
      //   author: item.author,
      //   headline: item.title,
      //   id: item.id,
      // }))
      let buffer = []
      postData.slice(0,PAGINATE_BY).forEach((item) => buffer.push(...item.articles))
      // let buffer = [] 
      // for (const item of postData.slice(0,PAGINATE_BY)) {
      //   buffer.push(...item.articles)
      // }
      // console.log(`Bruh ` + buffer)
      const finalPostData = buffer.map((item)=> ({
        image:item.cover_image,
        author: item.author,
        headline: item.title,
        id: item.id,
      }))
      setPosts(finalPostData)
      return finalPostData
    })
    .catch((err) => console.log(err))
    .finally(() => console.log("Fetch Posts Executed"))
  }

  useConstructor(function(){
    fetchPosts()
    
  })

  return (
    <View>
      {/* <SectionHeader label={"Recent News"} /> */}
      <SectionHeader label={"Trending"} />
      <View style={styles.recentCardContainer}>
        <Carousel
          loop
          width={metrics.screenWidth}
          height={ITEM_HEIGHT}
          style={styles.recentCardContainer}
          autoPlay={true}
          data={posts}
          scrollAnimationDuration={1000}
          mode="parallax"
          modeConfig={{
            parallaxScrollingScale: 1,
            parallaxScrollingOffset: 1,
          }}
          onSnapToItem={(index) => updateCurrentIndex(index)}
          renderItem={({index,item}) => (
            <View style={{ paddingHorizontal: 16 }}>
              <ImageBGCard
                image={{uri: item.image} ?? images.imageCard}
                author={ item.author ?? "Anonymous Author"}
                headline={item.headline ?? `Bruh Moment ${index}`}
              />
            </View>
          )}
        />
       
      </View>
      <View style={styles.paginationContainer}>
        {posts.map((item, index) => {
          return <MaterialComIcon key={`dot_${index}`} name={"checkbox-blank-circle"} color={currentCardIndex === index ? colors.tertiaryColor: colors.lightGray} size={12} />
        })}
      </View>
    </View>
  )
}

export default RecentNewsSection

const styles = StyleSheet.create({
  recentHeader: {
    paddingHorizontal: 16,
  },
  recentHeaderText: {
    fontFamily: fonts.type.semibold,
    fontSize: fonts.getSize(16),
    color: colors.black
  },
  seeAllText: {
    fontFamily: fonts.type.semibold,
    color: colors.topColor,
    paddingRight: 16,
    alignSelf: 'stretch'

  },
  recentHeaderIcon: {

  },
  recentCardContainer: {
    alignItems: 'center',
    paddingHorizontal: 8,
    width: metrics.screenWidth
  },
  paginationContainer:{
    justifyContent:'flex-end',
    alignItems:'center',
    paddingHorizontal: 16,
    paddingTop:8,
    paddingBottom:4,
    flexDirection:'row',
    gap:2}
})