import { FaFile, FaDownload, FaTrash } from "react-icons/fa";
import styles from "./DateienItem.module.css";
import { useState } from "react";
import { useFileOperations } from "../../hooks/useFiles";

type DateienItemProps = {
    file: {
        id: number;
        file_name: string;
        action: string;
        created_at: string;
        size?: number;
    };
    onDelete?: () => void;
};

/**
 * 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 'Unbekannte Größe';
    
    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]}`;
};

const DateienItem = ({ file, onDelete }: DateienItemProps) => {
    const { downloadingFiles, deletingFiles, handleFileDownload, handleFileDelete } = useFileOperations();
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    const isDownloading = downloadingFiles.has(file.id);
    const isDeleting = deletingFiles.has(file.id);

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

    const handleDeleteClick = async () => {
        if (showDeleteConfirm) {
            const success = await handleFileDelete(file.id);
            if (success && onDelete) {
                onDelete();
            }
            setShowDeleteConfirm(false);
        } else {
            setShowDeleteConfirm(true);
        }
    };

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

    return (
        <li>
            {/* 1st column: Name with icon */}
            <div className={styles.fileName}>
                <FaFile className={styles.icon} />
                <span>{file.file_name}</span>
            </div>
            
            {/* 2nd column: Type */}
            <div className={styles.fileType}>
                {file.action}
            </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.downloadButton} ${isDownloading ? styles.downloading : ''}`}
                        onClick={() => handleFileDownload(file.id, file.file_name)}
                        disabled={isDownloading || isDeleting}
                        title="Download file"
                    >
                        <FaDownload className={styles.actionIcon} />
                        {isDownloading && <span className={styles.actionText}>Downloading...</span>}
                    </button>
                    <button 
                        className={`${styles.deleteButton} ${isDeleting ? styles.deleting : ''} ${showDeleteConfirm ? styles.confirm : ''}`}
                        onClick={handleDeleteClick}
                        disabled={isDownloading || isDeleting}
                        title={showDeleteConfirm ? "Click again to confirm deletion" : "Delete file"}
                        onBlur={handleCancelDelete}
                    >
                        <FaTrash className={styles.actionIcon} />
                        {isDeleting && <span className={styles.actionText}>Deleting...</span>}
                        {showDeleteConfirm && <span className={styles.actionText}>Click to confirm</span>}
                    </button>
                </div>
            </div>
        </li>
    );
};

export default DateienItem;

