import { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaFile, FaPlus } from 'react-icons/fa';
import { useTrusteeDocuments, useTrusteeDocumentOperations } from '../../../../../hooks/useTrustee';

const attributesToColumns = (attributes: any[]) => {
    return attributes.map(attr => {
        const isDateField = attr.type === 'date' || attr.type === 'timestamp' ||
            /(date|Date|timestamp|Timestamp|created|Created|updated|Updated|at|At)$/i.test(attr.name);

        // Hide binary data column
        if (attr.name === 'documentData') {
            return null;
        }

        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
        };
    }).filter(Boolean);
};

const createDocumentsHook = () => {
    return () => {
        const {
            items: documents,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            attributes,
            permissions,
            fetchById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = useTrusteeDocuments();
        const {
            handleDelete,
            handleCreate,
            handleUpdate,
            deletingItems,
            creatingItem,
            deleteError,
            createError,
            updateError
        } = useTrusteeDocumentOperations();

        const generatedColumns = attributes && attributes.length > 0
            ? attributesToColumns(attributes)
            : undefined;

        const wrappedHandleCreate = useCallback(async (formData: any) => {
            return await handleCreate(formData);
        }, [handleCreate]);

        const handleDeleteSingle = useCallback(async (item: any) => {
            const success = await handleDelete(item.id);
            if (success) {
                refetch();
            }
        }, [handleDelete, refetch]);

        const handleDeleteMultiple = useCallback(async (selectedItems: any[]) => {
            const ids = selectedItems.map(item => item.id);
            const results = await Promise.all(ids.map(id => handleDelete(id)));
            const allSuccessful = results.every(result => result);
            if (allSuccessful) {
                refetch();
            }
        }, [handleDelete, refetch]);

        return {
            data: documents,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            handleDelete,
            handleDeleteMultiple,
            handleCreate: wrappedHandleCreate,
            handleUpdate,
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            deletingItems,
            creatingItem,
            deleteError,
            createError,
            updateError,
            attributes,
            permissions,
            columns: generatedColumns,
            fetchById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        };
    };
};

export const trusteeDocumentsPageData: GenericPageData = {
    id: 'trustee-documents',
    path: 'trustee/documents',
    name: 'trustee.documents.title',
    description: 'trustee.documents.description',
    parentPath: 'trustee',

    icon: FaFile,
    title: 'trustee.documents.title',
    subtitle: 'trustee.documents.subtitle',

    headerButtons: [
        {
            id: 'new-document',
            label: 'trustee.documents.new_button',
            icon: FaPlus,
            variant: 'primary',
            formConfig: {
                fields: [
                    {
                        key: 'organisationId',
                        label: 'trustee.documents.field.organisationId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'TrusteeOrganisation'
                    },
                    {
                        key: 'contractId',
                        label: 'trustee.documents.field.contractId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'TrusteeContract'
                    },
                    {
                        key: 'documentName',
                        label: 'trustee.documents.field.documentName',
                        type: 'string',
                        required: true,
                        placeholder: 'trustee.documents.field.documentName_placeholder'
                    },
                    {
                        key: 'documentMimeType',
                        label: 'trustee.documents.field.documentMimeType',
                        type: 'enum',
                        required: true,
                        options: [
                            { value: 'application/pdf', label: 'PDF' },
                            { value: 'image/jpeg', label: 'JPEG' },
                            { value: 'image/png', label: 'PNG' },
                            { value: 'application/octet-stream', label: 'Other' }
                        ]
                    }
                ],
                popupTitle: 'trustee.documents.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handleCreate',
                successMessage: 'trustee.documents.create.success',
                errorMessage: 'trustee.documents.create.error'
            }
        }
    ],

    content: [
        {
            id: 'documents-table',
            type: 'table',
            tableConfig: {
                hookFactory: createDocumentsHook,
                actionButtons: [
                    {
                        type: 'edit',
                        title: 'trustee.documents.action.edit',
                        idField: 'id',
                        nameField: 'documentName',
                        operationName: 'handleUpdate',
                        loadingStateName: 'updatingItems',
                        fetchItemFunctionName: 'fetchById',
                        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 documents' };
                        }
                    },
                    {
                        type: 'delete',
                        title: 'trustee.documents.action.delete',
                        idField: 'id',
                        operationName: 'handleDelete',
                        loadingStateName: 'deletingItems',
                        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 documents' };
                        }
                    }
                ],
                searchable: true,
                filterable: true,
                sortable: true,
                resizable: true,
                pagination: true,
                pageSize: 10,
                className: 'trustee-documents-table'
            }
        }
    ],

    persistent: false,
    preload: false,
    preserveState: true,
    moduleEnabled: true,

    onActivate: async () => {
        if (import.meta.env.DEV) console.log('Trustee Documents activated');
    },
    onLoad: async () => {
        if (import.meta.env.DEV) console.log('Trustee Documents loaded');
    },
    onUnload: async () => {
        if (import.meta.env.DEV) console.log('Trustee Documents unloaded');
    }
};
