import { PersonAddOutlined, PersonRemoveOutlined } from "@mui/icons-material";
import { Box, IconButton, Typography, useTheme } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { setFriends } from "@/state";
import FlexBetween from "./FlexBetween";
import UserImage from "./UserImage";
import { apiFetch } from "../state/api";

const Friend = ({ friendId, name, subtitle, userPicturePath }) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { _id } = useSelector((state) => state.user);
  const friends = useSelector((state) => state.user?.friends);

  const { palette } = useTheme();
  const primaryLight = palette.primary.light;
  const primaryDark = palette.primary.dark;
  const main = palette.neutral.main;
  const medium = palette.neutral.medium;

  let isFriend = false;
  try {
    // isFriend = friends.find((friend) => friend._id === friendId);
    isFriend = friends.some((friend) => friend._id === friendId);
  } catch (err) {
    console.log("friend error: " + err);
  }

  const patchFriend = async () => {
    if (_id === friendId) {
      console.log("You cannot add/remove yourself");
      return;
    }

    const response = await apiFetch(`${import.meta.env.VITE_BASE_URL}/users/${_id}/${friendId}`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
      },
    });
    try {
      const data = await response.json();
      dispatch(setFriends({ friends: data }));
    } catch (err) {
      throw new Error("friend not found");
    }
  };

  return (
    <FlexBetween>
      <FlexBetween gap="1rem">
        <UserImage image={userPicturePath} size="55px" />
        <Box
          onClick={() => {
            navigate(`/profile/${friendId}`);
            // navigate(0);
          }}
        >
          <Typography
            color={main}
            variant="h5"
            fontWeight="500"
            sx={{
              "&:hover": {
                color: palette.primary.light,
                cursor: "pointer",
              },
            }}
          >
            {name}
          </Typography>
          <Typography color={medium} fontSize="0.75rem">
            {subtitle}
          </Typography>
        </Box>
      </FlexBetween>
      <IconButton onClick={() => patchFriend()} sx={{ backgroundColor: primaryLight, p: "0.6rem" }}>
        {isFriend ? (
          <PersonRemoveOutlined sx={{ color: primaryDark }} />
        ) : (
          <PersonAddOutlined sx={{ color: primaryDark }} />
        )}
      </IconButton>
    </FlexBetween>
  );
};

export default Friend;
