import { useRoles, useUsers } from "../hooks/swrHooks"
import { IRole } from "../interfaces/role"
import { useEffect, useState } from "react"
import { CreateField } from "../interfaces/create"
import UserService from "../services/UserService"
import FormFields from "../components/FormFields"
import { Badge, Button, Flex, Loader, Modal, Pagination, ScrollAreaAutosize, Select, Table } from "@mantine/core"
import { useDisclosure } from "@mantine/hooks"
import { IUser } from "../interfaces/user"

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

    const { roles } = useRoles()

    const [roleOptions, setRoleOptions] = useState<{ label: string, value: string }[]>()

    useEffect(() => {
        if (Array.isArray(roles)) {
            setRoleOptions(roles.map((role: IRole) => ({ label: role.name, value: role.id.toString() })))
        }
    }, [roles])

    const [opened, { open, close }] = useDisclosure(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 = [
        { 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 (
            <Flex direction='column' align='flex-start' gap='sm' p='sm'>
                <Loader />
            </Flex>
        )
    }

    return (
        <ScrollAreaAutosize w={'100%'} h={'100%'} p='sm'>
            <Button onClick={open}>
                Добавить пользователя
            </Button>

            <Modal opened={opened} onClose={close} title="Регистрация пользователя" centered>
                <FormFields
                    fields={createFields}
                    submitHandler={UserService.createUser}
                />
            </Modal>

            {Array.isArray(roleOptions) &&
                <Table highlightOnHover>
                    <Table.Thead>
                        <Table.Tr>
                            {columns.map(column => (
                                <Table.Th key={column.field}>{column.headerName}</Table.Th>
                            ))}
                        </Table.Tr>
                    </Table.Thead>
                    <Table.Tbody>
                        {users.map((user: IUser) => (
                            <Table.Tr
                                key={user.id}
                            //bg={selectedRows.includes(element.position) ? 'var(--mantine-color-blue-light)' : undefined}
                            >
                                {columns.map(column => {
                                    if (column.field === 'is_active') {
                                        return (
                                            user.is_active ? (
                                                <Table.Td key={column.field}>
                                                    <Badge fullWidth variant="light">
                                                        Активен
                                                    </Badge>
                                                </Table.Td>
                                            ) : (
                                                <Table.Td key={column.field}>
                                                    <Badge color="gray" fullWidth variant="light">
                                                        Отключен
                                                    </Badge>
                                                </Table.Td>
                                            )
                                        )
                                    }
                                    else if (column.field === 'role_id') {
                                        return (
                                            <Table.Td key={column.field}>
                                                <Select
                                                    data={roleOptions}
                                                    defaultValue={user.role_id.toString()}
                                                    variant="unstyled"
                                                    allowDeselect={false}
                                                />
                                            </Table.Td>
                                        )
                                    }
                                    else return (
                                        <Table.Td key={column.field}>{user[column.field as keyof IUser]}</Table.Td>
                                    )
                                })}
                            </Table.Tr>
                        ))}
                    </Table.Tbody>
                </Table>
            }

            <Pagination total={10} />

            {/* <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={() => {
                }}
            /> */}
        </ScrollAreaAutosize>
    )
}