import { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaFileContract, FaPlus } from 'react-icons/fa';
import { useTrusteeContracts, useTrusteeContractOperations } 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 createContractsHook = () => {
    return () => {
        const {
            items: contracts,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            attributes,
            permissions,
            fetchById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = useTrusteeContracts();
        const {
            handleDelete,
            handleCreate,
            handleUpdate,
            deletingItems,
            creatingItem,
            deleteError,
            createError,
            updateError
        } = useTrusteeContractOperations();

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

    icon: FaFileContract,
    title: 'trustee.contracts.title',
    subtitle: 'trustee.contracts.subtitle',

    headerButtons: [
        {
            id: 'new-contract',
            label: 'trustee.contracts.new_button',
            icon: FaPlus,
            variant: 'primary',
            formConfig: {
                fields: [
                    {
                        key: 'organisationId',
                        label: 'trustee.contracts.field.organisationId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'TrusteeOrganisation'
                    },
                    {
                        key: 'label',
                        label: 'trustee.contracts.field.label',
                        type: 'string',
                        required: true,
                        placeholder: 'trustee.contracts.field.label_placeholder'
                    },
                    {
                        key: 'enabled',
                        label: 'trustee.contracts.field.enabled',
                        type: 'boolean',
                        required: false
                    }
                ],
                popupTitle: 'trustee.contracts.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handleCreate',
                successMessage: 'trustee.contracts.create.success',
                errorMessage: 'trustee.contracts.create.error'
            }
        }
    ],

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

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

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