import { Box, Button, CircularProgress } from "@mui/material"
import DataTable from "../components/DataTable"
import { GridColDef } from "@mui/x-data-grid"
import { useRoles, useUsers } from "../hooks/swrHooks"
import { Role } from "../interfaces/auth"
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: 'Роль',
            valueGetter: (value, row) => {
                if (roles) {
                    const roleName = roles.find((role: Role) => 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",
        }}
        >
            <Button onClick={() => setOpen(true)}>
                Добавить пользователя
            </Button>

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

            <DataTable rows={users} columns={columns} />
        </Box>
    )
}