import { Box, Typography, useTheme } from "@mui/material";
import Friend from "@/components/Friend";
import WidgetWrapper from "@/components/WidgetWrapper";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setFriends } from "@/state";
import { apiFetch } from "../../state/api";
// import { getToken } from "../../state/token";

const FriendListWidget = ({ userId }) => {
  const dispatch = useDispatch();
  const { palette } = useTheme();

  const friends = useSelector((state) => state.user?.friends || []);

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

  useEffect(() => {
    getFriends();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <WidgetWrapper>
      <Typography color={palette.neutral.dark} variant="h5" fontWeight="500" sx={{ mb: "1.5rem" }}>
        Freunde
      </Typography>
      <Box display="flex" flexDirection="column" gap="1.5rem">
        {friends.map((friend) => (
          <Friend
            key={friend._id}
            friendId={friend._id}
            name={`${friend.firstName} ${friend.lastName}`}
            subtitle={friend.occupation}
            userPicturePath={friend.picture}
          />
        ))}
      </Box>
    </WidgetWrapper>
  );
};

export default FriendListWidget;
