import React, { useEffect } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import { getPageTitle } from '../config';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { fetch as fetchPosts } from '../stores/posts/postsSlice';
import SocialPostCard from '../components/Posts/SocialPostCard';
import LoadingSpinner from '../components/LoadingSpinner';

export default function FeedPage() {
    const dispatch = useAppDispatch();
    const { posts, loading } = useAppSelector((state) => state.posts);

    useEffect(() => {
        dispatch(fetchPosts({ page: 1, limit: 10 }));
    }, [dispatch]);

    return (
        <>
            <Head>
                <title>{getPageTitle('Feed')}</title>
            </Head>
            <SectionMain>
                <div className="max-w-2xl mx-auto py-8">
                    <h1 className="text-3xl font-black mb-8 dark:text-white tracking-tight px-4">Your Feed</h1>
                    
                    {loading && (
                        <div className="flex justify-center py-20">
                            <LoadingSpinner />
                        </div>
                    )}

                    {!loading && posts && Array.isArray(posts) && posts.length > 0 && (
                        <div className="space-y-4">
                            {posts.map((post: any) => (
                                <SocialPostCard 
                                    key={post.id} 
                                    post={post} 
                                    onLike={(id) => console.log('Like', id)}
                                    onComment={(id) => console.log('Comment', id)}
                                />
                            ))}
                        </div>
                    )}

                    {!loading && (!posts || (Array.isArray(posts) && posts.length === 0)) && (
                        <div className="text-center py-20 bg-gray-50 dark:bg-gray-800/50 rounded-3xl border border-dashed border-gray-300 dark:border-gray-700 mx-4">
                            <p className="text-gray-500 dark:text-gray-400">No posts yet. Be the first to share something!</p>
                        </div>
                    )}
                </div>
            </SectionMain>
        </>
    );
}

FeedPage.getLayout = function getLayout(page: ReactElement) {
    return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};