import { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaLink, FaPlus } from 'react-icons/fa';
import { useTrusteePositionDocuments, useTrusteePositionDocumentOperations } from '../../../../../hooks/useTrusteePositionDocuments';

// Helper function to convert attribute definitions to column config
const attributesToColumns = (attributes: any[]) => {
    return attributes.map(attr => {
        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,
            filterable: isDateField ? false : (attr.filterable !== false),
            searchable: attr.searchable !== false,
            filterOptions: attr.filterOptions
        };
    });
};

// Hook factory function for position-documents data
const createPositionDocumentsHook = () => {
    return () => {
        const { 
            positionDocuments, 
            loading, 
            error, 
            refetch, 
            removeOptimistically,
            attributes,
            permissions,
            pagination,
            fetchPositionDocumentById,
            generateEditFieldsFromAttributes,
            ensureAttributesLoaded
        } = useTrusteePositionDocuments();
        const { 
            handlePositionDocumentDelete,
            handlePositionDocumentCreate,
            deletingPositionDocuments,
            creatingPositionDocument,
            deleteError,
            createError
        } = useTrusteePositionDocumentOperations();
        
        const generatedColumns = attributes && attributes.length > 0 
            ? attributesToColumns(attributes)
            : undefined;
        
        const wrappedHandlePositionDocumentCreate = useCallback(async (formData: any) => {
            return await handlePositionDocumentCreate(formData);
        }, [handlePositionDocumentCreate]);
        
        const handleDeleteSingle = useCallback(async (positionDocument: any) => {
            const success = await handlePositionDocumentDelete(positionDocument.id);
            if (success) {
                refetch();
            }
        }, [handlePositionDocumentDelete, refetch]);

        const handleDeleteMultiple = useCallback(async (selectedPositionDocuments: any[]) => {
            const positionDocumentIds = selectedPositionDocuments.map(pd => pd.id);
            const results = await Promise.all(
                positionDocumentIds.map(id => handlePositionDocumentDelete(id))
            );
            
            const allSuccessful = results.every(result => result);
            if (allSuccessful) {
                refetch();
            }
        }, [handlePositionDocumentDelete, refetch]);

        return {
            data: positionDocuments,
            loading,
            error,
            refetch,
            removeOptimistically,
            handleDelete: handlePositionDocumentDelete,
            handleDeleteMultiple,
            handlePositionDocumentCreate: wrappedHandlePositionDocumentCreate,
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            deletingPositionDocuments,
            creatingPositionDocument,
            deleteError,
            createError,
            attributes,
            permissions,
            columns: generatedColumns,
            pagination,
            fetchPositionDocumentById,
            generateEditFieldsFromAttributes,
            ensureAttributesLoaded
        };
    };
};

export const trusteePositionDocumentsPageData: GenericPageData = {
    id: 'administration-trustee-position-documents',
    path: 'administration/trustee/position-documents',
    name: 'trustee.positionDocuments.title',
    description: 'trustee.positionDocuments.description',
    
    // Parent page
    parentPath: 'administration/trustee',
    
    // Visual
    icon: FaLink,
    title: 'trustee.positionDocuments.title',
    subtitle: 'trustee.positionDocuments.subtitle',
    
    // Header buttons
    headerButtons: [
        {
            id: 'new-position-document',
            label: 'trustee.positionDocuments.new',
            icon: FaPlus,
            variant: 'primary',
            formConfig: {
                fields: [
                    {
                        key: 'organisationId',
                        label: 'trustee.positionDocuments.field.organisationId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'trustee.organisation',
                        validator: (value: any) => {
                            if (!value || (typeof value === 'string' && value.trim() === '')) {
                                return 'Organisation is required';
                            }
                            return null;
                        }
                    },
                    {
                        key: 'contractId',
                        label: 'trustee.positionDocuments.field.contractId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'trustee.contract',
                        dependsOn: 'organisationId',
                        validator: (value: any) => {
                            if (!value || (typeof value === 'string' && value.trim() === '')) {
                                return 'Contract is required';
                            }
                            return null;
                        }
                    },
                    {
                        key: 'positionId',
                        label: 'trustee.positionDocuments.field.positionId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'trustee.position',
                        dependsOn: 'contractId',
                        validator: (value: any) => {
                            if (!value || (typeof value === 'string' && value.trim() === '')) {
                                return 'Position is required';
                            }
                            return null;
                        }
                    },
                    {
                        key: 'documentId',
                        label: 'trustee.positionDocuments.field.documentId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'trustee.document',
                        dependsOn: 'contractId',
                        validator: (value: any) => {
                            if (!value || (typeof value === 'string' && value.trim() === '')) {
                                return 'Document is required';
                            }
                            return null;
                        }
                    }
                ],
                popupTitle: 'trustee.positionDocuments.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handlePositionDocumentCreate',
                successMessage: 'trustee.positionDocuments.create.success',
                errorMessage: 'trustee.positionDocuments.create.error'
            }
        }
    ],
    
    // Content sections
    content: [
        {
            id: 'position-documents-table',
            type: 'table',
            tableConfig: {
                hookFactory: createPositionDocumentsHook,
                actionButtons: [
                    {
                        type: 'delete',
                        title: 'trustee.positionDocuments.action.delete',
                        idField: 'id',
                        operationName: 'handleDelete',
                        loadingStateName: 'deletingPositionDocuments',
                        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 links' };
                        }
                    }
                ],
                searchable: true,
                filterable: true,
                sortable: true,
                resizable: true,
                pagination: true,
                pageSize: 10,
                className: 'position-documents-table'
            }
        }
    ],
    
    // Page behavior
    persistent: false,
    preload: false,
    preserveState: true,
    moduleEnabled: true,
    
    // Lifecycle hooks
    onActivate: async () => {
        if (import.meta.env.DEV) console.log('Position-Documents activated');
    },
    onLoad: async () => {
        if (import.meta.env.DEV) console.log('Position-Documents loaded');
    },
    onUnload: async () => {
        if (import.meta.env.DEV) console.log('Position-Documents unloaded');
    }
};
