import { FlatList, ScrollView, StyleSheet, Text, TouchableWithoutFeedback, View } from 'react-native'
import React from 'react'
import { navigateToArticle, useConstructor } from '../../constants/functions'
import { getArticlesByCategory, getArticlesBySearch, getTrendingNews } from '../../api/data'
import LoadingScreen from '../../components/organisms/Sections/LoadingScreen'
import colors from '../../constants/colors'
import OctiIcon from 'react-native-vector-icons/Octicons'
import NewscoutCenteredTitleHeader from '../../components/molecules/Header/NewscoutCenteredTitleHeader'
import HorizontalNewsCardVariant from '../../components/molecules/Cards/HorizontalNewsCardVariant'
import { horizontalScale, moderateScale, verticalScale } from '../../constants/metrics'
const NewsListPage = props => {

  const {
    navigation,
    route
  } = props

  const {
    type,
    title
  } = route.params

  const fetchNews = (title,page = 1) => {
    getArticlesByCategory(title,page)
      .then(res => {
        setNews(prev => [...prev, ...res.data.body.results])
      }).catch(err => console.error(err))
  }

  const fetchTrendingNews = () => {
    getTrendingNews()
      .then(res => {
        setNews(prev => [...prev, ...res.data.body.results.map(item => item.articles[0])])
      }).catch(err => console.error(err))
  }

  const fetchSearchResults = (text) => {
    getArticlesBySearch(text).then(res => {
      setNews(prev => [...prev, ...res.data.body.results])
    }).catch(err => console.error(err))
  }
  const [headerName, setHeaderName] = React.useState("")
  const [news, setNews] = React.useState([])
  const [pagesLoaded, setPagesLoaded] = React.useState(0)


  //FlatList Optimizations

  const renderItem = (news) => {
    let newsItem = news.item; return <HorizontalNewsCardVariant
      onPress={() => navigateToArticle(navigation, newsItem.id, newsItem.slug)}
      timestamp={newsItem.published_on}
      headline={newsItem.title}
      image={{ uri: newsItem.cover_image }}
      category={newsItem.category}
      tagline={newsItem.id}
    />
  }

  const keyExtractor = (item) => news.indexOf(item)

  const scrollPagination = () => {

    setHeaderName(title)
    if (type === "normal") {
      switch (title) {
        case "Trending":
          fetchTrendingNews()
          break;
        case "Bookmark":
          break
        default:
          break;
      }
    } else if (type === "category") {
      fetchNews(title,pagesLoaded + 1)
      setPagesLoaded(pagesLoaded + 1)
    }else if (type === "search"){
      fetchSearchResults(title)
      setPagesLoaded(pagesLoaded + 1)
    }
    console.log(pagesLoaded)
    console.log(news.length)
  }

  useConstructor(() => {
    scrollPagination()
  })



  const styles = StyleSheet.create({
    pageContainer: {
      backgroundColor: colors().dominant
    },
    newsContainer: {
      backgroundColor: colors().dominant,
      minHeight: "100%",
      height: 'auto',
      paddingHorizontal: horizontalScale(16),
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: moderateScale(8),
      paddingVertical: verticalScale(16),
      numColumns: 2

    }
  })

  

  return (
    <View style={styles.pageContainer}>
      <NewscoutCenteredTitleHeader title={headerName} backButtonShown={true} onBackClick={() => navigation.goBack()}>
        <TouchableWithoutFeedback onPress={() => { navigation.toggleDrawer() }}>
          <OctiIcon name='three-bars' size={24} color={colors().primaryColor} />
        </TouchableWithoutFeedback>
      </NewscoutCenteredTitleHeader>
      {
        news.length <= 0 ?
          <LoadingScreen />
          :

          <FlatList
            contentContainerStyle={styles.newsContainer}
            showsVerticalScrollIndicator={false}
            data={news}
            renderItem={renderItem}
            keyExtractor={keyExtractor}
            onEndReached={scrollPagination}
            onEndReachedThreshold={200}
          />



      }
    </View>
  )
}

export default NewsListPage

