import {Table, Button, Result, Typography} from "antd";
import {ControlOutlined} from "@ant-design/icons";
import LoadingIndicator from "../../Widgets/LoadingIndicator/LoadingIndicator.jsx";
import useAdminPage from "./useAdminPage.js";
import useAdminPageUI from "./useAdminPageUI.js";
import CreateUserModalForm from "./Components/CreateUserModalForm/CreateUserModalForm.jsx";
import UpdateUserModalForm from "../../Dummies/UpdateUserModalForm/UpdateUserModalForm.jsx";


const AdminPage = () => {
    const adminPageData = useAdminPage();
    const adminPageUI = useAdminPageUI();

    const columns = [
        {
            title: "ID",
            dataIndex: "id",
            key: "id",
        },
        {
            title: "Фамилия",
            dataIndex: "last_name",
            key: "lastName",
            sorter: (a, b) => a.last_name.localeCompare(b.last_name),
        },
        {
            title: "Имя",
            dataIndex: "first_name",
            key: "firstName",
            sorter: (a, b) => a.first_name.localeCompare(b.first_name),
        },
        {
            title: "Отчество",
            dataIndex: "patronymic",
            key: "patronymic",
        },
        {
            title: "Роль",
            dataIndex: ["role", "title"],
            key: "role",
            filters: adminPageData.roles.map(role => ({text: role.title, value: role.title})),
            onFilter: (value, record) => record.role.title === value,
        },
        {
            title: "Действия",
            key: "actions",
            render: (_, record) => (
                <Button type="link" onClick={() => adminPageUI.openEditModal(record)}>
                    Редактировать
                </Button>
            ),
        },
    ];


    if (adminPageData.isError) {
        return <Result status="500" title="500" subTitle="Произошла ошибка при загрузке данных"/>
    }

    return (
        <div style={adminPageUI.containerStyle}>
            {adminPageData.isLoading ? (
                <LoadingIndicator/>
            ) : (
                <>
                    <Typography.Title level={1}>
                        <ControlOutlined/> Панель администратора
                    </Typography.Title>
                    <Button
                        type="primary"
                        onClick={adminPageUI.openCreateModal}
                        style={{marginBottom: 16}}
                    >
                        Создать пользователя
                    </Button>
                    <Table
                        columns={columns}
                        dataSource={adminPageData.users}
                        rowKey="id"
                        pagination={{pageSize: 10}}
                        loading={adminPageData.isLoading}
                    />

                    <CreateUserModalForm/>
                    <UpdateUserModalForm/>
                </>
            )}
        </div>
    );
};

export default AdminPage;