import React from 'react';
import { useAdmin } from '../../context/AdminContext';

export default function SessionsPanel() {
    const { data, apiCall, refresh } = useAdmin();
    const sessions = data.sessions || [];

    const revokeSession = async (sessionId) => {
        if (!confirm('Are you sure you want to revoke this session?')) return;
        const result = await apiCall(`/api/admin/sessions/${sessionId}/revoke`, 'POST');
        if (result.ok) refresh();
        else alert(result.error || 'Failed to revoke session');
    };

    const cleanupSessions = async () => {
        if (!confirm('This will delete all expired sessions older than 30 days. Continue?')) return;
        const result = await apiCall('/api/admin/sessions/cleanup?daysOld=30', 'POST');
        if (result.ok) {
            alert(`Cleaned up ${result.rowsDeleted} expired sessions`);
            refresh();
        }
        else alert(result.error || 'Failed to cleanup sessions');
    };

    return (
        <div className="table-panel">
            <div className="panel-header">
                <h2>Active Sessions</h2>
                <button className="btn-action" onClick={cleanupSessions}>
                    Cleanup Expired
                </button>
            </div>

            <table className="data-table">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Client</th>
                        <th>Last Activity</th>
                        <th>Expires</th>
                        <th>IP Address</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {sessions.map(session => (
                        <tr key={session.sessionId}>
                            <td>
                                <div>{session.userEmail}</div>
                                <small className="text-muted">{session.displayName}</small>
                            </td>
                            <td>{session.clientName}</td>
                            <td>{new Date(session.lastActivity).toLocaleString()}</td>
                            <td>{new Date(session.expiresAt).toLocaleString()}</td>
                            <td>{session.ipAddress || '-'}</td>
                            <td>
                                <button
                                    className="btn-small btn-danger"
                                    onClick={() => revokeSession(session.sessionId)}
                                >
                                    Revoke
                                </button>
                            </td>
                        </tr>
                    ))}
                    {sessions.length === 0 && (
                        <tr><td colSpan="6" className="empty-row">No active sessions</td></tr>
                    )}
                </tbody>
            </table>
        </div>
    );
}
