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

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

        const wrappedHandleCreate = useCallback(async (formData: any) => {
            // Auto-calculate VAT amount if not provided
            if (formData.bookingAmount && formData.vatPercentage && !formData.vatAmount) {
                formData.vatAmount = formData.bookingAmount * formData.vatPercentage / 100;
            }
            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: positions,
            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 trusteePositionsPageData: GenericPageData = {
    id: 'trustee-positions',
    path: 'trustee/positions',
    name: 'trustee.positions.title',
    description: 'trustee.positions.description',
    parentPath: 'trustee',

    icon: FaReceipt,
    title: 'trustee.positions.title',
    subtitle: 'trustee.positions.subtitle',

    headerButtons: [
        {
            id: 'new-position',
            label: 'trustee.positions.new_button',
            icon: FaPlus,
            variant: 'primary',
            formConfig: {
                fields: [
                    {
                        key: 'organisationId',
                        label: 'trustee.positions.field.organisationId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'TrusteeOrganisation'
                    },
                    {
                        key: 'contractId',
                        label: 'trustee.positions.field.contractId',
                        type: 'enum',
                        required: true,
                        optionsReference: 'TrusteeContract'
                    },
                    {
                        key: 'valuta',
                        label: 'trustee.positions.field.valuta',
                        type: 'date',
                        required: true
                    },
                    {
                        key: 'company',
                        label: 'trustee.positions.field.company',
                        type: 'string',
                        required: false,
                        placeholder: 'trustee.positions.field.company_placeholder'
                    },
                    {
                        key: 'desc',
                        label: 'trustee.positions.field.desc',
                        type: 'textarea',
                        required: false,
                        minRows: 2,
                        maxRows: 4
                    },
                    {
                        key: 'bookingCurrency',
                        label: 'trustee.positions.field.bookingCurrency',
                        type: 'enum',
                        required: true,
                        options: [
                            { value: 'CHF', label: 'CHF' },
                            { value: 'EUR', label: 'EUR' },
                            { value: 'USD', label: 'USD' },
                            { value: 'GBP', label: 'GBP' }
                        ]
                    },
                    {
                        key: 'bookingAmount',
                        label: 'trustee.positions.field.bookingAmount',
                        type: 'number',
                        required: true
                    },
                    {
                        key: 'originalCurrency',
                        label: 'trustee.positions.field.originalCurrency',
                        type: 'enum',
                        required: true,
                        options: [
                            { value: 'CHF', label: 'CHF' },
                            { value: 'EUR', label: 'EUR' },
                            { value: 'USD', label: 'USD' },
                            { value: 'GBP', label: 'GBP' }
                        ]
                    },
                    {
                        key: 'originalAmount',
                        label: 'trustee.positions.field.originalAmount',
                        type: 'number',
                        required: true
                    },
                    {
                        key: 'vatPercentage',
                        label: 'trustee.positions.field.vatPercentage',
                        type: 'number',
                        required: false
                    },
                    {
                        key: 'vatAmount',
                        label: 'trustee.positions.field.vatAmount',
                        type: 'number',
                        required: false
                    }
                ],
                popupTitle: 'trustee.positions.modal.create.title',
                popupSize: 'large',
                createOperationName: 'handleCreate',
                successMessage: 'trustee.positions.create.success',
                errorMessage: 'trustee.positions.create.error'
            }
        }
    ],

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

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

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