import React, { useContext } from 'react';
import axios from 'axios';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
//MUI
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import TablePagination from '@mui/material/TablePagination';
import Button from '@mui/material/Button';
import { AuthContext } from '../../../helpers/AuthContext';

export default function UserList() {
    const [listOfUsers, setListOfUsers] = useState([]);
    const { authState } = useContext(AuthContext);
    let navigate = useNavigate();

    //FIXME: needs headers to send user role
    useEffect(() => {
        axios.get(`/api/admin/user/activeUsers`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setListOfUsers(response.data);
        });
    }, []);

    const updateTable = () => {
        axios.get(`/api/admin/user/`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setListOfUsers(response.data);
        });
    }

    // const deleteUser = (id) => {
    //     axios.delete(`/api/admin/user/${id}`, {
    //     headers: {
    //         Authorization: 'Bearer ' + localStorage.getItem('accessToken')
    //     }
    // }
    //     ).then(() => {
    //         updateTable();
    //     });
    // };

    const deleteUser = (id) => {
        navigate(`/admin/users/delete/${id}`);
    };

    const editUser = (id) => {
        navigate(`/admin/users/update/${id}`);
    };

    const addUser = () => {
        navigate('/admin/users/create')
    }

    function createData(id, username, email, status, stripeUserId, firstName, lastName, userRoles) {
        let roles = userRoles.map(role => {
            return role.name.replace("ROLE_", "").toLowerCase();
        })
        return { id, username, email, status, stripeUserId, firstName, lastName, roles };
    }

    const rows = listOfUsers.map((value) => (
        createData(value.id, value.username, value.email, value.status, value.stripeUserId, value.firstName, value.lastName, value.roles)
    ))

    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(5);


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

    const handleChangeRowsPerPage = (event) => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };

    return (
        <div className='full-vh'>
            <div className='d-flex justify-content-center bg-grey '>
                <TableContainer
                    className='mt-5 w-75 shadow'
                    component={Paper}
                >
                    <h1 className='text-center mt-2'>List of Users</h1>
                    <Table className='shadow-sm mb-3' sx={{ minWidth: 850 }} aria-label="simple table">
                        <TableHead className='shadow-sm'>
                            <TableRow>
                                <TableCell align="right">ID</TableCell>
                                <TableCell align="right">Username</TableCell>
                                <TableCell align="right">Email</TableCell>
                                <TableCell align="right">Last Name</TableCell>
                                <TableCell align="right">First Name</TableCell>
                                <TableCell align="right">Stripe Id</TableCell>
                                <TableCell align="center">User Roles</TableCell>
                                <TableCell align="center">Account Status</TableCell>
                                <TableCell align="center">Actions</TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => (
                                <TableRow
                                    key={row.id}
                                    sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                                >
                                    <TableCell align="right">{row.id}</TableCell>
                                    <TableCell align="right">{row.username}</TableCell>
                                    <TableCell align="right">{row.email}</TableCell>
                                    <TableCell align="right">{row.lastName}</TableCell>
                                    <TableCell align="right">{row.firstName}</TableCell>
                                    <TableCell align="right">{row.stripeUserId}</TableCell>
                                    <TableCell align="right">{row.roles.join(", ")}</TableCell>
                                    <TableCell align="right">{row.status}</TableCell>
                                    <TableCell align="right">
                                        {row.id !== authState.id &&
                                            <>
                                                <Button className="bg-secondary text-white mx-2" onClick={() => { editUser(row.id) }}>Edit!</Button>
                                                <Button className="bg-danger text-white" onClick={() => { deleteUser(row.id) }}>Delete</Button>
                                            </>
                                        }
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                    <div className='d-flex flex-wrap justify-content-between'>
                        <Button
                            className="bg-info text-white m-2 align-middle"
                            onClick={addUser}
                        >
                            Add User
                        </Button>
                        <TablePagination
                            rowsPerPageOptions={[5, 10, 25]}
                            component="div"
                            count={rows.length}
                            rowsPerPage={rowsPerPage}
                            page={page}
                            onPageChange={handleChangePage}
                            onRowsPerPageChange={handleChangeRowsPerPage}
                        ></TablePagination>
                    </div>
                </TableContainer>
            </div>
        </div>

    )
}