import { useCallback } from 'react';
import { GenericPageData } from '../../pageInterface';
import { FaProjectDiagram } from 'react-icons/fa';
import { useUserWorkflows, useWorkflowOperations } from '../../../../hooks/useWorkflows';

// Helper function to convert attribute definitions to column config
const attributesToColumns = (attributes: any[]) => {
    return attributes
        .filter(attr => {
            // Exclude statistic, logs, messages, tasks, max steps, current action, total tasks, and total actions columns entirely
            const attrNameLower = attr.name.toLowerCase();
            const excludedColumns = [
                'statistic', 'statistics', 'stats',
                'logs', 'log',
                'messages', 'message',
                'tasks', 'task',
                'maxsteps', 'max_steps', 'max steps', 'maxstep', 'max_step',
                'currentaction', 'current_action', 'current action',
                'totaltasks', 'total_tasks', 'total tasks',
                'totalactions', 'total_actions', 'total actions',
                'expectedformats', 'expected_formats', 'expected formats', 'expectedformat', 'expected_format', 'expected format'
            ];
            return !excludedColumns.includes(attrNameLower);
        })
        .map(attr => {
            // Check if this is a date/timestamp field - disable filtering for these
            const attrNameLower = attr.name.toLowerCase();
            const isDateField = attr.type === 'date' || 
                               /(date|Date|timestamp|Timestamp|created|Created|updated|Updated|at|At)$/i.test(attr.name) ||
                               attrNameLower === 'lastactivity' ||
                               attrNameLower === 'last_activity' ||
                               attrNameLower === 'last activity';
            
            const column: any = {
                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
            };
            
            // Add explicit formatters for numeric fields that should NOT be treated as dates
            if (attrNameLower === 'currentround' || attrNameLower === 'current_round' || attrNameLower === 'current round') {
                column.formatter = (value: any) => {
                    if (value === null || value === undefined) return '-';
                    return typeof value === 'number' ? value.toString() : value;
                };
                // Ensure type is set to number to prevent date formatting
                column.type = 'number';
            } else if (attrNameLower === 'currenttask' || attrNameLower === 'current_task' || attrNameLower === 'current task') {
                column.formatter = (value: any) => {
                    if (value === null || value === undefined) return '-';
                    return typeof value === 'number' ? value.toString() : value;
                };
                // Ensure type is set to number to prevent date formatting
                column.type = 'number';
            }
            
            return column;
        });
};

// Hook factory function for workflows data
const createWorkflowsHook = () => {
    return () => {
        const { 
            data: workflows, 
            loading, 
            error, 
            refetch, 
            removeOptimistically, 
            updateOptimistically,
            attributes,
            permissions,
            pagination,
            fetchWorkflowById,
            generateEditFieldsFromAttributes,
            ensureAttributesLoaded
        } = useUserWorkflows();
        const { 
            handleWorkflowDelete, 
            handleWorkflowDeleteMultiple,
            handleWorkflowUpdate,
            deletingWorkflows, 
            editingWorkflows
        } = useWorkflowOperations();
        
        const generatedColumns = attributes && attributes.length > 0 
            ? attributesToColumns(attributes)
            : undefined;
        
        // Handle single workflow deletion for FormGenerator
        const handleDeleteSingle = useCallback(async (workflow: any) => {
            const success = await handleWorkflowDelete(workflow.id);
            
            if (success) {
                refetch();
            }
        }, [handleWorkflowDelete, refetch]);

        // Handle multiple workflow deletion for FormGenerator
        const handleDeleteMultiple = useCallback(async (selectedWorkflows: any[]) => {
            const workflowIds = selectedWorkflows.map(workflow => workflow.id);
            const success = await handleWorkflowDeleteMultiple(workflowIds);
            
            if (success) {
                refetch();
            }
        }, [handleWorkflowDeleteMultiple, refetch]);

        return {
            data: workflows,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            // Operations
            handleDelete: handleWorkflowDelete,
            handleDeleteMultiple,
            handleWorkflowUpdate,
            // FormGenerator specific handlers
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            // Loading states
            deletingWorkflows,
            editingWorkflows,
            // Attributes and permissions for dynamic column/button generation
            attributes,
            permissions,
            pagination, // Pagination metadata from backend
            columns: generatedColumns, // Return generated columns
            // Functions for EditActionButton
            fetchWorkflowById, // Fetch single workflow by ID
            generateEditFieldsFromAttributes, // Generate edit fields from attributes
            ensureAttributesLoaded // Generic function to ensure attributes are loaded
        };
    };
};

export const workflowsPageData: GenericPageData = {
    id: 'workflows-list',
    path: 'workflows/list',
    name: 'workflows.title',
    description: 'workflows.description',
    
    // Parent page - now under 'workflows' group
    parentPath: 'workflows',
    
    // Visual
    icon: FaProjectDiagram,
    title: 'workflows.title',
    subtitle: 'workflows.title',
    
    // Header buttons - none for now, workflows are typically created through the playground
    
    // Content sections - using generic table approach
    content: [
        {
            id: 'workflows-table',
            type: 'table',
            tableConfig: {
                hookFactory: createWorkflowsHook,
                // Columns are generated dynamically from attributes via hookData.columns
                actionButtons: [
                    {
                        type: 'play',
                        title: 'workflows.action.play',
                        idField: 'id',
                        nameField: 'name',
                        navigateTo: 'start/dashboard',
                        mode: 'workflow', // Set mode to 'workflow' to select workflow instead of setting prompt
                        // 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 workflows' };
                        }
                    },
                    {
                        type: 'edit',
                        title: 'workflows.action.edit',
                        idField: 'id',
                        nameField: 'name',
                        operationName: 'handleWorkflowUpdate',
                        loadingStateName: 'editingWorkflows',
                        fetchItemFunctionName: 'fetchWorkflowById',
                        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 workflows' };
                        }
                    },
                    {
                        type: 'delete',
                        title: 'workflows.action.delete',
                        idField: 'id',
                        operationName: 'handleDelete',
                        loadingStateName: 'deletingWorkflows',
                        // 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 workflows' };
                        }
                    }
                ],
                searchable: true,
                filterable: true,
                sortable: true,
                resizable: true,
                pagination: true,
                pageSize: 10,
                className: 'workflows-table'
            }
        }
    ],
    
    // Page behavior
    persistent: false,
    preload: false,
    preserveState: true, // Keep page mounted and prevent refetching
    moduleEnabled: true,
    
    // Sidebar - will be shown as subpage under Administration
    
    // Lifecycle hooks
    onActivate: async () => {
        if (import.meta.env.DEV) console.log('Workflows activated');
    },
    onLoad: async () => {
        if (import.meta.env.DEV) console.log('Workflows loaded - can initialize workflow lists here');
    },
    onUnload: async () => {
        if (import.meta.env.DEV) console.log('Workflows unloaded - cleanup workflow references');
    }
};
