import { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaUserTag, FaPlus } from 'react-icons/fa';
import { useTrusteeRoles, useTrusteeRoleOperations } from '../../../../../hooks/useTrustee';

const attributesToColumns = (attributes: any[]) => {
    return attributes.map(attr => {
        const isDateField = attr.type === 'date' || attr.type === 'timestamp' ||
            /(date|Date|timestamp|Timestamp|created|Created|updated|Updated|at|At)$/i.test(attr.name);

        return {
            key: attr.name,
            label: attr.label || attr.name,
            type: attr.type || 'string',
            width: attr.width || 200,
            minWidth: attr.minWidth || 100,
            maxWidth: attr.maxWidth || 400,
            sortable: attr.sortable !== false,
            filterable: isDateField ? false : (attr.filterable !== false),
            searchable: attr.searchable !== false,
            filterOptions: attr.filterOptions
        };
    });
};

const createRolesHook = () => {
    return () => {
        const {
            items: roles,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            attributes,
            permissions,
            fetchById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = useTrusteeRoles();
        const {
            handleDelete,
            handleCreate,
            handleUpdate,
            deletingItems,
            creatingItem,
            deleteError,
            createError,
            updateError
        } = useTrusteeRoleOperations();

        const generatedColumns = attributes && attributes.length > 0
            ? attributesToColumns(attributes)
            : undefined;

        const wrappedHandleCreate = useCallback(async (formData: any) => {
            return await handleCreate(formData);
        }, [handleCreate]);

        const handleDeleteSingle = useCallback(async (item: any) => {
            const success = await handleDelete(item.id);
            if (success) {
                refetch();
            }
        }, [handleDelete, refetch]);

        const handleDeleteMultiple = useCallback(async (selectedItems: any[]) => {
            const ids = selectedItems.map(item => item.id);
            const results = await Promise.all(ids.map(id => handleDelete(id)));
            const allSuccessful = results.every(result => result);
            if (allSuccessful) {
                refetch();
            }
        }, [handleDelete, refetch]);

        return {
            data: roles,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            handleDelete,
            handleDeleteMultiple,
            handleCreate: wrappedHandleCreate,
            handleUpdate,
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            deletingItems,
            creatingItem,
            deleteError,
            createError,
            updateError,
            attributes,
            permissions,
            columns: generatedColumns,
            fetchById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        };
    };
};

export const trusteeRolesPageData: GenericPageData = {
    id: 'trustee-roles',
    path: 'trustee/roles',
    name: 'trustee.roles.title',
    description: 'trustee.roles.description',
    parentPath: 'trustee',

    icon: FaUserTag,
    title: 'trustee.roles.title',
    subtitle: 'trustee.roles.subtitle',

    headerButtons: [
        {
            id: 'new-role',
            label: 'trustee.roles.new_button',
            icon: FaPlus,
            variant: 'primary',
            formConfig: {
                fields: [
                    {
                        key: 'id',
                        label: 'trustee.roles.field.id',
                        type: 'string',
                        required: true,
                        placeholder: 'trustee.roles.field.id_placeholder'
                    },
                    {
                        key: 'desc',
                        label: 'trustee.roles.field.desc',
                        type: 'textarea',
                        required: true,
                        placeholder: 'trustee.roles.field.desc_placeholder',
                        minRows: 3,
                        maxRows: 6
                    }
                ],
                popupTitle: 'trustee.roles.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handleCreate',
                successMessage: 'trustee.roles.create.success',
                errorMessage: 'trustee.roles.create.error'
            }
        }
    ],

    content: [
        {
            id: 'roles-table',
            type: 'table',
            tableConfig: {
                hookFactory: createRolesHook,
                actionButtons: [
                    {
                        type: 'edit',
                        title: 'trustee.roles.action.edit',
                        idField: 'id',
                        nameField: 'id',
                        operationName: 'handleUpdate',
                        loadingStateName: 'updatingItems',
                        fetchItemFunctionName: 'fetchById',
                        disabled: (hookData: any) => {
                            if (!hookData?.permissions) return { disabled: false };
                            const hasUpdate = hookData.permissions.update !== 'n' && hookData.permissions.view;
                            return { disabled: !hasUpdate, message: 'No permission to edit roles' };
                        }
                    },
                    {
                        type: 'delete',
                        title: 'trustee.roles.action.delete',
                        idField: 'id',
                        operationName: 'handleDelete',
                        loadingStateName: 'deletingItems',
                        disabled: (hookData: any) => {
                            if (!hookData?.permissions) return { disabled: false };
                            const hasDelete = hookData.permissions.delete !== 'n' && hookData.permissions.view;
                            return { disabled: !hasDelete, message: 'No permission to delete roles' };
                        }
                    }
                ],
                searchable: true,
                filterable: true,
                sortable: true,
                resizable: true,
                pagination: true,
                pageSize: 10,
                className: 'trustee-roles-table'
            }
        }
    ],

    persistent: false,
    preload: false,
    preserveState: true,
    moduleEnabled: true,

    onActivate: async () => {
        if (import.meta.env.DEV) console.log('Trustee Roles activated');
    },
    onLoad: async () => {
        if (import.meta.env.DEV) console.log('Trustee Roles loaded');
    },
    onUnload: async () => {
        if (import.meta.env.DEV) console.log('Trustee Roles unloaded');
    }
};
