import { useCallback } from 'react';
import { GenericPageData } from '../../../pageInterface';
import { FaBuilding, FaPlus } from 'react-icons/fa';
import { useTrusteeOrganisations, useTrusteeOrganisationOperations } from '../../../../../hooks/useTrustee';

// Helper function to convert attribute definitions to column config
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
        };
    });
};

// Hook factory function for organisations data
const createOrganisationsHook = () => {
    return () => {
        const {
            items: organisations,
            loading,
            error,
            refetch,
            removeOptimistically,
            updateOptimistically,
            attributes,
            permissions,
            fetchById,
            generateEditFieldsFromAttributes,
            generateCreateFieldsFromAttributes,
            ensureAttributesLoaded
        } = useTrusteeOrganisations();
        const {
            handleDelete,
            handleCreate,
            handleUpdate,
            deletingItems,
            creatingItem,
            deleteError,
            createError,
            updateError
        } = useTrusteeOrganisationOperations();

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

    icon: FaBuilding,
    title: 'trustee.organisations.title',
    subtitle: 'trustee.organisations.subtitle',

    headerButtons: [
        {
            id: 'new-organisation',
            label: 'trustee.organisations.new_button',
            icon: FaPlus,
            variant: 'primary',
            formConfig: {
                fields: [
                    {
                        key: 'id',
                        label: 'trustee.organisations.field.id',
                        type: 'string',
                        required: true,
                        placeholder: 'trustee.organisations.field.id_placeholder',
                        validator: (value: string) => {
                            if (!value || value.trim() === '') {
                                return 'Organisation ID cannot be empty';
                            }
                            if (value.length < 3 || value.length > 50) {
                                return 'Organisation ID must be 3-50 characters';
                            }
                            if (!/^[a-zA-Z0-9_-]+$/.test(value)) {
                                return 'Organisation ID can only contain letters, numbers, hyphens, and underscores';
                            }
                            return null;
                        }
                    },
                    {
                        key: 'label',
                        label: 'trustee.organisations.field.label',
                        type: 'string',
                        required: true,
                        placeholder: 'trustee.organisations.field.label_placeholder'
                    },
                    {
                        key: 'enabled',
                        label: 'trustee.organisations.field.enabled',
                        type: 'boolean',
                        required: false
                    }
                ],
                popupTitle: 'trustee.organisations.modal.create.title',
                popupSize: 'medium',
                createOperationName: 'handleCreate',
                successMessage: 'trustee.organisations.create.success',
                errorMessage: 'trustee.organisations.create.error'
            }
        }
    ],

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

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

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