import { useFocusEffect } from 'expo-router'
import React, { useState } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import { PostComponent } from '../components/PostComponent'
import { Post } from '../models/postModel'

export default function PostsScreen() {
    const cloudfrontURL = process.env.CLOUDFRONT_URL
    const [posts, setPosts] = useState<Post[]>()

    useFocusEffect(
        React.useCallback(() => {
            // Do something when the screen is focused
            // TODO: add endpoint to get only non approved or denied status posts
            fetchData()
            return () => {
                // Do something when the screen is unfocused
                // Useful for cleanup functions
            }
        }, [])
    )

    async function fetchData() {
        fetch('http://localhost:3000/api/v1/posts/status/created')
            .then((res) => res.json())
            .then((json) => {
                setPosts(json.data)
            })
    }

    return (
        <View style={styles.wrapper}>
            <Text style={styles.title}>Posts</Text>
            {posts?.length ? (
                posts.map((el) => <PostComponent key={el._id} post={el} fetchData={fetchData} />)
            ) : (
                <View style={styles.caughtUpContainer}>
                    <Text style={styles.caughtUpText}>All caught up!</Text>
                </View>
            )}
        </View>
    )
}

const styles = StyleSheet.create({
    wrapper: {
        flex: 1,
        backgroundColor: '#25292e',
        padding: 16,
        alignItems: 'center',
        overflow: 'scroll'
    },
    title: {
        color: '#fff',
        justifyContent: 'center'
    },
    posts: {
        marginTop: 10,
        backgroundColor: '#363c43ff',
        padding: 10,
        width: '90%',
        borderRadius: 5
    },
    caughtUpContainer: {
        flex: 1,
        alignContent: 'center',
        justifyContent: 'center'
    },
    caughtUpText: {
        color: '#787b80ff'
    }
})
