import { Box, Button, CircularProgress } from "@mui/material"
import { DataGrid, GridColDef } from "@mui/x-data-grid"
import { useRoles, useUsers } from "../hooks/swrHooks"
import { IRole } from "../interfaces/role"
import { useState } from "react"
import CreateUserModal from "../components/modals/CreateUserModal"

export default function Users() {
    const { users, isError, isLoading } = useUsers()

    const { roles } = useRoles()

    const [open, setOpen] = useState(false)

    const columns: GridColDef[] = [
        { field: 'id', headerName: 'ID', type: "number", width: 70 },
        { field: 'email', headerName: 'Email', width: 130, editable: true },
        { field: 'login', headerName: 'Логин', width: 130, editable: true },
        { field: 'phone', headerName: 'Телефон', width: 90, editable: true },
        { field: 'name', headerName: 'Имя', width: 90, editable: true },
        { field: 'surname', headerName: 'Фамилия', width: 90, editable: true },
        { field: 'is_active', headerName: 'Активен', type: "boolean", width: 90, editable: true },
        {
            field: 'role_id',
            headerName: 'Роль',
            valueOptions: roles ? roles.map((role: IRole) => ({ label: role.name, value: role.id })) : [],
            type: 'singleSelect',
            width: 90,
            editable: true
        },
    ];

    if (isError) return <div>Произошла ошибка при получении данных.</div>
    if (isLoading) return <CircularProgress />

    return (
        <Box sx={{
            display: "flex",
            flexDirection: "column",
            alignItems: "flex-start",
            gap: "16px",
        }}
        >
            <Button onClick={() => setOpen(true)}>
                Добавить пользователя
            </Button>

            <CreateUserModal
                open={open}
                setOpen={setOpen}
            />

            <DataGrid
                autoHeight
                style={{ width: "100%" }}
                rows={users}
                columns={columns}
                initialState={{
                    pagination: {
                        paginationModel: { page: 0, pageSize: 10 },
                    },
                }}
                pageSizeOptions={[10, 20, 50, 100]}
                checkboxSelection
                disableRowSelectionOnClick

                processRowUpdate={(updatedRow) => {
                    return updatedRow
                }}

                onProcessRowUpdateError={() => {
                }}
            />
        </Box>
    )
}