'use client'
import * as React from 'react';
import { Box, Table, TableContainer, TableHead, TableRow, TableCell, TableBody, Paper, Typography, TextField, InputAdornment, FormControl, IconButton, OutlinedInput, Stack } from '@mui/material';
import { Done, Edit, ErrorOutline, Search, Visibility } from '@mui/icons-material';
import UserEditDialog from './UserEditDialog';
import UserDisableDialog from './UserDisableDialog';

export default function AdminUsers() {
    const [users, setUsers] = React.useState([]);
    const [length, setLength] = React.useState(0);
    const [open, setOpen] = React.useState(false);
    const [open1, setOpen1] = React.useState(false);
    const [user, setUser] = React.useState({ USER_ID: 0, USERNAME: '', EMAIL: '', EMAIL_VALID: 0, CREATION_TIME: '', LAST_LOGIN: '' });

    React.useEffect(() => {
        const fetchUsers = async () => {
            const response = await fetch('/api/admin/users');
            if (response.ok) {
                const data = await response.json();
                setUsers(data);
            }
        }
        fetchUsers();
    }, []);

    React.useEffect(() => {
        const fetchUsersLength = async () => {
            const response = await fetch('/api/admin/users?length=true');
            if (response.ok) {
                const data = await response.json();
                setLength(data);
            }
        }
        fetchUsersLength();
    }, []);

    const handleSearch = async (event) => {
        const search = event.target.value;
        if (search.length > 0) {
            const response = await fetch(`/api/admin/users?search=${search}`);
            if (response.ok) {
                const data = await response.json();
                setUsers(data);
            }
        } else {
            const response = await fetch('/api/admin/users');
            if (response.ok) {
                const data = await response.json();
                setUsers(data);
            }
        }
    }

    const handleEdit = (user) => {
        setUser(user);
        setOpen(true);
    }

    const handleUserEdit = async (id, username, email, email_valid) => {
        const response = await fetch('/api/admin/users', {
            method: 'PUT',
            body: JSON.stringify({ id, username, email, email_valid }),
            headers: { 'Content-Type': 'application/json' }
        });

        if (response.ok) {
            window.location.reload();
            setOpen(false);
        }
    }

    const handleUserDisable = async (id, reason) => {
        const response = await fetch('/api/admin/users/disable', {
            method: 'POST',
            body: JSON.stringify({ id: id, reason: reason }),
            headers: { 'Content-Type': 'application/json' }
        });

        if (response.ok) {
            setOpen1(false);
        }
    }

    const handleEnable = async (id) => {
        const response = await fetch('/api/admin/users/enable', {
            method: 'POST',
            body: JSON.stringify({ id: id }),
            headers: { 'Content-Type': 'application/json' }
        });

        if (response.ok) {
            window.location.reload();
            setOpen(false);
        }
    }

    return (
        <>
            <Box sx={{ flexGrow: 1, textAlign: 'center', margin: '25px' }}>
                <Stack direction='row' sx={{ justifyContent: 'space-between' }}>
                    <Typography variant="h4" component="div">Utilisateurs</Typography>
                    <FormControl><TextField id="search" label="Rechercher" variant="outlined" onChange={handleSearch} sx={{ margin: '10px' }} /></FormControl>
                </Stack>
                <TableContainer component={Paper}>
                    <Table sx={{ minWidth: 650 }} aria-label="simple table">
                        <TableHead>
                            <TableRow>
                                <TableCell>UID</TableCell>
                                <TableCell>Nom d&apos;utilisateur</TableCell>
                                <TableCell>Email</TableCell>
                                <TableCell>Email validé ?</TableCell>
                                <TableCell>Activé ?</TableCell>
                                <TableCell>Date de création</TableCell>
                                <TableCell>Date de dernière connexion</TableCell>
                                <TableCell>Actions</TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {users.map((user) => (
                                <TableRow key={user.USER_ID}>
                                    <TableCell component="th" scope="row">
                                        {user.USER_ID}
                                    </TableCell>
                                    <TableCell>{user.USERNAME}</TableCell>
                                    <TableCell>{user.EMAIL}</TableCell>
                                    <TableCell align='center'>{user.EMAIL_VALID == 'True' ? <Done /> : <ErrorOutline />}</TableCell>
                                    <TableCell align='center'>{user.ENABLED == 'True' ? <Done /> : <ErrorOutline />}</TableCell>
                                    <TableCell>{new Date(user.CREATION_TIME).toLocaleString()}</TableCell>
                                    <TableCell>{new Date(user.LAST_LOGIN).toLocaleString()}</TableCell>
                                    <TableCell>
                                        <IconButton>
                                            <Visibility />
                                        </IconButton>
                                        <IconButton onClick={() => handleEdit(user)}>
                                            <Edit />
                                        </IconButton>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </TableContainer>
                <UserEditDialog open={open} user={user} handleClose={() => setOpen(false)} handleModify={handleUserEdit} handleDisable={(e) => setOpen1(true)} handleEnable={handleEnable} />
                <UserDisableDialog open={open1} user={user} handleClose={() => setOpen1(false)} handleDisable={handleUserDisable} />
            </Box>
        </>
    );
}