import { useEffect, useState } from '@wordpress/element';
import Layout from '../layout/Layout';
import { getTokenSummary, getTokenLogs, adminRevokeToken } from '../../api/local';
import { showPromiseToast } from '../../utils';

const LiveMonitor = () => {
    const [summary, setSummary] = useState({ active: 0, revoked: 0, expired: 0, error: 0 });
    const [activeTokens, setActiveTokens] = useState([]);

    const loadSummary = () => {
        const res = getTokenSummary().then((data) => setSummary(data?.summary || {}));
        showPromiseToast(res, 'Updating token summary');
    };

    const loadActiveTokens = () => {
        const res = getTokenLogs({ status: 'active', per_page: 20 }).then((data) => setActiveTokens(data?.logs || []));
        showPromiseToast(res, 'Fetching active tokens');
    };

    useEffect(() => {
        loadSummary();
        loadActiveTokens();
    }, []);

    const handleRevoke = (hash) => {
        const res = adminRevokeToken(hash).then(() => {
            loadSummary();
            loadActiveTokens();
        });
        showPromiseToast(res, 'Revoking token', 'Token revoked');
    };

    return (
        <Layout>
            <div className="space-y-8">
                <div className="bg-white rounded p-6">
                    <div className="flex items-center justify-between">
                        <div>
                            <h2 className="text-2xl font-bold text-gray-900">Live Token Monitor</h2>
                            <p className="text-gray-600 text-sm mt-1">Realtime snapshot of issued tokens across your site.</p>
                        </div>
                        <button
                            type="button"
                            className="rounded-md bg-gray-800 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-gray-900"
                            onClick={() => {
                                loadSummary();
                                loadActiveTokens();
                            }}
                        >
                            Refresh
                        </button>
                    </div>

                    <dl className="mt-6 grid grid-cols-1 gap-4 md:grid-cols-4">
                        {Object.entries(summary).map(([key, value]) => (
                            <div key={key} className="rounded-lg bg-gray-50 px-4 py-4">
                                <dt className="text-sm font-medium text-gray-500 capitalize">{key}</dt>
                                <dd className="mt-1 text-3xl font-semibold text-gray-900">{value}</dd>
                            </div>
                        ))}
                    </dl>
                </div>

                <div className="bg-white rounded p-6">
                    <h3 className="text-xl font-semibold text-gray-900">Active Tokens</h3>
                    <p className="text-sm text-gray-600">Force logout or revoke access with a click.</p>

                    <div className="mt-4 overflow-x-auto">
                        <table className="min-w-full divide-y divide-gray-200">
                            <thead className="bg-gray-50">
                            <tr>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">User</th>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Issued</th>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Expires</th>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Device</th>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                            </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200 bg-white">
                            {activeTokens.map((token) => (
                                <tr key={token.id}>
                                    <td className="px-3 py-3 text-sm text-gray-900">#{token.user_id}</td>
                                    <td className="px-3 py-3 text-sm text-gray-500">{token.issued_at}</td>
                                    <td className="px-3 py-3 text-sm text-gray-500">{token.expires_at}</td>
                                    <td className="px-3 py-3 text-sm text-gray-500">{token.device}</td>
                                    <td className="px-3 py-3 text-sm">
                                        <button
                                            type="button"
                                            className="text-red-600 hover:text-red-800 text-sm font-medium"
                                            onClick={() => handleRevoke(token.token_hash)}
                                        >
                                            Force Revoke
                                        </button>
                                    </td>
                                </tr>
                            ))}
                            {!activeTokens.length && (
                                <tr>
                                    <td colSpan="5" className="px-3 py-6 text-center text-sm text-gray-500">
                                        No active tokens.
                                    </td>
                                </tr>
                            )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </Layout>
    );
};

export default LiveMonitor;


