import { ScrollView, StyleSheet, Text, View } from 'react-native'
import React, { useContext } from 'react'
import { horizontalScale, moderateScale, verticalScale } from '../../../constants/metrics'
import VerticalNewsCard from '../../molecules/Cards/VerticalNewsCard'
import { navigateToArticle, useConstructor } from '../../../constants/functions'
import SectionHeader from '../../molecules/Header/SectionHeader'
import { ThemeContext } from '../../../context/theme.context'
import colors from '../../../constants/colors'
import { getArticlesByCategory } from '../../../api/data'

const RecentPostsSection = props => {

  const { 
    navigation,
    route
  } = props

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

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

  const fetchPosts = (category) => {
      getArticlesByCategory(category)
      .then(res => setPosts(res.data.body.results))
      .catch((err) => console.log(err))
      .finally(() => console.log("Fetch Posts Executed"))
  }

  useConstructor(function () {
    fetchPosts('Sector Updates');
  })

  const styles = StyleSheet.create({
    recentPostsContainer: {
      paddingHorizontal: horizontalScale(16),
      gap: moderateScale(4),
      paddingBottom: verticalScale(16),
      backgroundColor: colors().dominant,
      flexDirection:'row'
    }
  })


  return (
    <View style={styles.container}>
      <SectionHeader label={"Recents Posts"} />
      <ScrollView horizontal showsHorizontalScrollIndicator={false}>
        <View style={styles.recentPostsContainer}>

          {posts.map((item) => <VerticalNewsCard
            key={item.id}
            id={item.id}
            image={{uri :item.cover_image}}
            author={item.author}
            headline={item.title}
            tagline={item.blurb}
            timestamp={item.published_on}
            onPress={() => navigateToArticle(navigation,item.id,item.slug)}
          />)}

        </View>
      </ScrollView>
    </View>
  )
}

export default RecentPostsSection

