import { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaFileContract, FaPlus } from 'react-icons/fa';
import { getUserDataCache } from '../../../../../utils/userCache';
import { useMandates, useMandateOperations } from '../../../../../hooks/useAdminMandates';
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 mandates data
const createMandatesHook = () => {
    return () => {
        const { 
            data: mandates, 
            loading, 
            error, 
            refetch, 
            removeOptimistically, 
            updateOptimistically,
            attributes,
            permissions,
            pagination,
            fetchMandateById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = useMandates();
        const { 
            handleMandateDelete,
            handleMandateCreate,
            handleMandateUpdate,
            handleInlineUpdate,
            deletingMandates,
            editingMandates,
            deleteError,
            updateError
        } = useMandateOperations();
        
        const generatedColumns = attributes && attributes.length > 0 
            ? attributesToColumns(attributes)
            : undefined;
        
        // Handle single mandate deletion for FormGenerator
        const handleDeleteSingle = useCallback(async (mandate: any) => {
            const success = await handleMandateDelete(mandate.id);
            
            if (success) {
                refetch();
            }
        }, [handleMandateDelete, refetch]);

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

        return {
            data: mandates,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            // Operations
            handleDelete: handleMandateDelete,
            handleDeleteMultiple,
            handleMandateUpdate,
            handleInlineUpdate, // For inline boolean editing in table
            // FormGenerator specific handlers
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            // Loading states
            deletingMandates,
            editingMandates,
            // Error states
            deleteError,
            updateError,
            // Attributes and permissions for dynamic column/button generation
            attributes,
            permissions,
            pagination, // Pagination metadata from backend
            columns: generatedColumns,
            // Functions for EditActionButton
            fetchMandateById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded,
            // Entity type for EditActionButton
            entityType: 'Mandate',
            // Create operation for CreateButton
            handleMandateCreate
        };
    };
};

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