import { Box, useMediaQuery } from "@mui/material";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import Navbar from "@/scenes/navbar";
import FriendListWidget from "@/scenes/widgets/FriendListWidget";
import MyPostWidget from "@/scenes/widgets/MyPostWidget";
import PostsWidget from "@/scenes/widgets/PostsWidget";
import UserWidget from "@/scenes/widgets/UserWidget";
import { apiFetch } from "../../state/api";
import { useSelector } from "react-redux";

const ProfilePage = () => {
  const [user, setUser] = useState(null);
  const { userId } = useParams();
  const isNonMobileScreens = useMediaQuery("(min-width:1000px)");

  const loggedInUser = useSelector((state) => state.user);

  const [error, setError] = useState(null);
  useEffect(() => {
    const getUser = async () => {
      try {
        const response = await apiFetch(`${import.meta.env.VITE_BASE_URL}/users/${userId}`, {
          method: "GET",
        });

        const data = await response.json();
        setUser(data);
      } catch (err) {
        setError("Server returned invalid response");
      }
    };

    getUser();
  }, [userId]);
  if (error) {
    return <h3>Error fetching users: {error}</h3>;
  }

  if (!user) return null;
  return (
    <Box>
      <Navbar />
      <Box
        width="100%"
        padding="2rem 6%"
        display={isNonMobileScreens ? "flex" : "block"}
        gap="2rem"
        justifyContent="center"
      >
        <Box flexBasis={isNonMobileScreens ? "26%" : undefined}>
          <UserWidget userId={userId} picturePath={user.picture} user={user} />
          <Box m="2rem 0" />
          <FriendListWidget userId={userId} />
        </Box>
        <Box
          flexBasis={isNonMobileScreens ? "42%" : undefined}
          mt={isNonMobileScreens ? undefined : "2rem"}
        >
          <MyPostWidget picturePath={loggedInUser.picture} />
          <Box m="2rem 0" />
          <PostsWidget userId={loggedInUser._id} isProfile />
        </Box>
      </Box>
    </Box>
  );
};

export default ProfilePage;
