import Add from "@mui/icons-material/Add";
import { DataState } from "@/shared/ui/DataState.jsx";
import {
    AdminActionIconButton,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
} from "@/shared/ui/AdminListLayout.jsx";
import { RoleFormDrawer } from "@/features/roles/components/RoleFormDrawer.jsx";
import { RoleTable } from "@/features/roles/components/RoleTable.jsx";
import { useRolesPage } from "@/features/roles/hooks/useRolesPage.js";

export function RoleManagementPage() {
    const page = useRolesPage();

    return (
        <>
            <AdminListPage>
                <AdminListToolbar
                    actions={
                        page.abilities.canCreate ? (
                            <AdminActionIconButton label="新增角色" primary onClick={page.openCreate}>
                                <Add fontSize="small" />
                            </AdminActionIconButton>
                        ) : null
                    }
                />

                <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                    <AdminListBody>
                        <RoleTable
                            abilities={page.abilities}
                            query={page.query}
                            onEdit={page.openEdit}
                            onQueryChange={page.changeQuery}
                            onRemove={page.remove}
                            roles={page.roles}
                        />
                        <div className="pagination-bar">
                            <span>{page.roles.length} 条</span>
                        </div>
                    </AdminListBody>
                </DataState>
            </AdminListPage>

            <RoleFormDrawer
                abilities={page.abilities}
                editingRole={page.editingRole}
                form={page.form}
                onClose={page.closeDrawer}
                onSubmit={page.submit}
                onTogglePermissionGroup={page.togglePermissionGroup}
                onTogglePermission={page.togglePermission}
                open={page.drawerOpen}
                permissionGroups={page.permissionGroups}
                setForm={page.setForm}
            />
        </>
    );
}
