/**
 * MediaPanel.jsx - Global Media Library (Replaces ContextPanel)
 * Shows all media uploaded across all Ask AI sessions
 */

const { useState, useEffect } = React;

function MediaPanel({ t }) {
    const [media, setMedia] = useState({ images: [], documents: [], audio: [] });
    const [loading, setLoading] = useState(true);
    const [selectedTab, setSelectedTab] = useState('images');
    const API_URL = window.API_URL || '/api';
    const token = localStorage.getItem('token');

    useEffect(() => {
        fetchMedia();
    }, []);

    const fetchMedia = async () => {
        try {
            setLoading(true);
            const response = await fetch(`${API_URL}/ask/media`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setMedia(data.media || { images: [], documents: [], audio: [] });
        } catch (error) {
            console.error('Failed to fetch media:', error);
        } finally {
            setLoading(false);
        }
    };

    const renderMediaItem = (item) => {
        const isImage = item.filepath && (item.filepath.match(/\.(jpg|jpeg|png|gif|webp)$/i));

        return (
            <div
                key={item.id}
                style={{
                    padding: '0.75rem',
                    borderRadius: '12px',
                    border: '2px solid #e2e8f0',
                    background: 'white',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                }}
                onMouseEnter={e => {
                    e.currentTarget.style.borderColor = '#667eea';
                    e.currentTarget.style.boxShadow = '0 2px 8px rgba(102, 126, 234, 0.2)';
                }}
                onMouseLeave={e => {
                    e.currentTarget.style.borderColor = '#e2e8f0';
                    e.currentTarget.style.boxShadow = 'none';
                }}
            >
                {isImage ? (
                    <img
                        src={item.filepath}
                        alt={item.filename}
                        style={{
                            width: '100%',
                            height: '120px',
                            objectFit: 'cover',
                            borderRadius: '8px',
                            marginBottom: '0.5rem'
                        }}
                    />
                ) : (
                    <div style={{
                        width: '100%',
                        height: '80px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        background: 'linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1))',
                        borderRadius: '8px',
                        marginBottom: '0.5rem',
                        fontSize: '2.5rem'
                    }}>
                        {selectedTab === 'documents' ? '📄' : '🎵'}
                    </div>
                )}
                <div style={{ fontSize: '0.75rem', fontWeight: '600', color: '#1e293b', marginBottom: '0.25rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {item.filename}
                </div>
                <div style={{ fontSize: '0.7rem', color: '#94a3b8' }}>
                    {item.session_title}
                </div>
            </div>
        );
    };

    const tabs = [
        { key: 'images', label: 'Images', count: media.images.length },
        { key: 'documents', label: 'Documents', count: media.documents.length },
        { key: 'audio', label: 'Audio', count: media.audio.length }
    ];

    return (
        <div style={{
            width: '100%',
            height: '100%',
            background: 'linear-gradient(to bottom, #f8f9fa, #ffffff)',
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            minHeight: 0
        }}>
            {/* Header */}
            <div style={{
                padding: '1.5rem',
                borderBottom: '2px solid #e2e8f0',
                background: 'white'
            }}>
                <h3 style={{
                    margin: 0,
                    fontSize: '1.25rem',
                    fontWeight: '700',
                    color: '#1e293b',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.5rem'
                }}>
                    <span>🎨</span>
                    <span>{t('ask.mediaLibrary') || 'Media Library'}</span>
                </h3>
                <p style={{
                    margin: '0.5rem 0 0',
                    fontSize: '0.8rem',
                    color: '#64748b'
                }}>
                    {t('ask.mediaDescription') || 'All media across your chats'}
                </p>
            </div>

            {/* Tabs */}
            <div style={{
                display: 'flex',
                gap: '0.25rem',
                padding: '0.75rem',
                background: 'white',
                borderBottom: '1px solid #e2e8f0'
            }}>
                {tabs.map(tab => (
                    <button
                        key={tab.key}
                        onClick={() => setSelectedTab(tab.key)}
                        style={{
                            flex: 1,
                            padding: '0.4rem 0.25rem',
                            borderRadius: '8px',
                            border: selectedTab === tab.key ? '2px solid #667eea' : '2px solid transparent',
                            background: selectedTab === tab.key ? 'rgba(102, 126, 234, 0.1)' : 'transparent',
                            color: selectedTab === tab.key ? '#667eea' : '#64748b',
                            fontSize: '0.7rem',
                            fontWeight: '600',
                            cursor: 'pointer',
                            transition: 'all 0.2s',
                            whiteSpace: 'nowrap',
                            textAlign: 'center'
                        }}
                        onMouseEnter={e => {
                            if (selectedTab !== tab.key) {
                                e.currentTarget.style.background = 'rgba(102, 126, 234, 0.05)';
                            }
                        }}
                        onMouseLeave={e => {
                            if (selectedTab !== tab.key) {
                                e.currentTarget.style.background = 'transparent';
                            }
                        }}
                    >
                        {tab.label} ({tab.count})
                    </button>
                ))}
            </div>

            {/* Media Grid */}
            <div style={{
                flex: 1,
                overflowY: 'auto',
                padding: '1.5rem',
                minHeight: 0
            }}>
                {loading ? (
                    <div style={{ textAlign: 'center', padding: '3rem', color: '#94a3b8' }}>
                        <div className="loading"></div>
                        <p style={{ marginTop: '1rem' }}>{t('common.loading') || 'Loading...'}</p>
                    </div>
                ) : media[selectedTab].length === 0 ? (
                    <div style={{ textAlign: 'center', padding: '3rem', color: '#94a3b8' }}>
                        <div style={{ fontSize: '3rem', marginBottom: '1rem', opacity: 0.5 }}>
                            {selectedTab === 'images' ? '🖼️' : selectedTab === 'documents' ? '📄' : '🎵'}
                        </div>
                        <p>{t('ask.noMedia') || 'No media uploaded yet'}</p>
                    </div>
                ) : (
                    <div style={{
                        display: 'grid',
                        gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))',
                        gap: '1rem'
                    }}>
                        {media[selectedTab].map(renderMediaItem)}
                    </div>
                )}
            </div>
        </div>
    );
}

window.MediaPanel = MediaPanel;
