import { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaKey, FaPlus } from 'react-icons/fa';
import { useTrusteeAccess, useTrusteeAccessOperations } 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);

        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
        };
    });
};

const createAccessHook = () => {
    return () => {
        const {
            items: accessRecords,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            attributes,
            permissions,
            fetchById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = useTrusteeAccess();
        const {
            handleDelete,
            handleCreate,
            handleUpdate,
            deletingItems,
            creatingItem,
            deleteError,
            createError,
            updateError
        } = useTrusteeAccessOperations();

        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: accessRecords,
            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 trusteeAccessPageData: GenericPageData = {
    id: 'trustee-access',
    path: 'trustee/access',
    name: 'trustee.access.title',
    description: 'trustee.access.description',
    parentPath: 'trustee',

    icon: FaKey,
    title: 'trustee.access.title',
    subtitle: 'trustee.access.subtitle',

    headerButtons: [
        {
            id: 'new-access',
            label: 'trustee.access.new_button',
            icon: FaPlus,
            variant: 'primary',
            formConfig: {
                fields: [
                    {
                        key: 'organisationId',
                        label: 'trustee.access.field.organisationId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'TrusteeOrganisation'
                    },
                    {
                        key: 'roleId',
                        label: 'trustee.access.field.roleId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'TrusteeRole'
                    },
                    {
                        key: 'userId',
                        label: 'trustee.access.field.userId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'User'
                    },
                    {
                        key: 'contractId',
                        label: 'trustee.access.field.contractId',
                        type: 'enum',
                        required: false,
                        optionsReference: 'TrusteeContract',
                        placeholder: 'trustee.access.field.contractId_placeholder'
                    }
                ],
                popupTitle: 'trustee.access.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handleCreate',
                successMessage: 'trustee.access.create.success',
                errorMessage: 'trustee.access.create.error'
            }
        }
    ],

    content: [
        {
            id: 'access-table',
            type: 'table',
            tableConfig: {
                hookFactory: createAccessHook,
                actionButtons: [
                    {
                        type: 'edit',
                        title: 'trustee.access.action.edit',
                        idField: 'id',
                        nameField: 'id',
                        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 access' };
                        }
                    },
                    {
                        type: 'delete',
                        title: 'trustee.access.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 access' };
                        }
                    }
                ],
                searchable: true,
                filterable: true,
                sortable: true,
                resizable: true,
                pagination: true,
                pageSize: 10,
                className: 'trustee-access-table'
            }
        }
    ],

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

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