/**
 * SessionSidebar.jsx - Chat History Sidebar
 */

const { useState } = React;

function SessionSidebar({ sessions, activeSessionId, onSelectSession, onNewChat, onDeleteSession, onRenameSession, t }) {
    return (
        <div style={{
            width: '280px',
            height: '100%',
            background: 'var(--card-bg, rgba(255, 255, 255, 0.98))',
            borderRight: '1px solid var(--border-color, rgba(0,0,0,0.08))',
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            minHeight: 0
        }}>
            {/* Header */}
            <div style={{
                padding: '1rem 1.5rem',
                borderBottom: '2px solid #e2e8f0',
                background: 'white'
            }}>
                <h3 style={{
                    margin: 0,
                    fontSize: '1.125rem',
                    fontWeight: '700',
                    color: '#1e293b'
                }}>
                    💬 {t('ask.history') || 'Chat History'}
                </h3>
            </div>

            {/* New Chat Button */}
            <div style={{
                padding: '1rem',
                borderBottom: '1px solid #e2e8f0',
                background: 'white'
            }}>
                <button
                    onClick={onNewChat}
                    style={{
                        width: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        gap: '0.5rem',
                        padding: '0.75rem 1rem',
                        background: 'linear-gradient(135deg, #667eea, #764ba2)',
                        color: 'white',
                        border: 'none',
                        borderRadius: '12px',
                        fontSize: '0.9rem',
                        fontWeight: '600',
                        cursor: 'pointer',
                        transition: 'all 0.2s',
                        boxShadow: '0 2px 8px rgba(102, 126, 234, 0.3)'
                    }}
                    onMouseEnter={e => {
                        e.currentTarget.style.transform = 'translateY(-1px)';
                        e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.4)';
                    }}
                    onMouseLeave={e => {
                        e.currentTarget.style.transform = 'translateY(0)';
                        e.currentTarget.style.boxShadow = '0 2px 8px rgba(102, 126, 234, 0.3)';
                    }}
                >
                    <span style={{ fontSize: '1.1rem' }}>✨</span>
                    <span>{t('ask.newChat') || 'New Chat'}</span>
                </button>
            </div>
            {/* Sessions List */}
            <div style={{
                flex: 1,
                overflowY: 'auto',
                padding: '1rem',
                minHeight: 0
            }}>
                {sessions.length === 0 ? (
                    <div style={{
                        textAlign: 'center',
                        padding: '3rem 1.5rem',
                        color: '#94a3b8'
                    }}>
                        <div style={{ fontSize: '3rem', marginBottom: '1rem', opacity: 0.5 }}>💬</div>
                        <p style={{ fontSize: '0.9rem', lineHeight: '1.6' }}>
                            {t('ask.noSessions')}
                        </p>
                    </div>
                ) : (
                    sessions.map(session => (
                        <SessionCard
                            key={session.id}
                            session={session}
                            isActive={session.id === activeSessionId}
                            onClick={() => onSelectSession(session.id)}
                            onDelete={(e) => onDeleteSession(session.id, e)}
                            onRename={onRenameSession}
                        />
                    ))
                )}
            </div>
        </div>
    );
}


function SessionCard({ session, isActive, onClick, onDelete, onRename }) {
    const [isHovered, setIsHovered] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [editTitle, setEditTitle] = useState(session.title);

    const handleDelete = async (e, sessionId) => {
        e.stopPropagation(); // Prevent triggering session selection
        if (onDelete) { // Changed onDeleteSession to onDelete as per prop
            await onDelete(e); // Pass the event directly to the onDelete prop
        }
    };

    const handleRename = async (e) => {
        e.stopPropagation();
        if (!editTitle.trim() || editTitle === session.title) {
            setIsEditing(false);
            setEditTitle(session.title);
            return;
        }

        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`${API_URL}/ask/sessions/${session.id}/rename?new_title=${encodeURIComponent(editTitle)}`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (response.ok) {
                onRename(session.id, editTitle);
                setIsEditing(false);
            }
        } catch (error) {
            console.error('Failed to rename:', error);
            setEditTitle(session.title);
            setIsEditing(false);
        }
    };

    return (
        <div
            onClick={onClick}
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
            style={{
                padding: '0.75rem 1rem',
                margin: '0.5rem 0',
                borderRadius: '12px',
                cursor: 'pointer',
                background: isActive
                    ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
                    : isHovered
                        ? 'rgba(102, 126, 234, 0.08)'
                        : 'transparent',
                border: `1px solid ${isActive ? 'transparent' : 'var(--border-color, rgba(0,0,0,0.06))'}`,
                transition: 'all 0.2s ease',
                position: 'relative',
                color: isActive ? 'white' : 'var(--text-primary, #1e293b)'
            }}
        >
            {isEditing ? (
                <input
                    type="text"
                    value={editTitle}
                    onChange={(e) => setEditTitle(e.target.value)}
                    onBlur={handleRename}
                    onKeyDown={(e) => {
                        if (e.key === 'Enter') handleRename(e);
                        if (e.key === 'Escape') { setIsEditing(false); setEditTitle(session.title); }
                        e.stopPropagation();
                    }}
                    onClick={(e) => e.stopPropagation()}
                    autoFocus
                    style={{
                        width: '100%',
                        padding: '0.25rem',
                        background: 'white',
                        border: '2px solid #667eea',
                        borderRadius: '6px',
                        fontSize: '0.875rem',
                        fontWeight: '600',
                        color: '#1e293b',
                        outline: 'none'
                    }}
                />
            ) : (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    gap: '0.5rem'
                }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{
                            fontSize: '0.875rem',
                            fontWeight: '600',
                            marginBottom: '0.25rem',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis'
                        }}>
                            {session.title}
                        </div>
                        {session.last_message_preview && (
                            <div style={{
                                fontSize: '0.75rem',
                                opacity: isActive ? 0.9 : 0.6,
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis'
                            }}>
                                {session.last_message_preview}
                            </div>
                        )}
                    </div>

                    {isHovered && !isActive && (
                        <div style={{ display: 'flex', gap: '0.25rem' }}>
                            <button
                                onClick={(e) => { e.stopPropagation(); setIsEditing(true); }}
                                style={{
                                    background: 'transparent',
                                    border: 'none',
                                    padding: '0.25rem',
                                    cursor: 'pointer',
                                    opacity: 0.7,
                                    fontSize: '1rem'
                                }}
                                title="Rename"
                            >
                                ✏️
                            </button>
                            <button
                                onClick={onDelete}
                                style={{
                                    background: 'transparent',
                                    border: 'none',
                                    padding: '0.25rem',
                                    cursor: 'pointer',
                                    opacity: 0.7,
                                    fontSize: '1rem'
                                }}
                                title="Delete"
                            >
                                🗑️
                            </button>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

window.SessionSidebar = SessionSidebar;

