import React, { useState, useEffect, useCallback } from 'react';
import { useAdmin } from '../../context/AdminContext';

// ─── Helpers ──────────────────────────────────────────────────────────────────
const fmtDateTime = (iso) => {
    if (!iso) return '—';
    return new Date(iso).toLocaleString('en-US', {
        month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', second: '2-digit',
    });
};

const fmtDuration = (ms) => {
    if (ms == null) return '—';
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(1)}s`;
};

function StatusBadge({ code }) {
    if (!code) return <span style={{ color: '#94a3b8' }}>—</span>;
    let bg, color;
    if (code < 300)      { bg = '#dcfce7'; color = '#166534'; }
    else if (code < 400) { bg = '#dbeafe'; color = '#1e40af'; }
    else if (code < 500) { bg = '#fef9c3'; color = '#854d0e'; }
    else                 { bg = '#fee2e2'; color = '#991b1b'; }

    return (
        <span style={{
            background: bg, color, padding: '2px 7px', borderRadius: 10,
            fontSize: 11, fontWeight: 600,
        }}>
            {code}
        </span>
    );
}

function MethodBadge({ method }) {
    if (!method) return null;
    const colors = {
        GET:    { bg: '#eff6ff', color: '#1d4ed8' },
        POST:   { bg: '#f0fdf4', color: '#166534' },
        PUT:    { bg: '#fffbeb', color: '#92400e' },
        PATCH:  { bg: '#fdf4ff', color: '#6b21a8' },
        DELETE: { bg: '#fff1f2', color: '#9f1239' },
    };
    const s = colors[method] || { bg: '#f1f5f9', color: '#475569' };
    return (
        <span style={{
            background: s.bg, color: s.color, padding: '2px 7px', borderRadius: 10,
            fontSize: 11, fontWeight: 700, letterSpacing: 0.4,
        }}>
            {method}
        </span>
    );
}

// ─── Component ────────────────────────────────────────────────────────────────
export default function ClientActivityPanel() {
    const { apiCall } = useAdmin();

    // Client picker state
    const [clients, setClients]             = useState([]);
    const [clientsLoading, setClientsLoading] = useState(true);
    const [selectedClientId, setSelectedClientId] = useState('');
    const [selectedClientName, setSelectedClientName] = useState('');

    // Activity list state
    const [items, setItems]         = useState([]);
    const [totalCount, setTotalCount] = useState(0);
    const [page, setPage]           = useState(1);
    const pageSize                  = 50;
    const [loading, setLoading]     = useState(false);
    const [error, setError]         = useState(null);

    // Filters
    const [pathFilter, setPathFilter]     = useState('');
    const [statusFilter, setStatusFilter] = useState('');
    const [dateFrom, setDateFrom]         = useState('');
    const [dateTo, setDateTo]             = useState('');

    // ── Load client list for picker ──────────────────────────────────────────
    useEffect(() => {
        (async () => {
            setClientsLoading(true);
            try {
                const result = await apiCall('/api/admin/clients/list', 'POST', { page: 1, pageSize: 200 });
                if (result?.ok && Array.isArray(result.clients)) {
                    const active = result.clients.filter(c => c.cltStatus === 'Active' || c.status === 'Active');
                    setClients(active.length ? active : result.clients);
                }
            } catch { /* ignore */ }
            finally { setClientsLoading(false); }
        })();
    }, [apiCall]);

    // ── Load activity for selected client ────────────────────────────────────
    const loadActivity = useCallback(async (clientId, pg = 1) => {
        if (!clientId) return;
        setLoading(true);
        setError(null);
        try {
            const body = {
                clientId,
                page: pg,
                pageSize,
                pathContains: pathFilter   || undefined,
                statusCode:   statusFilter ? parseInt(statusFilter) : undefined,
                dateFrom:     dateFrom     || undefined,
                dateTo:       dateTo       || undefined,
            };
            const result = await apiCall('/api/admin/client-activity/list', 'POST', body);
            if (result?.ok) {
                setItems(Array.isArray(result.items) ? result.items : []);
                setTotalCount(result.totalCount ?? 0);
                setPage(pg);
            } else {
                setError(result?.error || 'Failed to load activity');
            }
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }, [apiCall, pathFilter, statusFilter, dateFrom, dateTo]);

    const handleClientChange = (e) => {
        const cid  = e.target.value;
        const name = clients.find(c => (c.cltId || c.clientId) === cid)?.cltName || cid;
        setSelectedClientId(cid);
        setSelectedClientName(name);
        setPage(1);
        setItems([]);
        setTotalCount(0);
        if (cid) loadActivity(cid, 1);
    };

    const handleSearch = () => {
        if (selectedClientId) loadActivity(selectedClientId, 1);
    };

    const totalPages = Math.ceil(totalCount / pageSize);

    // ── Render ────────────────────────────────────────────────────────────────
    return (
        <div className="data-panel" style={{ maxWidth: 1100 }}>

            {/* Header */}
            <div className="panel-header">
                <div>
                    <h3 className="panel-title">Client Activity</h3>
                    <p className="panel-subtitle">
                        Gateway request log from <code>tbAccessLog</code>
                    </p>
                </div>
            </div>

            {/* Client picker + filters */}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 20, alignItems: 'flex-end' }}>
                <div style={{ flex: '0 0 220px' }}>
                    <label className="form-label" style={{ marginBottom: 4 }}>Client</label>
                    <select
                        className="form-select"
                        value={selectedClientId}
                        onChange={handleClientChange}
                        disabled={clientsLoading}
                    >
                        <option value="">
                            {clientsLoading ? 'Loading…' : '— select a client —'}
                        </option>
                        {clients.map(c => {
                            const id   = c.cltId   || c.clientId;
                            const name = c.cltName || c.name;
                            return <option key={id} value={id}>{name}</option>;
                        })}
                    </select>
                </div>

                <div style={{ flex: '1 1 160px', minWidth: 140 }}>
                    <label className="form-label" style={{ marginBottom: 4 }}>Path contains</label>
                    <input
                        className="form-input"
                        type="text"
                        placeholder="/api/initiative"
                        value={pathFilter}
                        onChange={e => setPathFilter(e.target.value)}
                        onKeyDown={e => e.key === 'Enter' && handleSearch()}
                    />
                </div>

                <div style={{ flex: '0 0 100px' }}>
                    <label className="form-label" style={{ marginBottom: 4 }}>Status code</label>
                    <select
                        className="form-select"
                        value={statusFilter}
                        onChange={e => setStatusFilter(e.target.value)}
                    >
                        <option value="">All</option>
                        <option value="200">200</option>
                        <option value="400">400</option>
                        <option value="401">401</option>
                        <option value="403">403</option>
                        <option value="404">404</option>
                        <option value="500">500</option>
                    </select>
                </div>

                <div style={{ flex: '0 0 160px' }}>
                    <label className="form-label" style={{ marginBottom: 4 }}>From</label>
                    <input
                        className="form-input"
                        type="date"
                        value={dateFrom}
                        onChange={e => setDateFrom(e.target.value)}
                    />
                </div>

                <div style={{ flex: '0 0 160px' }}>
                    <label className="form-label" style={{ marginBottom: 4 }}>To</label>
                    <input
                        className="form-input"
                        type="date"
                        value={dateTo}
                        onChange={e => setDateTo(e.target.value)}
                    />
                </div>

                <button
                    className="btn-action"
                    onClick={handleSearch}
                    disabled={!selectedClientId || loading}
                    style={{ alignSelf: 'flex-end' }}
                >
                    {loading ? 'Loading…' : 'Search'}
                </button>
            </div>

            {/* Empty prompt */}
            {!selectedClientId && (
                <div className="empty-state">
                    Select a client to view their activity log.
                </div>
            )}

            {/* Error */}
            {error && <div className="error-message">{error}</div>}

            {/* Summary bar */}
            {selectedClientId && !loading && items.length > 0 && (
                <div style={{
                    display: 'flex', gap: 20, padding: '8px 12px', background: '#f8fafc',
                    borderRadius: 6, marginBottom: 12, fontSize: 13, color: '#475569',
                    border: '1px solid #e2e8f0',
                }}>
                    <span><strong>{selectedClientName}</strong></span>
                    <span>{totalCount.toLocaleString()} request{totalCount !== 1 ? 's' : ''}</span>
                    {totalPages > 1 && <span>Page {page} of {totalPages}</span>}
                </div>
            )}

            {/* Activity table */}
            {selectedClientId && !loading && items.length > 0 && (
                <>
                    <table className="data-table" style={{ fontSize: 12 }}>
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>Method</th>
                                <th>Path</th>
                                <th>Status</th>
                                <th>Duration</th>
                                <th>User</th>
                                <th>IP</th>
                            </tr>
                        </thead>
                        <tbody>
                            {items.map(item => (
                                <tr key={item.id}
                                    style={item.statusCode >= 500 ? { background: '#fff1f2' }
                                          : item.statusCode >= 400 ? { background: '#fffbeb' }
                                          : undefined}
                                >
                                    <td style={{ whiteSpace: 'nowrap', color: '#64748b' }}>
                                        {fmtDateTime(item.timestamp)}
                                    </td>
                                    <td><MethodBadge method={item.method} /></td>
                                    <td style={{ fontFamily: 'monospace', fontSize: 11, maxWidth: 320, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                        <span title={item.path + (item.queryString || '')}>
                                            {item.path}
                                            {item.queryString && (
                                                <span style={{ color: '#94a3b8' }}>{item.queryString}</span>
                                            )}
                                        </span>
                                    </td>
                                    <td><StatusBadge code={item.statusCode} /></td>
                                    <td style={{ color: '#64748b', whiteSpace: 'nowrap' }}>
                                        {fmtDuration(item.durationMs)}
                                    </td>
                                    <td style={{ color: '#64748b', fontSize: 11 }}>
                                        {item.userEmail || item.userDisplayName || '—'}
                                    </td>
                                    <td style={{ color: '#94a3b8', fontSize: 11, fontFamily: 'monospace' }}>
                                        {item.ipAddress || '—'}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>

                    {/* Pagination */}
                    {totalPages > 1 && (
                        <div style={{ display: 'flex', gap: 8, marginTop: 16, justifyContent: 'center' }}>
                            <button
                                className="btn-cancel"
                                disabled={page <= 1}
                                onClick={() => loadActivity(selectedClientId, page - 1)}
                            >
                                ← Prev
                            </button>
                            <span style={{ padding: '6px 12px', fontSize: 13, color: '#475569' }}>
                                {page} / {totalPages}
                            </span>
                            <button
                                className="btn-cancel"
                                disabled={page >= totalPages}
                                onClick={() => loadActivity(selectedClientId, page + 1)}
                            >
                                Next →
                            </button>
                        </div>
                    )}
                </>
            )}

            {/* Empty result */}
            {selectedClientId && !loading && !error && items.length === 0 && (
                <div className="empty-state">
                    No activity found for this client with the current filters.
                </div>
            )}
        </div>
    );
}
