import { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaShieldAlt, FaPlus } from 'react-icons/fa';
import { getUserDataCache } from '../../../../../utils/userCache';
import { useRbacRules, useRbacRuleOperations } from '../../../../../hooks/useAdminRbacRules';
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 rules data
const createRbacRulesHook = () => {
    return () => {
        const { 
            data: rbacRules, 
            loading, 
            error, 
            refetch, 
            removeOptimistically, 
            updateOptimistically,
            attributes,
            permissions,
            pagination,
            fetchRbacRuleById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = useRbacRules();
        const { 
            handleRbacRuleDelete,
            handleRbacRuleCreate,
            handleRbacRuleUpdate,
            handleInlineUpdate,
            deletingRbacRules,
            editingRbacRules,
            deleteError,
            updateError
        } = useRbacRuleOperations();
        
        const generatedColumns = attributes && attributes.length > 0 
            ? attributesToColumns(attributes)
            : undefined;
        
        // Handle single RBAC rule deletion for FormGenerator
        const handleDeleteSingle = useCallback(async (rule: any) => {
            const success = await handleRbacRuleDelete(rule.id);
            
            if (success) {
                refetch();
            }
        }, [handleRbacRuleDelete, refetch]);

        // Handle multiple RBAC rule deletion for FormGenerator
        const handleDeleteMultiple = useCallback(async (selectedRules: any[]) => {
            const ruleIds = selectedRules.map(rule => rule.id);
            const results = await Promise.all(
                ruleIds.map(id => handleRbacRuleDelete(id))
            );
            
            const allSuccessful = results.every((result: boolean) => result);
            
            if (allSuccessful) {
                refetch();
            }
        }, [handleRbacRuleDelete, refetch]);

        return {
            data: rbacRules,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            // Operations
            handleDelete: handleRbacRuleDelete,
            handleDeleteMultiple,
            handleRbacRuleUpdate,
            handleInlineUpdate, // For inline boolean editing in table
            // FormGenerator specific handlers
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            // Loading states
            deletingRbacRules,
            editingRbacRules,
            // Error states
            deleteError,
            updateError,
            // Attributes and permissions for dynamic column/button generation
            attributes,
            permissions,
            columns: generatedColumns,
            // Functions for EditActionButton
            fetchRbacRuleById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded,
            // Entity type for EditActionButton
            entityType: 'AccessRule',
            // Create operation for CreateButton
            handleRbacRuleCreate,
            // Pagination info for FormGeneratorTable
            pagination
        };
    };
};

export const rbacRulesPageData: GenericPageData = {
    id: 'admin-rbac-rules',
    path: 'admin/rbac-rules',
    name: 'admin.rbac-rules.title',
    description: 'admin.rbac-rules.description',
    
    // Parent page
    parentPath: 'admin',
    showInSidebar: true,
    
    // Visual
    icon: FaShieldAlt,
    title: 'admin.rbac-rules.title',
    subtitle: 'admin.rbac-rules.subtitle',
    
    // Header buttons
    headerButtons: [
        {
            id: 'add-rbac-rule',
            label: 'admin.rbac-rules.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-rules.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handleRbacRuleCreate',
                successMessage: 'admin.rbac-rules.create.success',
                errorMessage: 'admin.rbac-rules.create.error'
            }
        }
    ],
    
    // Content sections - using generic table approach
    content: [
        {
            id: 'rbac-rules-table',
            type: 'table',
            tableConfig: {
                hookFactory: createRbacRulesHook,
                // Columns are generated dynamically from attributes via hookData.columns
                actionButtons: [
                    {
                        type: 'edit',
                        title: 'admin.rbac-rules.action.edit',
                        idField: 'id',
                        nameField: 'id',
                        operationName: 'handleRbacRuleUpdate',
                        loadingStateName: 'editingRbacRules',
                        fetchItemFunctionName: 'fetchRbacRuleById',
                        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 RBAC rules' };
                        }
                    },
                    {
                        type: 'delete',
                        title: 'admin.rbac-rules.action.delete',
                        idField: 'id',
                        operationName: 'handleDelete',
                        loadingStateName: 'deletingRbacRules',
                        // 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 RBAC rules' };
                        }
                    }
                ],
                searchable: true,
                filterable: true,
                sortable: true,
                resizable: true,
                pagination: true,
                pageSize: 10,
                className: 'rbac-rules-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 Rules page activated');
    },
    onDeactivate: async () => {
        if (import.meta.env.DEV) console.log('RBAC Rules page deactivated');
    }
};
