/**
 * Team Admin > Activity (Audit Log)
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

export default function ActivitySection({ teamId }) {
    const [entries, setEntries] = useState([]);
    const [actions, setActions] = useState([]);
    const [total, setTotal] = useState(0);
    const [page, setPage] = useState(1);
    const [filterAction, setFilterAction] = useState('');
    const [filterResource, setFilterResource] = useState('');
    const [loading, setLoading] = useState(true);
    const perPage = 50;

    const load = useCallback(async () => {
        setLoading(true);
        try {
            const opts = { page, per_page: perPage };
            if (filterAction) opts.action = filterAction;
            if (filterResource) opts.resource_type = filterResource;
            const data = await sw.api.teams.audit(teamId, opts);
            setEntries(data.data || []);
            setTotal(data.total || 0);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, [teamId, page, filterAction, filterResource]);

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

    useEffect(() => {
        sw.api.teams.auditActions(teamId).then(d => setActions(d.actions || [])).catch(() => {});
    }, [teamId]);

    const totalPages = Math.ceil(total / perPage) || 1;

    function fmtDate(d) {
        if (!d) return '\u2014';
        return new Date(d).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' });
    }

    // Extract unique resource types from actions (action format: resource.verb)
    const resourceTypes = [...new Set(actions.map(a => a.split('.')[0]).filter(Boolean))];

    return html`
        <div>
            <div class="form-row" style="margin-bottom:12px;">
                <div class="form-group"><label>Action</label>
                    <select value=${filterAction} onChange=${e => { setFilterAction(e.target.value); setPage(1); }}>
                        <option value="">All</option>
                        ${actions.map(a => html`<option key=${a} value=${a}>${a}</option>`)}
                    </select>
                </div>
                <div class="form-group"><label>Resource</label>
                    <select value=${filterResource} onChange=${e => { setFilterResource(e.target.value); setPage(1); }}>
                        <option value="">All</option>
                        ${resourceTypes.map(r => html`<option key=${r} value=${r}>${r}</option>`)}
                    </select>
                </div>
            </div>

            ${loading
                ? html`<div class="settings-placeholder">Loading\u2026</div>`
                : html`
                    <div class="admin-list">
                        ${entries.length === 0 && html`<div class="empty-hint">No activity entries</div>`}
                        ${entries.map(e => html`
                            <div class="admin-surface-row" key=${e.id} style="font-size:12px;">
                                <span style="width:140px;">${fmtDate(e.created_at)}</span>
                                <span style="width:100px;"><strong>${e.actor_name || '\u2014'}</strong></span>
                                <span class="badge" style="margin:0 4px;">${e.action}</span>
                                <span style="flex:1;color:var(--text-3);">${e.resource_type}/${e.resource_id?.substring(0, 8) || '\u2014'}</span>
                                <span class="text-muted" style="width:100px;">${e.ip_address || ''}</span>
                            </div>
                        `)}
                    </div>

                    <div style="margin-top:12px;display:flex;align-items:center;gap:8px;">
                        <button class="btn-small" disabled=${page <= 1} onClick=${() => setPage(p => p - 1)}>\u2190 Prev</button>
                        <span class="text-muted" style="font-size:12px;">Page ${page} of ${totalPages} (${total} total)</span>
                        <button class="btn-small" disabled=${page >= totalPages} onClick=${() => setPage(p => p + 1)}>Next \u2192</button>
                    </div>
                `
            }
        </div>
    `;
}
