import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '../auth/AuthProvider';
import { MGMT_BASE } from '../auth/authConfig';

const PAGE_SIZE = 20;

// ─── Date presets ──────────────────────────────────────────────────────────────
function getPreset(key) {
    const now   = new Date();
    const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
    switch (key) {
        case 'today':
            return { dateFrom: today.toISOString(), dateTo: null };
        case 'yesterday': {
            const d = new Date(today); d.setUTCDate(d.getUTCDate() - 1);
            const e = new Date(today); e.setUTCMilliseconds(-1);
            return { dateFrom: d.toISOString(), dateTo: e.toISOString() };
        }
        case '7d': {
            const d = new Date(today); d.setUTCDate(d.getUTCDate() - 7);
            return { dateFrom: d.toISOString(), dateTo: null };
        }
        case '30d': {
            const d = new Date(today); d.setUTCDate(d.getUTCDate() - 30);
            return { dateFrom: d.toISOString(), dateTo: null };
        }
        default: return { dateFrom: null, dateTo: null };
    }
}

function isoToLocal(iso) {
    if (!iso) return '';
    const d = new Date(iso);
    const p = n => String(n).padStart(2, '0');
    return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;
}

const PRESETS = [
    { key: 'all',       label: 'All time' },
    { key: 'today',     label: 'Today' },
    { key: 'yesterday', label: 'Yesterday' },
    { key: '7d',        label: 'Last 7 days' },
    { key: '30d',       label: 'Last 30 days' },
    { key: 'custom',    label: 'Custom...' },
];

// ─── Path breadcrumb ──────────────────────────────────────────────────────────
function parsePath(path) {
    const parts = (path || '').replace(/^\/api\//, '').split('/').filter(Boolean);
    const isId  = s => /^[0-9a-f-]{8,}$/i.test(s) || /^\d+$/.test(s) || s.length > 24;
    return parts.map(p => ({ value: p, isId: isId(p) }));
}

function PathCell({ path }) {
    const segs = parsePath(path);
    return (
        <td title={path} style={{ padding: '8px 14px', maxWidth: 420 }}>
            <span style={{ fontFamily: 'monospace', fontSize: 12, display: 'flex', flexWrap: 'wrap', gap: 2, alignItems: 'center' }}>
                {segs.map((seg, i) => (
                    <React.Fragment key={i}>
                        {i > 0 && <span style={{ color: '#cbd5e1', margin: '0 1px' }}>&#8250;</span>}
                        <span style={{
                            color:      seg.isId ? '#7c3aed' : '#1e293b',
                            fontWeight: seg.isId ? 400 : 500,
                            fontStyle:  seg.isId ? 'italic' : 'normal',
                        }}>
                            {seg.value}
                        </span>
                    </React.Fragment>
                ))}
            </span>
        </td>
    );
}

// ─── Status badge ─────────────────────────────────────────────────────────────
function StatusBadge({ code }) {
    const ok   = code >= 200 && code < 300;
    const warn = code >= 400 && code < 500;
    const bg    = ok ? '#dcfce7' : warn ? '#fef9c3' : '#fee2e2';
    const color = ok ? '#15803d' : warn ? '#854d0e' : '#b91c1c';
    return (
        <span style={{ background: bg, color, padding: '2px 8px', borderRadius: 4, fontSize: 11, fontWeight: 700 }}>
            {code}
        </span>
    );
}

function fmt(iso) {
    if (!iso) return '—';
    return new Date(iso).toLocaleString(undefined, {
        month: 'short', day: 'numeric',
        hour: 'numeric', minute: '2-digit', second: '2-digit',
    });
}

function rel(iso) {
    if (!iso) return '';
    const s = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
    if (s < 60)        return s + 's ago';
    if (s < 3600)      return Math.floor(s / 60) + 'm ago';
    if (s < 86400)     return Math.floor(s / 3600) + 'h ago';
    if (s < 604800)    return Math.floor(s / 86400) + 'd ago';
    return new Date(iso).toLocaleDateString();
}

// ─── Component ────────────────────────────────────────────────────────────────
export default function ActivityPanel() {
    const { getAccessToken } = useAuth();

    const [items,        setItems]        = useState([]);
    const [total,        setTotal]        = useState(0);
    const [loading,      setLoading]      = useState(false);
    const [error,        setError]        = useState(null);
    const [page,         setPage]         = useState(1);

    const [staff,        setStaff]        = useState([]);
    const [staffLoading, setStaffLoading] = useState(true);
    const [filterOid,    setFilterOid]    = useState('');

    const [preset,     setPreset]     = useState('all');
    const [dateFrom,   setDateFrom]   = useState(null);
    const [dateTo,     setDateTo]     = useState(null);
    const [customFrom, setCustomFrom] = useState('');
    const [customTo,   setCustomTo]   = useState('');

    useEffect(() => {
        async function loadStaff() {
            try {
                const token = await getAccessToken();
                const res   = await fetch(MGMT_BASE + '/api/monitoring/staff', {
                    headers: { Authorization: 'Bearer ' + token },
                });
                const data = await res.json();
                if (data.ok) setStaff(data.staff || []);
            } catch (e) {
                console.warn('[Activity] Staff list failed:', e.message);
            } finally {
                setStaffLoading(false);
            }
        }
        loadStaff();
    }, [getAccessToken]);

    const load = useCallback(async (pg, oid, from, to) => {
        setLoading(true);
        setError(null);
        try {
            const token = await getAccessToken();
            const body  = { page: pg, pageSize: PAGE_SIZE };
            if (oid)  body.oid      = oid;
            if (from) body.dateFrom = from;
            if (to)   body.dateTo   = to;

            const res = await fetch(MGMT_BASE + '/api/monitoring/activity', {
                method:  'POST',
                headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
                body:    JSON.stringify(body),
            });
            const data = await res.json();
            if (!data.ok && !data.items) throw new Error(data.error || 'HTTP ' + res.status);
            setItems(data.items || []);
            setTotal(data.total || 0);
            setPage(pg);
        } catch (e) {
            setError(e.message);
        } finally {
            setLoading(false);
        }
    }, [getAccessToken]);

    useEffect(() => { load(1, '', null, null); }, []);

    const applyPreset = (key) => {
        setPreset(key);
        if (key === 'custom') return;
        const { dateFrom: f, dateTo: t } = getPreset(key);
        setDateFrom(f);
        setDateTo(t);
        setCustomFrom(f ? isoToLocal(f) : '');
        setCustomTo(t ? isoToLocal(t) : '');
        load(1, filterOid, f, t);
    };

    const applyCustom = () => {
        const f = customFrom ? new Date(customFrom).toISOString() : null;
        const t = customTo   ? new Date(customTo).toISOString()   : null;
        setDateFrom(f);
        setDateTo(t);
        load(1, filterOid, f, t);
    };

    const handleStaffChange = (oid) => {
        setFilterOid(oid);
        load(1, oid, dateFrom, dateTo);
    };

    const totalPages   = Math.max(1, Math.ceil(total / PAGE_SIZE));
    const selectedName = staff.find(s => s.oid === filterOid) && staff.find(s => s.oid === filterOid).displayName;
    const presetLabel  = (PRESETS.find(p => p.key === preset) || {}).label || '';

    const pill = (active) => ({
        padding: '6px 12px', borderRadius: 20, fontSize: 12, cursor: 'pointer',
        border:      active ? '1.5px solid #3b82f6' : '1px solid #e2e8f0',
        background:  active ? '#eff6ff' : '#f8fafc',
        color:       active ? '#1d4ed8' : '#475569',
        fontWeight:  active ? 600 : 400,
    });

    const pageBtn = (disabled) => ({
        padding: '6px 14px', borderRadius: 5, border: '1px solid #e2e8f0',
        background: disabled ? '#f8fafc' : '#fff',
        cursor: disabled ? 'default' : 'pointer',
        fontSize: 13, color: disabled ? '#cbd5e1' : '#374151',
    });

    return (
        <div style={{ padding: 24, maxWidth: 1100 }}>

            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
                <div>
                    <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: '#0f172a' }}>Admin Activity Log</h2>
                    <p style={{ margin: '4px 0 0', fontSize: 13, color: '#64748b' }}>
                        All mutating operations performed by staff members
                    </p>
                </div>
                <button
                    onClick={() => load(page, filterOid, dateFrom, dateTo)}
                    disabled={loading}
                    style={{ padding: '7px 16px', borderRadius: 6, border: '1px solid #e2e8f0', background: '#f8fafc', cursor: 'pointer', fontSize: 13, color: '#374151' }}
                >
                    {loading ? 'Loading...' : '↻ Refresh'}
                </button>
            </div>

            {/* Filter bar */}
            <div style={{ display: 'flex', gap: 10, marginBottom: 8, flexWrap: 'wrap', alignItems: 'center' }}>
                <div style={{ position: 'relative', minWidth: 220 }}>
                    <select
                        value={filterOid}
                        onChange={e => handleStaffChange(e.target.value)}
                        disabled={staffLoading}
                        style={{
                            width: '100%', padding: '7px 28px 7px 12px', borderRadius: 6,
                            border: '1px solid #e2e8f0', fontSize: 13, background: '#fff',
                            color: filterOid ? '#1e293b' : '#94a3b8', cursor: 'pointer', appearance: 'none',
                        }}
                    >
                        <option value="">{staffLoading ? 'Loading...' : 'All staff (' + staff.length + ')'}</option>
                        {staff.map(s => (
                            <option key={s.oid} value={s.oid}>
                                {s.displayName || s.email}{s.displayName && s.email ? ' — ' + s.email : ''}
                            </option>
                        ))}
                    </select>
                    <span style={{ position: 'absolute', right: 9, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: '#94a3b8', fontSize: 11 }}>▾</span>
                </div>

                <span style={{ color: '#e2e8f0' }}>|</span>

                {PRESETS.map(p => (
                    <button key={p.key} onClick={() => applyPreset(p.key)} style={pill(preset === p.key)}>
                        {p.label}
                    </button>
                ))}

                {filterOid && (
                    <button onClick={() => handleStaffChange('')} style={{ ...pill(false), borderRadius: 6 }}>
                        × Clear
                    </button>
                )}
            </div>

            {/* Custom range inputs */}
            {preset === 'custom' && (
                <div style={{
                    display: 'flex', gap: 8, alignItems: 'center', marginBottom: 12,
                    padding: '10px 14px', borderRadius: 8, background: '#f8fafc', border: '1px solid #e2e8f0',
                }}>
                    <label style={{ fontSize: 12, color: '#64748b', whiteSpace: 'nowrap' }}>From</label>
                    <input type="datetime-local" value={customFrom} onChange={e => setCustomFrom(e.target.value)}
                        style={{ padding: '5px 10px', borderRadius: 6, border: '1px solid #e2e8f0', fontSize: 13 }} />
                    <label style={{ fontSize: 12, color: '#64748b', whiteSpace: 'nowrap' }}>To</label>
                    <input type="datetime-local" value={customTo} onChange={e => setCustomTo(e.target.value)}
                        style={{ padding: '5px 10px', borderRadius: 6, border: '1px solid #e2e8f0', fontSize: 13 }} />
                    <button onClick={applyCustom}
                        style={{ padding: '6px 16px', borderRadius: 6, border: 'none', background: '#3b82f6', color: '#fff', cursor: 'pointer', fontSize: 13, fontWeight: 600 }}>
                        Apply
                    </button>
                </div>
            )}

            {error && (
                <div style={{ padding: 12, borderRadius: 6, background: '#fee2e2', color: '#b91c1c', marginBottom: 12, fontSize: 13 }}>
                    {error}
                </div>
            )}

            {/* Table */}
            <div style={{ border: '1px solid #e2e8f0', borderRadius: 8, overflow: 'hidden', background: '#fff' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                    <thead>
                        <tr style={{ background: '#f8fafc', borderBottom: '1px solid #e2e8f0' }}>
                            {['Timestamp', 'Who', 'Path', 'Status'].map(h => (
                                <th key={h} style={{ padding: '10px 14px', textAlign: 'left', fontWeight: 600, color: '#475569', fontSize: 12 }}>
                                    {h}
                                </th>
                            ))}
                        </tr>
                    </thead>
                    <tbody>
                        {loading && items.length === 0 ? (
                            <tr><td colSpan={4} style={{ padding: 32, textAlign: 'center', color: '#94a3b8' }}>Loading...</td></tr>
                        ) : items.length === 0 ? (
                            <tr><td colSpan={4} style={{ padding: 32, textAlign: 'center', color: '#94a3b8' }}>No activity in this range.</td></tr>
                        ) : items.map((row, i) => (
                            <React.Fragment key={row.activityId}>
                            <tr style={{
                                borderBottom: row.filter ? 'none' : '1px solid #f1f5f9',
                                background: i % 2 === 0 ? '#fff' : '#fafafa',
                                opacity: loading ? 0.6 : 1, transition: 'opacity 0.15s',
                            }}>
                                <td title={rel(row.activityAt)} style={{ padding: '8px 14px', whiteSpace: 'nowrap' }}>
                                    <span style={{ color: '#475569', fontSize: 12, fontFamily: 'monospace' }}>
                                        {fmt(row.activityAt)}
                                    </span>
                                </td>
                                <td title={row.email || row.oid || ''} style={{ padding: '8px 14px', whiteSpace: 'nowrap' }}>
                                    <span style={{ fontWeight: 500, color: '#1e293b' }}>
                                        {row.displayName || row.email || row.oid || '—'}
                                    </span>
                                </td>
                                <PathCell path={row.path} />
                                <td style={{ padding: '8px 14px' }}>
                                    <StatusBadge code={row.statusCode} />
                                </td>
                            </tr>
                            {row.filter && (
                                <tr style={{
                                    borderBottom: '1px solid #f1f5f9',
                                    background: i % 2 === 0 ? '#fff' : '#fafafa',
                                    opacity: loading ? 0.6 : 1,
                                }}>
                                    <td colSpan={4} style={{ padding: '0 14px 7px', textAlign: 'center' }}>
                                        <span style={{
                                            fontFamily: 'monospace', fontSize: 11,
                                            color: '#94a3b8', letterSpacing: '0.01em',
                                        }}>
                                            {row.filter}
                                        </span>
                                    </td>
                                </tr>
                            )}
                            </React.Fragment>
                        ))}
                    </tbody>
                </table>
            </div>

            {/* Pagination — always visible */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 12 }}>
                <span style={{ fontSize: 12, color: '#64748b' }}>
                    {total.toLocaleString()} record{total !== 1 ? 's' : ''}
                    {selectedName ? ' · ' + selectedName : ''}
                    {preset !== 'all' ? ' · ' + presetLabel.toLowerCase() : ''}
                </span>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                    <button disabled={page <= 1 || loading} onClick={() => load(page - 1, filterOid, dateFrom, dateTo)}
                        style={pageBtn(page <= 1 || loading)}>
                        ← Prev
                    </button>
                    <span style={{ fontSize: 12, color: '#94a3b8', minWidth: 70, textAlign: 'center' }}>
                        {page} / {totalPages}
                    </span>
                    <button disabled={page >= totalPages || loading} onClick={() => load(page + 1, filterOid, dateFrom, dateTo)}
                        style={pageBtn(page >= totalPages || loading)}>
                        Next →
                    </button>
                </div>
            </div>
        </div>
    );
}
