import { useCallback } from 'react';
import { GenericPageData } from '../../pageInterface';
import { FaLightbulb, FaPlus } from 'react-icons/fa';
import { usePrompts, usePromptOperations } from '../../../../hooks/usePrompts';

// 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 prompts data
const createPromptsHook = () => {
    return () => {
        const { 
            prompts, 
            loading, 
            error, 
            refetch, 
            removeOptimistically, 
            updateOptimistically,
            attributes,
            permissions,
            pagination,
            fetchPromptById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = usePrompts();
        const { 
            handlePromptDelete,
            handlePromptCreate,
            handlePromptUpdate,
            handleInlineUpdate,
            deletingPrompts,
            creatingPrompt,
            deleteError,
            createError,
            updateError
        } = usePromptOperations();
        
        const generatedColumns = attributes && attributes.length > 0 
            ? attributesToColumns(attributes)
            : undefined;
        
        // Wrapped create handler that adds mandateId from currentUser cache
        const wrappedHandlePromptCreate = useCallback(async (formData: { name: string; content: string }) => {
            // mandateId is retrieved inside handlePromptCreate from sessionStorage cache
            return await handlePromptCreate({ name: formData.name, content: formData.content });
        }, [handlePromptCreate]);
        
        // Handle single prompt deletion for FormGenerator
        const handleDeleteSingle = useCallback(async (prompt: any) => {
            const success = await handlePromptDelete(prompt.id);
            
            if (success) {
                refetch();
            }
        }, [handlePromptDelete, refetch]);

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

        return {
            data: prompts,
            loading,
            error,
            refetch,
            removeOptimistically, // Expose optimistic removal (generic name for DeleteActionButton)
            updateOptimistically, // Expose optimistic update for EditActionButton
            // Operations
            handleDelete: handlePromptDelete,
            handleDeleteMultiple,
            handlePromptCreate: wrappedHandlePromptCreate, // Use wrapped version
            handlePromptUpdate,
            handleInlineUpdate, // For inline boolean editing in table
            // FormGenerator specific handlers
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            // Loading states
            deletingPrompts,
            creatingPrompt,
            // Error states
            deleteError,
            createError,
            updateError,
            // Attributes and permissions for dynamic column/button generation
            attributes,
            permissions,
            pagination, // Pagination metadata from backend
            columns: generatedColumns, // Return generated columns
            // Functions for EditActionButton
            fetchPromptById, // Fetch single prompt by ID
            generateEditFieldsFromAttributes, // Generate edit fields from attributes
            generateCreateFieldsFromAttributes, // Generate create fields from attributes
            ensureAttributesLoaded // Generic function to ensure attributes are loaded
        };
    };
};


export const promptsPageData: GenericPageData = {
    id: 'basedata-prompts',
    path: 'basedata/prompts',
    name: 'prompts.title',
    description: 'prompts.description',
    
    // Parent page - now under 'basedata' group (formerly 'administration')
    parentPath: 'basedata',
    
    // Visual
    icon: FaLightbulb,
    title: 'prompts.title',
    subtitle: 'prompts.subtitle',
    
    // Header buttons
    headerButtons: [
        {
            id: 'new-prompt',
            label: 'prompts.new_button',
            icon: FaPlus,
            variant: 'primary',
            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: 'prompts.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handlePromptCreate',
                successMessage: 'prompts.create.success',
                errorMessage: 'prompts.create.error'
            }
        }
    ],
    
    // Content sections - using generic table approach
    content: [
        {
            id: 'prompts-table',
            type: 'table',
            tableConfig: {
                hookFactory: createPromptsHook,
                // Columns are generated dynamically from attributes via hookData.columns
                actionButtons: [
                    {
                        type: 'play',
                        title: 'prompts.action.start',
                        idField: 'id',
                        nameField: 'name',
                        contentField: 'content',
                        mode: 'prompt',
                        navigateTo: 'start/dashboard',
                        // Only show if user has read permission (permissions.read !== 'n')
                        disabled: (hookData: any) => {
                            if (!hookData?.permissions) return { disabled: false };
                            const hasRead = hookData.permissions.read !== 'n' && hookData.permissions.view;
                            return { disabled: !hasRead, message: 'No permission to start prompts' };
                        }
                    },
                    {
                        type: 'edit',
                        title: 'prompts.action.edit',
                        idField: 'id',
                        nameField: 'name',
                        operationName: 'handlePromptUpdate',
                        loadingStateName: 'updatingPrompts',
                        fetchItemFunctionName: 'fetchPromptById',
                        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 prompts' };
                        }
                    },
                    {
                        type: 'delete',
                        title: 'prompts.action.delete',
                        idField: 'id',
                        operationName: 'handleDelete',
                        loadingStateName: 'deletingPrompts', // Entity-specific loading state
                        // 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 prompts' };
                        }
                    },
                    {
                        type: 'copy',
                        title: 'prompts.action.copy',
                        idField: 'id',
                        nameField: 'name',
                        contentField: 'content',
                        operationName: 'handlePromptCreate',
                        loadingStateName: 'creatingPrompt',
                        // Only show if user has create permission (permissions.create !== 'n')
                        disabled: (hookData: any) => {
                            if (!hookData?.permissions) return { disabled: false };
                            const hasCreate = hookData.permissions.create !== 'n' && hookData.permissions.view;
                            return { disabled: !hasCreate, message: 'No permission to create prompts' };
                        }
                    }
                ],
                searchable: true,
                filterable: true,
                sortable: true,
                resizable: true,
                pagination: true,
                pageSize: 10,
                className: 'prompts-table'
            }
        }
    ],
    
    // Page behavior
    persistent: false,
    preload: false,
    preserveState: true, // Keep page mounted and prevent refetching
    moduleEnabled: true,
    
    // shown in sidebar under administration
    
    // No drag and drop configuration for prompts
    
    // Lifecycle hooks
    onActivate: async () => {
        if (import.meta.env.DEV) console.log('Prompts activated');
    },
    onLoad: async () => {
        if (import.meta.env.DEV) console.log('Prompts loaded - can initialize prompts list here');
    },
    onUnload: async () => {
        if (import.meta.env.DEV) console.log('Prompts unloaded - cleanup prompts references');
    }
};

