const AttachmentManager = ({ articleId, attachments, onAttachmentsChange, readOnly = false }) => {
    const [uploading, setUploading] = React.useState(false);
    const fileInputRef = React.useRef(null);
    
    const handleUpload = async (files) => {
        if (!files || files.length === 0) return;
        
        setUploading(true);
        const newAttachments = [];
        
        for (const file of files) {
            try {
                const formData = new FormData();
                formData.append('file', file);
                
                const response = await fetch(`/api/knowledge-base/${articleId}/attachments/upload`, {
                    method: 'POST',
                    headers: {
                        'X-OTO-User': localStorage.getItem('oto_username')
                    },
                    body: formData
                });
                
                const result = await response.json();
                if (result.success) {
                    newAttachments.push(result.attachment);
                }
            } catch (error) {
                console.error('Upload failed:', error);
                window.otoNotify?.toast(`Failed to upload ${file.name}`, 'error');
            }
        }
        
        setUploading(false);
        if (newAttachments.length > 0) {
            onAttachmentsChange([...attachments, ...newAttachments]);
        }
    };
    
    const handleDelete = async (attachmentId) => {
        const ok = await window.otoNotify?.confirm({ title: 'Delete attachment', message: 'Delete this attachment?', confirmLabel: 'Delete', danger: true });
        if (!ok) return;

        try {
            const response = await fetch(`/api/knowledge-base/${articleId}/attachments/${attachmentId}`, {
                method: 'DELETE',
                headers: {
                    'X-OTO-User': localStorage.getItem('oto_username')
                }
            });
            
            const result = await response.json();
            if (result.success) {
                onAttachmentsChange(attachments.filter(a => a.id !== attachmentId));
            }
        } catch (error) {
            console.error('Delete failed:', error);
            window.otoNotify?.toast('Failed to delete attachment', 'error');
        }
    };
    
    const formatFileSize = (bytes) => {
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
    };
    
    return (
        <div className="space-y-2">
            {!readOnly && (
                <div>
                    <input
                        ref={fileInputRef}
                        type="file"
                        multiple
                        onChange={(e) => handleUpload(Array.from(e.target.files))}
                        className="hidden"
                    />
                    <button
                        type="button"
                        onClick={() => fileInputRef.current?.click()}
                        disabled={uploading}
                        className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover disabled:bg-gray-400"
                    >
                        {uploading ? 'Uploading...' : 'Upload Files'}
                    </button>
                </div>
            )}
            
            {attachments && attachments.length > 0 && (
                <div className="space-y-2">
                    {attachments.map((att) => (
                        <div key={att.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-200">
                            <div className="flex items-center gap-3">
                                <div className="text-2xl">📎</div>
                                <div>
                                    <div className="font-semibold text-sm">{att.original_filename}</div>
                                    <div className="text-xs text-gray-500">
                                        {formatFileSize(att.file_size)} • Uploaded by {att.uploaded_by}
                                    </div>
                                </div>
                            </div>
                            <div className="flex gap-2">
                                <a
                                    href={`/api/knowledge-base/${articleId}/attachments/${att.id}/download`}
                                    className="px-3 py-1 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
                                    download
                                >
                                    Download
                                </a>
                                {!readOnly && (
                                    <button
                                        type="button"
                                        onClick={() => handleDelete(att.id)}
                                        className="px-3 py-1 text-sm bg-primary/10 text-primary rounded hover:bg-primary/20"
                                    >
                                        Delete
                                    </button>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

if (typeof window !== 'undefined') window.AttachmentManager = AttachmentManager;