import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setPosts } from "@/state";
import { apiFetch } from "../../state/api";
import { EmptyPostWidget, PostWidget } from "./PostWidget";

const PostsWidget = ({ userId, isProfile = false }) => {
  const dispatch = useDispatch();
  const posts = useSelector((state) => state.posts);

  const getPosts = async () => {
    const response = await apiFetch(`${import.meta.env.VITE_BASE_URL}/posts`, {
      method: "GET",
    });
    try {
      const data = await response.json();
      dispatch(setPosts({ posts: data }));
    } catch (err) {
      throw new Error("Server returned invalid response");
    }
  };

  const getUserPosts = async () => {
    const response = await apiFetch(`${import.meta.env.VITE_BASE_URL}/posts/${userId}/posts`, {
      method: "GET",
    });
    try {
      const data = await response.json();
      dispatch(setPosts({ posts: data }));
    } catch (err) {
      throw new Error("Server returned invalid response");
    }
  };

  useEffect(() => {
    if (isProfile) {
      getUserPosts();
    } else {
      getPosts();
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  if (!Array.isArray(posts) || posts.length <= 0) {
    return (
      <>
        <EmptyPostWidget />
      </>
    );
  }

  return (
    <>
      {[...posts]
        .reverse()
        .map(
          ({
            _id,
            userId,
            firstName,
            lastName,
            description,
            location,
            pictureContentType,
            userPicture,
            likes,
            comments,
          }) => (
            <PostWidget
              key={_id}
              postId={_id}
              postUserId={userId}
              name={`${firstName} ${lastName}`}
              description={description}
              location={location}
              picturePath={pictureContentType ? _id : null}
              userPicturePath={userPicture}
              likes={likes}
              comments={comments}
            />
          ),
        )}
    </>
  );
};

export default PostsWidget;
