import { Paper, Table, TableBody, TableCell, TableContainer, TableHead, TablePagination, TableRow } from '@mui/material';
import React, { useEffect, useState } from 'react';
import { useGetUsersQuery } from '../../api/api';
import Loader from '../../components/Loader';
import { getDateString } from '../../functions/getDataString';

function Users() {
  const { data, isFetching } = useGetUsersQuery();
  const [sortedData, setSortedData] = useState();
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  useEffect(() => {
    if (data) {
      console.log(data?.UserFind);
      const dataForSort = [...data?.UserFind];
      setSortedData(dataForSort?.sort((a, b) => b.createdAt - a.createdAt));
    }
  }, [data]);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };
  return (
    <>
      {isFetching ? <Loader /> :
        <Paper>
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>ID</TableCell>
                  <TableCell>Login</TableCell>
                  <TableCell>Created at</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {sortedData?.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)?.map(user =>
                  <TableRow key={user._id}>
                    <TableCell>{user._id}</TableCell>
                    <TableCell>{user.login}</TableCell>
                    <TableCell>{getDateString(user.createdAt)}</TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
          <TablePagination
            rowsPerPageOptions={[10, 20, 30]}
            component="div"
            count={sortedData?.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage} />
        </Paper>
      }
    </>

  )
}

export default Users;