import React, { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaUsers, FaPlus } from 'react-icons/fa';
import { IoMailOutline } from 'react-icons/io5';
import { useOrgUsers, useUserOperations } from '../../../../../hooks/useUsers';
import { getUserDataCache } from '../../../../../utils/userCache';

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

// Hook factory function for users data
const createUsersHook = () => {
    return () => {
        const { 
            data: users, 
            loading, 
            error, 
            refetch, 
            removeOptimistically, 
            updateOptimistically,
            attributes,
            permissions,
            pagination,
            fetchUserById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = useOrgUsers();
        const { 
            handleUserDelete,
            handleUserCreate,
            handleUserUpdate,
            handleInlineUpdate,
            handleSendPasswordLink,
            deletingUsers,
            editingUsers,
            sendingPasswordLink,
            creatingUser,
            deleteError,
            createError,
            updateError,
            passwordLinkError
        } = useUserOperations();
        
        const generatedColumns = attributes && attributes.length > 0 
            ? attributesToColumns(attributes)
            : undefined;
        
        // Wrapped create handler that adds mandateId from currentUser cache
        const wrappedHandleUserCreate = useCallback(async (formData: any) => {
            return await handleUserCreate(formData);
        }, [handleUserCreate]);
        
        // Handle single user deletion for FormGenerator
        const handleDeleteSingle = useCallback(async (user: any) => {
            const success = await handleUserDelete(user.id);
            
            if (success) {
                refetch();
            }
        }, [handleUserDelete, refetch]);

        // Handle multiple user deletion for FormGenerator
        const handleDeleteMultiple = useCallback(async (selectedUsers: any[]) => {
            const userIds = selectedUsers.map(user => user.id);
            const results = await Promise.all(
                userIds.map(id => handleUserDelete(id))
            );
            
            const allSuccessful = results.every(result => result);
            
            if (allSuccessful) {
                refetch();
            }
        }, [handleUserDelete, refetch]);

        return {
            data: users,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            // Operations
            handleDelete: handleUserDelete,
            handleDeleteMultiple,
            handleUserCreate: wrappedHandleUserCreate,
            handleUserUpdate,
            handleInlineUpdate, // For inline boolean editing in table
            handleSendPasswordLink, // Send password setup link to user
            // FormGenerator specific handlers
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            // Loading states
            deletingUsers,
            editingUsers,
            sendingPasswordLink,
            creatingUser,
            // Error states
            deleteError,
            createError,
            updateError,
            passwordLinkError,
            // Attributes and permissions for dynamic column/button generation
            attributes,
            permissions,
            pagination, // Pagination metadata from backend
            columns: generatedColumns,
            // Functions for EditActionButton
            fetchUserById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        };
    };
};

export const teamMembersPageData: GenericPageData = {
    id: 'admin-team-members',
    path: 'admin/team-members',
    name: 'team-members.title',
    description: 'team-members.description',
    
    // Parent page
    parentPath: 'admin',
    
    // Visual
    icon: FaUsers,
    title: 'team-members.title',
    subtitle: 'team-members.subtitle',
    
    // Header buttons
    headerButtons: [
        {
            id: 'add-member',
            label: 'team-members.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: 'team-members.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handleUserCreate',
                successMessage: 'team-members.create.success',
                errorMessage: 'team-members.create.error'
            }
        }
    ],
    
    // Content sections - using generic table approach
    content: [
        {
            id: 'users-table',
            type: 'table',
            tableConfig: {
                hookFactory: createUsersHook,
                // Columns are generated dynamically from attributes via hookData.columns
                // Standard action buttons (built-in: edit, delete, view, copy)
                actionButtons: [
                    {
                        type: 'edit',
                        title: 'team-members.action.edit',
                        idField: 'id',
                        nameField: 'username',
                        operationName: 'handleUserUpdate',
                        loadingStateName: 'editingUsers',
                        fetchItemFunctionName: 'fetchUserById',
                        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 users' };
                        }
                    },
                    {
                        type: 'delete',
                        title: 'team-members.action.delete',
                        idField: 'id',
                        operationName: 'handleDelete',
                        loadingStateName: 'deletingUsers',
                        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 users' };
                        }
                    }
                ],
                // Custom action buttons (entity-specific)
                customActions: [
                    {
                        id: 'sendPasswordLink',
                        icon: React.createElement(IoMailOutline),
                        title: 'team-members.action.sendPasswordLink',
                        onClick: async (row: any, hookData: any) => {
                            if (hookData?.handleSendPasswordLink) {
                                await hookData.handleSendPasswordLink(row.id);
                            }
                        },
                        // Only show for users with local authentication (not msft/google)
                        visible: (row: any) => row.authenticationAuthority === 'local',
                        disabled: (_row: any, hookData: any) => {
                            if (!hookData?.permissions) return { disabled: false, message: '' };
                            const hasUpdate = hookData.permissions.update !== 'n' && hookData.permissions.view;
                            return { disabled: !hasUpdate, message: 'No permission to send password link' };
                        },
                        loading: (row: any, hookData: any) => hookData?.sendingPasswordLink?.has(row.id) || false
                    }
                ],
                searchable: true,
                filterable: true,
                sortable: true,
                resizable: true,
                pagination: true,
                pageSize: 10,
                className: 'users-table'
            }
        }
    ],
    
    // Page behavior
    persistent: false,
    preload: false,
    preserveState: true, // Keep page mounted and prevent refetching
    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('Team Members activated');
    },
    onLoad: async () => {
        if (import.meta.env.DEV) console.log('Team Members loaded - can initialize users list here');
    },
    onUnload: async () => {
        if (import.meta.env.DEV) console.log('Team Members unloaded - cleanup users references');
    }
};

