import { useCallback, useEffect, useState } from "react";
import { PostList } from "../components/PostList";

function getPosts(data) {
  return Array.isArray(data) ? data : data.posts || data.items || [];
}

export function FeedPage({ loadPosts, editPost, deletePost, loadImage, currentUserId, currentUsername }) {
  const [posts, setPosts] = useState([]);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(() => {
    setError("");
    setLoading(true);
    return loadPosts()
      .then((data) => {
        const rawPosts = getPosts(data);
        // Filter out logged-in user's own posts on feed
        const otherUserPosts = rawPosts.filter((post) => {
          const authorId = post.author_id ?? post.authorId ?? post.author?.id;
          if (authorId !== undefined && authorId !== null) {
            return String(authorId) !== String(currentUserId);
          }
          if (post.author_username && currentUsername) {
            return post.author_username !== currentUsername;
          }
          return true;
        });
        setPosts(otherUserPosts);
      })
      .catch((loadError) => setError(loadError.message))
      .finally(() => setLoading(false));
  }, [loadPosts, currentUserId, currentUsername]);

  useEffect(() => {
    refresh();
  }, [refresh]);

  async function handleEdit(id, data) {
    await editPost(id, data);
    await refresh();
  }

  async function handleDelete(id) {
    await deletePost(id);
    await refresh();
  }

  return (
    <section className="feed-page">
      <header className="feed-header">
        <div>
          <p className="eyebrow">Your daily archive</p>
          <h2>Community Feed</h2>
        </div>
        <span className="feed-status">Explore posts from others</span>
      </header>
      {error ? <p className="error-text">{error}</p> : null}
      {loading ? (
        <p className="post-loading">Loading community feed...</p>
      ) : posts.length === 0 ? (
        <div className="panel empty-feed-panel">
          <h3>No posts from other users yet</h3>
          <p className="muted">Posts created by you will appear on your profile. Check back later for community updates!</p>
        </div>
      ) : (
        <PostList posts={posts} currentUserId={currentUserId} loadImage={loadImage} onEdit={handleEdit} onDelete={handleDelete} />
      )}
    </section>
  );
}
