import { connect } from "react-redux";
import { useEffect, useState } from "react";
import { Box, Link } from "@mui/material";
import { Users, StyledUser } from "./user-draw.module";
import { actionGetUsers } from "../../actions";

const User = ({ getUsers }) => {
  const [skip, setSkip] = useState(0);
  const [users, setUsers] = useState([]);

  const scrollHandler = async () => {
    const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
    if (scrollTop + clientHeight >= scrollHeight) {
      const newUsers = (await getUsers(skip + 20)).data.UserFind;
      if (skip < newUsers.length + 20) {
        setUsers((prevUsers) => prevUsers.concat(newUsers.slice(0, 20)));
        setSkip((prevSkip) => prevSkip + 20);
      }
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      const usersData = (await getUsers()).data.UserFind;
      setUsers(usersData.slice(0, 20));
      document.addEventListener("scroll", scrollHandler);
    };

    fetchData();

    return () => {
      document.removeEventListener("scroll", scrollHandler);
    };
  }, []);

  return (
      <Box component="main">
        <Users className="users">
          {users.map((user) => (
              <StyledUser key={user._id} className="user">
                <Box className="profile-pic">
                  <Link href={`user/${user?._id}`}>
                    <Box
                        component="img"
                        src={
                          (user.avatar?.url)
                              ? user.avatar?.url  : "https://w7.pngwing.com/pngs/336/946/png-transparent-avatar-user-medicine-surgery-patient-avatar-face-heroes-head.png"
                        }
                        alt="profile-avatar"
                    />
                  </Link>
                </Box>
                <Link href={`user/${user._id}`}>
                  <Box component="p" className="username">
                    {user?.login}
                  </Box>
                </Link>
              </StyledUser>
          ))}
        </Users>
      </Box>
  );
};

export const ConnectUsersDraw = connect(
    (state) => ({
      users: state?.promise?.allUsers?.payload?.data?.UserFind,
    }),
    { getUsers: actionGetUsers }
)(User);
