import React, { useCallback } from 'react';
import { GenericPageData } from '../../pageInterface';
import { FaRegFileAlt, FaUpload, FaDownload } from 'react-icons/fa';
import { useUserFiles, useFileOperations } from '../../../../hooks/useFiles';

// Helper function to convert attribute definitions to column config
const attributesToColumns = (attributes: any[]) => {
    return attributes.map(attr => {
        // Check if this is a date/timestamp field - disable filtering for these
        const isDateField = attr.type === 'date' || 
                           /(date|Date|timestamp|Timestamp|created|Created|updated|Updated|at|At)$/i.test(attr.name);
        
        const column: any = {
            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,
            // Disable filtering for date/timestamp fields
            filterable: isDateField ? false : (attr.filterable !== false),
            searchable: attr.searchable !== false,
            filterOptions: attr.filterOptions
        };
        
        // Note: fileHash formatting is now handled automatically by FormGeneratorTable
        // with copyable truncated values - no custom formatter needed
        
        // Add formatter for fileSize to display human-readable sizes
        if (attr.name === 'fileSize' || attr.name === 'file_size' || attr.name === 'size') {
            column.formatter = (value: any) => {
                if (value === null || value === undefined) return '-';
                const bytes = typeof value === 'number' ? value : parseFloat(value);
                if (isNaN(bytes) || bytes < 0) return value || '-';
                
                // Format bytes to human-readable format
                const units = ['B', 'KB', 'MB', 'GB', 'TB'];
                let size = bytes;
                let unitIndex = 0;
                
                while (size >= 1024 && unitIndex < units.length - 1) {
                    size /= 1024;
                    unitIndex++;
                }
                
                // Round to 2 decimal places, but show integers if possible
                const formattedSize = size % 1 === 0 ? size.toString() : size.toFixed(2);
                return `${formattedSize} ${units[unitIndex]}`;
            };
        }
        
        return column;
    });
};

// Hook factory function for files data
const createFilesHook = () => {
    return () => {
        const { 
            data: files, 
            loading, 
            error, 
            refetch, 
            removeFileOptimistically, 
            updateFileOptimistically,
            attributes,
            permissions,
            pagination,
            fetchFileById,
            generateEditFieldsFromAttributes,
            ensureAttributesLoaded
        } = useUserFiles();
        const { 
            handleFileDownload, 
            handleFileDeleteMultiple,
            handleFilePreview, 
            handleFileUpdate,
            handleFileDelete,
            handleFileUpload,
            deletingFiles,
            previewingFiles,
            editingFiles,
            downloadingFiles,
            uploadingFile
        } = useFileOperations();
        
        const generatedColumns = attributes && attributes.length > 0 
            ? attributesToColumns(attributes)
            : undefined;
        
        // Handle single file deletion for FormGenerator
        const handleDeleteSingle = useCallback(async (file: any) => {
            const success = await handleFileDelete(file.id);
            
            if (success) {
                refetch();
            }
        }, [handleFileDelete, refetch]);

        // Handle multiple file deletion for FormGenerator
        const handleDeleteMultiple = useCallback(async (selectedFiles: any[]) => {
            const fileIds = selectedFiles.map(file => file.id);
            const success = await handleFileDeleteMultiple(fileIds);
            
            if (success) {
                refetch();
            }
        }, [handleFileDeleteMultiple, refetch]);

        // Wrap handleFileUpload for upload button and drag-and-drop
        // GenericDataHook expects: (file: File) => Promise<{ success: boolean; data: any }>
        const handleUpload = useCallback(async (file: File): Promise<{ success: boolean; data: any }> => {
            const result = await handleFileUpload(file);
            if (result.success) {
                // Refetch files list after successful upload
                refetch();
            }
            // Map fileData to data to match GenericDataHook interface
            return {
                success: result.success,
                data: 'fileData' in result ? result.fileData : ('data' in result ? result.data : null)
            };
        }, [handleFileUpload, refetch]);

        return {
            data: files,
            loading,
            error,
            refetch,
            removeFileOptimistically, // Expose optimistic removal (generic name for DeleteActionButton)
            updateFileOptimistically, // Expose optimistic update for EditActionButton
            // Operations
            handleDownload: handleFileDownload,
            handleDelete: handleFileDelete,
            handleDeleteMultiple,
            handlePreview: handleFilePreview,
            handleFileUpdate,
            // FormGenerator specific handlers
            onDelete: handleDeleteSingle,
            onDeleteMultiple: handleDeleteMultiple,
            // Loading states
            downloadingFiles,
            deletingFiles,
            previewingFiles,
            editingFiles,
            uploadingFile,
            // Upload functionality for button and drag-and-drop
            handleUpload,
            // Attributes and permissions for dynamic column/button generation
            attributes,
            permissions,
            pagination, // Pagination metadata from backend
            columns: generatedColumns, // Return generated columns
            // Functions for EditActionButton
            fetchFileById, // Fetch single file by ID
            generateEditFieldsFromAttributes, // Generate edit fields from attributes
            ensureAttributesLoaded // Generic function to ensure attributes are loaded
        };
    };
};

export const filesPageData: GenericPageData = {
    id: 'basedata-files',
    path: 'basedata/files',
    name: 'files.title',
    description: 'files.description',
    
    // Parent page - now under 'basedata' group (formerly 'administration')
    parentPath: 'basedata',
    
    // Visual
    icon: FaRegFileAlt,
    title: 'files.title',
    subtitle: 'files.title',
    
    // Header buttons
    headerButtons: [
        {
            id: 'upload-file',
            label: 'files.upload_button',
            icon: FaUpload,
            variant: 'primary',
            // onClick will be handled by PageRenderer to render UploadButton
            onClick: () => {}, // Placeholder - PageRenderer will detect this as upload button
            // Only show if user has create permission (permissions.create !== 'n')
            disabled: (hookData: any) => {
                if (!hookData?.permissions) return { disabled: false };
                const hasCreate = hookData.permissions.create !== 'n' && hookData.permissions.view;
                return { disabled: !hasCreate, message: 'No permission to upload files' };
            }
        }
    ],
    
    // Content sections - using generic table approach
    content: [
        {
            id: 'files-table',
            type: 'table',
            tableConfig: {
                hookFactory: createFilesHook,
                // Columns are generated dynamically from attributes via hookData.columns
                // Standard action buttons (built-in: edit, delete, view, copy)
                actionButtons: [
                    {
                        type: 'view',
                        title: 'files.action.preview',
                        idField: 'id',
                        nameField: 'fileName',
                        typeField: 'mimeType',
                        operationName: 'handlePreview',
                        loadingStateName: 'previewingFiles',
                        disabled: (hookData: any) => {
                            if (!hookData?.permissions) return { disabled: false };
                            const hasRead = hookData.permissions.read !== 'n' && hookData.permissions.view;
                            return { disabled: !hasRead, message: 'No permission to preview files' };
                        }
                    },
                    {
                        type: 'edit',
                        title: 'files.action.edit',
                        idField: 'id',
                        nameField: 'fileName',
                        operationName: 'handleFileUpdate',
                        loadingStateName: 'editingFiles',
                        fetchItemFunctionName: 'fetchFileById',
                        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 files' };
                        }
                    },
                    {
                        type: 'delete',
                        title: 'files.action.delete',
                        idField: 'id',
                        operationName: 'handleDelete',
                        loadingStateName: 'deletingFiles',
                        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 files' };
                        }
                    }
                ],
                // Custom action buttons (entity-specific)
                customActions: [
                    {
                        id: 'download',
                        icon: React.createElement(FaDownload),
                        title: 'files.action.download',
                        onClick: async (row: any, hookData: any) => {
                            if (hookData?.handleDownload) {
                                await hookData.handleDownload(row.id, row.fileName, row.mimeType);
                            }
                        },
                        disabled: (_row: any, hookData: any) => {
                            if (!hookData?.permissions) return { disabled: false, message: '' };
                            const hasRead = hookData.permissions.read !== 'n' && hookData.permissions.view;
                            return { disabled: !hasRead, message: 'No permission to download files' };
                        },
                        loading: (row: any, hookData: any) => hookData?.downloadingFiles?.has(row.id) || false
                    }
                ],
                searchable: true,
                filterable: true,
                sortable: true,
                resizable: true,
                pagination: true,
                pageSize: 10,
                className: 'files-table'
            }
        }
    ],
    
    // Page behavior
    persistent: false,
    preload: false,
    preserveState: true, // Keep page mounted and prevent refetching
    moduleEnabled: true,
    
    // Sidebar - will be shown as subpage under Administration
    
    // Drag and drop configuration
    dragDropConfig: {
        enabled: true,
        accept: '*/*', // Accept all file types
        multiple: true, // Allow multiple files
        // overlayText and overlaySubtext will use default translations from DragDropOverlay
    },
    
    // Lifecycle hooks
    onActivate: async () => {
        if (import.meta.env.DEV) console.log('Files activated');
    },
    onLoad: async () => {
        if (import.meta.env.DEV) console.log('Files loaded - can initialize file lists here');
    },
    onUnload: async () => {
        if (import.meta.env.DEV) console.log('Files unloaded - cleanup file references');
    }
};
