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"

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

    const { roles } = useRoles()

    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: 'Роль',
            valueGetter: (value) => {
                if (roles) {
                    const roleName = roles.find((role: IRole) => role.id === value).name
                    return roleName
                } else {
                    return value
                }
            },
            width: 90
        },
    ];

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

    return (
        <Box sx={{
            display: "flex",
            flexDirection: "column",
            alignItems: "flex-start",
            gap: "16px",
        }}
        >
            <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>
    )
}