import { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaUserShield, FaPlus } from 'react-icons/fa';
import { getUserDataCache } from '../../../../../utils/userCache';
import { useRbacRoles, useRbacRoleOperations } from '../../../../../hooks/useAdminRbacRoles';
import { isDateTimeType, type AttributeType } from '../../../../../utils/attributeTypeMapper';
import type { AttributeDefinition } from '../../../../../api/attributesApi';

// Helper function to convert attribute definitions to column config
const attributesToColumns = (attributes: AttributeDefinition[]) => {
    return attributes.map(attr => {
        // Use attributeTypeMapper to check if this is a date/timestamp field - disable filtering for these
        const isDateField = isDateTimeType(attr.type as AttributeType);
        
        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,
            // Disable filtering for date/timestamp fields
            filterable: isDateField ? false : (attr.filterable !== false),
            searchable: attr.searchable !== false,
            filterOptions: attr.filterOptions
        };
    });
};

// Hook factory function for rbac roles data
const createRbacRolesHook = () => {
    return () => {
        const { 
            data: roles, 
            loading, 
            error, 
            refetch, 
            removeOptimistically, 
            updateOptimistically,
            attributes,
            permissions,
            pagination,
            fetchRoleById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = useRbacRoles();
        const { 
            handleRoleDelete,
            handleRoleCreate,
            handleRoleUpdate,
            deletingRoles,
            editingRoles,
            deleteError,
            updateError
        } = useRbacRoleOperations();
        
        const generatedColumns = attributes && attributes.length > 0 
            ? attributesToColumns(attributes)
            : undefined;
        
        // Handle single role deletion for FormGenerator
        const handleDeleteSingle = useCallback(async (role: any) => {
            const success = await handleRoleDelete(role.id);
            
            if (success) {
                refetch();
            }
        }, [handleRoleDelete, refetch]);

        // Handle multiple role deletion for FormGenerator
        const handleDeleteMultiple = useCallback(async (selectedRoles: any[]) => {
            const roleIds = selectedRoles.map(role => role.id);
            const results = await Promise.all(
                roleIds.map(id => handleRoleDelete(id))
            );
            
            const allSuccessful = results.every((result: boolean) => result);
            
            if (allSuccessful) {
                refetch();
            }
        }, [handleRoleDelete, refetch]);

        // Wrapper for create operation that refetches after success
        const handleRoleCreateWithRefetch = useCallback(async (roleData: any) => {
            const result = await handleRoleCreate(roleData);
            if (result?.success) {
                await refetch();
            }
            return result;
        }, [handleRoleCreate, refetch]);

        return {
            data: roles,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            // Operations
            handleDelete: handleRoleDelete,
            handleDeleteMultiple,
            handleRoleUpdate,
            // FormGenerator specific handlers
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            // Loading states
            deletingRoles,
            editingRoles,
            // Error states
            deleteError,
            updateError,
            // Attributes and permissions for dynamic column/button generation
            attributes,
            permissions,
            pagination, // Pagination metadata from backend
            columns: generatedColumns,
            // Functions for EditActionButton
            fetchRoleById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded,
            // Entity type for EditActionButton
            entityType: 'Role',
            // Create operation for CreateButton (with refetch)
            handleRoleCreate: handleRoleCreateWithRefetch
        };
    };
};

export const rbacRolePageData: GenericPageData = {
    id: 'admin-rbac-role',
    path: 'admin/rbac-role',
    name: 'admin.rbac-role.title',
    description: 'admin.rbac-role.description',
    
    // Parent page
    parentPath: 'admin',
    showInSidebar: true,
    
    // Visual
    icon: FaUserShield,
    title: 'admin.rbac-role.title',
    subtitle: 'admin.rbac-role.subtitle',
    
    // Header buttons
    headerButtons: [
        {
            id: 'add-role',
            label: 'admin.rbac-role.new_button',
            variant: 'primary',
            size: 'md',
            icon: FaPlus,
            formConfig: {
                // Fields will be generated dynamically from attributes via generateCreateFieldsFromAttributes
                // PageRenderer will use generateCreateFieldsFromAttributes if available, otherwise generateEditFieldsFromAttributes
                fields: [], // Empty array - fields will be generated dynamically from attributes
                popupTitle: 'admin.rbac-role.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handleRoleCreate',
                successMessage: 'admin.rbac-role.create.success',
                errorMessage: 'admin.rbac-role.create.error'
            }
        }
    ],
    
    // Content sections - using generic table approach
    content: [
        {
            id: 'rbac-role-description',
            type: 'paragraph',
            content: 'admin.rbac-role.description_text'
        },
        {
            id: 'rbac-roles-table',
            type: 'table',
            tableConfig: {
                hookFactory: createRbacRolesHook,
                // Columns are generated dynamically from attributes via hookData.columns
                actionButtons: [
                    {
                        type: 'edit',
                        title: 'admin.rbac-role.action.edit',
                        idField: 'id',
                        nameField: 'id',
                        operationName: 'handleRoleUpdate',
                        loadingStateName: 'editingRoles',
                        fetchItemFunctionName: 'fetchRoleById',
                        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: 'admin.rbac-role.action.delete',
                        idField: 'id',
                        operationName: 'handleDelete',
                        loadingStateName: 'deletingRoles',
                        // Only show if user has delete permission (permissions.delete !== 'n')
                        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: 'rbac-roles-table'
            }
        }
    ],
    
    // Page behavior
    persistent: false,
    preload: false,
    preserveState: true,
    moduleEnabled: true,
    
    // Privilege checker: only allow sysadmin role
    privilegeChecker: async () => {
        const userData = getUserDataCache();
        const roleLabels = Array.isArray(userData?.roleLabels) ? userData.roleLabels : [];
        // Only allow access if user has "sysadmin" role
        return roleLabels.includes('sysadmin');
    },
    
    // Lifecycle hooks
    onActivate: async () => {
        if (import.meta.env.DEV) console.log('RBAC Role page activated');
    },
    onDeactivate: async () => {
        if (import.meta.env.DEV) console.log('RBAC Role page deactivated');
    }
};
