import React, { useEffect, useState } 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 PostCard from '../components/Socio/PostCard';
import CreatePost from '../components/Socio/CreatePost';
import TrendingBar from '../components/Socio/TrendingBar';
import LoadingSpinner from '../components/LoadingSpinner';
import UserAvatar from '../components/UserAvatar';

const FeedPage = () => {
  const dispatch = useAppDispatch();
  const { posts, loading } = useAppSelector((state) => state.posts);
  const { currentUser } = useAppSelector((state) => state.auth);
  
  const [refetch, setRefetch] = useState(0);

  useEffect(() => {
    dispatch(fetchPosts({ query: '?limit=10&page=0' }));
  }, [dispatch, refetch]);

  const stories = [
    { id: 1, name: 'Your Story', avatar: 'Me', isMe: true },
    { id: 2, name: 'Alice', avatar: 'AL' },
    { id: 3, name: 'Bob', avatar: 'BO' },
    { id: 4, name: 'Charlie', avatar: 'CH' },
    { id: 5, name: 'David', avatar: 'DA' },
    { id: 6, name: 'Eve', avatar: 'EV' },
  ];

  return (
    <>
      <Head>
        <title>{getPageTitle('Home Feed')}</title>
      </Head>

      <SectionMain>
        <div className="flex flex-col lg:flex-row gap-6 max-w-6xl mx-auto">
          {/* Main Feed Content */}
          <div className="flex-1 max-w-2xl mx-auto w-full">
            
            {/* Stories Bar */}
            <div className="flex items-center space-x-4 mb-8 overflow-x-auto pb-4 no-scrollbar">
              {stories.map((story) => (
                <div key={story.id} className="flex flex-col items-center flex-shrink-0 cursor-pointer group">
                  <div className={`w-16 h-16 rounded-full p-[2px] mb-1 ring-2 ${story.isMe ? 'ring-indigo-200 dark:ring-indigo-900' : 'ring-indigo-500'}`}>
                    <div className="w-full h-full rounded-full border-2 border-white dark:border-dark-800 overflow-hidden bg-gray-100 dark:bg-dark-900 flex items-center justify-center font-bold text-indigo-600">
                      {story.isMe && currentUser ? (
                        <UserAvatar username={currentUser.firstName} className="w-full h-full" />
                      ) : (
                        story.avatar
                      )}
                    </div>
                  </div>
                  <span className="text-[10px] font-semibold text-gray-600 dark:text-dark-600 group-hover:text-indigo-600 transition-colors">
                    {story.name}
                  </span>
                </div>
              ))}
            </div>

            {/* Create Post Widget */}
            <CreatePost onPostCreated={() => setRefetch(prev => prev + 1)} />

            {/* Posts List */}
            {loading && !posts.length ? (
              <LoadingSpinner />
            ) : (
              <div className="space-y-6">
                {posts.map((post: any) => (
                  <PostCard key={post.id} post={post} />
                ))}
                
                {!loading && posts.length === 0 && (
                  <div className="text-center py-20 bg-white dark:bg-dark-800 rounded-xl shadow-sm border border-gray-100 dark:border-dark-700">
                    <p className="text-gray-500">No posts yet. Be the first to post something!</p>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Right Sidebar - Trending & Suggestions */}
          <TrendingBar />
        </div>
      </SectionMain>
    </>
  );
};

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

export default FeedPage;
