import { FaFile, FaDownload, FaTrash } from "react-icons/fa";
import { MdOutlineRemoveRedEye } from "react-icons/md";
import styles from "./DateienItem.module.css";
import { useState } from "react";
import { useFileOperations } from "../../hooks/useFiles";
import FilePreviewPopup from "../Dashboard/DashboardChat/DashboardChatAreaFilePreview";
import { Document } from "../Dashboard/DashboardChat/dashboardChatAreaTypes";
import { useLanguage } from "../../contexts/LanguageContext";

type DateienItemProps = {
    file: {
        id: number;
        file_name: string;
        action: string;
        created_at: string;
        size?: number;
        source?: string; // 'user_uploaded', 'agent_created', or 'shared_with_me'
    };
    onDelete?: () => void;
    onOptimisticDelete?: () => void; // New prop for immediate UI update
};

const DateienItem = ({ file, onDelete, onOptimisticDelete }: DateienItemProps) => {
    const { t } = useLanguage();
    const { downloadingFiles, deletingFiles, handleFileDownload, handleFileDelete } = useFileOperations();
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    const [previewDocument, setPreviewDocument] = useState<Document | null>(null);
    const [isPreviewOpen, setIsPreviewOpen] = useState(false);
    const isDownloading = downloadingFiles.has(file.id);
    const isDeleting = deletingFiles.has(file.id);

    /**
     * Formats a file size in bytes to a human-readable string (KB, MB, etc.)
     */
    const formatFileSize = (bytes?: number): string => {
        if (bytes === undefined || bytes === null) return t('files.unknown_size', 'Unknown Size');
        
        if (bytes === 0) return '0 Bytes';
        
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(1024));
        
        if (i === 0) return `${bytes} ${sizes[i]}`;
        
        return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
    };

    /**
     * Formats the file source for display
     */
    const formatFileSource = (source?: string): string => {
        switch (source) {
            case 'user_uploaded':
                return t('files.source.uploaded', 'Uploaded');
            case 'agent_created':
                return t('files.source.ai_created', 'AI-created');
            case 'shared_with_me':
                return t('files.source.shared', 'Shared');
            default:
                return t('files.source.unknown', 'Unknown');
        }
    };

    // Format the date properly
    const formatDate = (dateString: string) => {
        try {
            const date = new Date(dateString);
            // Check if date is valid
            if (isNaN(date.getTime())) {
                return t('files.unknown_date', 'Unknown Date');
            }
            
            return date.toLocaleDateString('de-DE', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric'
            });
        } catch (e) {
            console.error('Error formatting date:', e);
            return t('files.unknown_date', 'Unknown Date');
        }
    };

    const handleDeleteClick = async () => {
        if (showDeleteConfirm) {
            const success = await handleFileDelete(file.id, onOptimisticDelete);
            if (!success) {
                // If deletion failed, refresh the file list to restore the file
                if (onDelete) {
                    onDelete();
                }
            }
            setShowDeleteConfirm(false);
        } else {
            setShowDeleteConfirm(true);
        }
    };

    const handleCancelDelete = () => {
        setShowDeleteConfirm(false);
    };

    const handlePreview = () => {
        // Split filename to get name and extension
        const nameParts = file.file_name.split('.');
        const extension = nameParts.length > 1 ? nameParts.pop() : undefined;
        const fileName = nameParts.join('.');

        // Create a Document object compatible with FilePreviewPopup
        const document: Document = {
            id: String(file.id),
            fileId: file.id,
            name: fileName,
            ext: extension,
            size: file.size
        };

        setPreviewDocument(document);
        setIsPreviewOpen(true);
    };

    const handleClosePreview = () => {
        setIsPreviewOpen(false);
        setPreviewDocument(null);
    };

    return (
        <>
            <li>
                {/* 1st column: Name with icon */}
                <div className={styles.fileName}>
                    <FaFile className={styles.icon} />
                    <span>{file.file_name}</span>
                </div>
                
                {/* 2nd column: Type with source */}
                <div className={styles.fileType}>
                    <div>{file.action}</div>
                    <div className={styles.fileSource}>{formatFileSource(file.source)}</div>
                </div>
                
                {/* 3rd column: Size */}
                <div className={styles.fileSize}>
                    {formatFileSize(file.size)}
                </div>
                
                {/* 4th column: Date and action buttons */}
                <div className={styles.fileDateWithActions}>
                    <span className={styles.fileDate}>
                        {formatDate(file.created_at)}
                    </span>
                    
                    <div className={styles.actionButtons}>
                        <button 
                            className={styles.previewButton}
                            onClick={handlePreview}
                            disabled={isDownloading || isDeleting}
                            title={t('files.preview_tooltip', 'Preview file')}
                        >
                            <MdOutlineRemoveRedEye className={styles.actionIcon} />
                        </button>
                        <button 
                            className={`${styles.downloadButton} ${isDownloading ? styles.downloading : ''}`}
                            onClick={() => handleFileDownload(file.id, file.file_name)}
                            disabled={isDownloading || isDeleting}
                            title={t('files.download_tooltip', 'Download file')}
                        >
                            <FaDownload className={styles.actionIcon} />
                            {isDownloading && <span className={styles.actionText}>{t('files.downloading', 'Downloading...')}</span>}
                        </button>
                        <button 
                            className={`${styles.deleteButton} ${isDeleting ? styles.deleting : ''} ${showDeleteConfirm ? styles.confirm : ''}`}
                            onClick={handleDeleteClick}
                            disabled={isDownloading || isDeleting}
                            title={showDeleteConfirm ? t('files.delete_confirm_tooltip', 'Click again to confirm deletion') : t('files.delete_tooltip', 'Delete file')}
                            onBlur={handleCancelDelete}
                        >
                            <FaTrash className={styles.actionIcon} />
                            {isDeleting && <span className={styles.actionText}>{t('files.deleting', 'Deleting...')}</span>}
                            {showDeleteConfirm && <span className={styles.actionText}>{t('files.delete_confirm', 'Click to confirm...')}</span>}
                        </button>
                    </div>
                </div>
            </li>

            {/* File Preview Popup */}
            {previewDocument && (
                <FilePreviewPopup
                    document={previewDocument}
                    isOpen={isPreviewOpen}
                    onClose={handleClosePreview}
                />
            )}
        </>
    );
};

export default DateienItem;

