import { Box, Button, CircularProgress, Modal } 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 { CreateField } from "../interfaces/create"
import UserService from "../services/UserService"
import FormFields from "../components/FormFields"

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

    const { roles } = useRoles()

    const [open, setOpen] = useState(false)

    const createFields: CreateField[] = [
        { key: 'email', headerName: 'E-mail', type: 'string', required: true, defaultValue: '' },
        { key: 'login', headerName: 'Логин', type: 'string', required: true, defaultValue: '' },
        { key: 'phone', headerName: 'Телефон', type: 'string', required: false, defaultValue: '' },
        { key: 'name', headerName: 'Имя', type: 'string', required: true, defaultValue: '' },
        { key: 'surname', headerName: 'Фамилия', type: 'string', required: true, defaultValue: '' },
        { key: 'password', headerName: 'Пароль', type: 'string', required: true, defaultValue: '' },
    ]

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

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

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

            <Modal
                open={open}
                onClose={() => setOpen(false)}
            >
                <FormFields
                    fields={createFields}
                    submitHandler={UserService.createUser}
                    title="Создание пользователя"
                    sx={{
                        position: 'absolute' as 'absolute',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%, -50%)',
                        width: 400,
                        bgcolor: 'background.paper',
                        boxShadow: 24,
                        p: 4,
                    }}
                />
            </Modal>

            <DataGrid
                density="compact"
                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>
    )
}