"use client";

// Security Advisory Feeds — CISA KEV (actively exploited) plus configurable
// RSS sources (ZDI / CERT-EU / BSI / Cisco / custom). These sources publish
// ahead of NVD/cvelistV5, so this page is the early-warning surface.
import { useEffect, useState } from 'react';
import api from '../../lib/api';

type FeedItem = { title: string; link: string; date: string; summary: string };
type Feed = { id: string; name: string; url: string; enabled: boolean; items: FeedItem[]; error: string | null };
type FeedCfg = { id: string; name: string; url: string; enabled: boolean };

export default function AdvisoriesPage() {
    const [kev, setKev] = useState<any[]>([]);
    const [feeds, setFeeds] = useState<Feed[]>([]);
    const [fetchedAt, setFetchedAt] = useState<string | null>(null);
    const [loading, setLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);
    const [userRole, setUserRole] = useState('');
    const [openFeed, setOpenFeed] = useState<string | null>(null);
    // Admin config editor
    const [cfg, setCfg] = useState<FeedCfg[]>([]);
    const [showCfg, setShowCfg] = useState(false);
    const [cfgMsg, setCfgMsg] = useState('');

    const load = async () => {
        try {
            const [k, f, me] = await Promise.all([
                api.get('/api/v1/advisories/kev-recent?limit=15').catch(() => ({ data: { items: [] } })),
                api.get('/api/v1/advisories/feeds').catch(() => ({ data: { feeds: [], fetched_at: null } })),
                api.get('/auth/me').catch(() => ({ data: {} })),
            ]);
            setKev(k.data?.items || []);
            setFeeds(f.data?.feeds || []);
            setFetchedAt(f.data?.fetched_at || null);
            setUserRole(me.data?.role || '');
            // config mirror for the admin editor (from the cache view — same rows)
            setCfg((f.data?.feeds || []).map((x: Feed) => ({ id: x.id, name: x.name, url: x.url, enabled: x.enabled })));
        } finally { setLoading(false); }
    };
    useEffect(() => { load(); }, []);

    const refresh = async () => {
        setRefreshing(true);
        try { await api.post('/api/v1/advisories/feeds/refresh'); await load(); }
        catch (e: any) { alert(e?.response?.data?.detail || 'Refresh failed'); }
        finally { setRefreshing(false); }
    };

    const saveCfg = async () => {
        try {
            await api.put('/api/v1/settings/advisory_feeds_config', { value: JSON.stringify(cfg) });
            setCfgMsg('Saved — refreshing feeds…');
            await api.post('/api/v1/advisories/feeds/refresh').catch(() => { });
            await load();
            setCfgMsg('Saved.');
        } catch (e: any) {
            setCfgMsg(e?.response?.data?.detail || 'Save failed');
        }
    };

    const canEdit = userRole === 'admin' || userRole === 'editor';

    if (loading) return <div className="p-8">Loading Advisories...</div>;

    return (
        <div className="p-8">
            <div className="flex items-start justify-between mb-6">
                <div>
                    <h2 className="text-3xl font-bold text-gray-900 font-mono">Security Advisory Feeds</h2>
                    <p className="mt-1 text-sm text-gray-500">
                        Early-warning sources that often publish before NVD / cvelistV5.
                        {fetchedAt && <span className="ml-2 font-mono text-xs text-gray-400">Last fetch: {new Date(fetchedAt).toLocaleString()}</span>}
                    </p>
                </div>
                <div className="flex gap-2">
                    {userRole === 'admin' && (
                        <button onClick={() => setShowCfg(!showCfg)} className="rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50">
                            ⚙️ Configure
                        </button>
                    )}
                    {canEdit && (
                        <button onClick={refresh} disabled={refreshing} className="rounded-md bg-truevuln-blue px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-600 disabled:opacity-50">
                            {refreshing ? 'Refreshing…' : 'Refresh now'}
                        </button>
                    )}
                </div>
            </div>

            {/* Admin: feed configuration */}
            {showCfg && userRole === 'admin' && (
                <div className="bg-white border border-gray-200 shadow-sm rounded-sm p-4 mb-6">
                    <h3 className="text-sm font-bold font-mono text-gray-900 mb-2">Feed configuration</h3>
                    <p className="text-xs text-gray-500 mb-3">Enable/disable sources or add a custom RSS/Atom URL. Feeds with DOCTYPE/ENTITY declarations are refused (XXE protection).</p>
                    <div className="space-y-2">
                        {cfg.map((f, i) => (
                            <div key={i} className="flex items-center gap-2">
                                <input type="checkbox" checked={f.enabled} onChange={(e) => { const n = [...cfg]; n[i] = { ...f, enabled: e.target.checked }; setCfg(n); }} className="h-4 w-4 rounded border-gray-300 text-truevuln-blue" />
                                <input type="text" value={f.name} onChange={(e) => { const n = [...cfg]; n[i] = { ...f, name: e.target.value }; setCfg(n); }} className="w-64 rounded-md border-gray-300 text-xs font-mono h-8 px-2" />
                                <input type="text" value={f.url} onChange={(e) => { const n = [...cfg]; n[i] = { ...f, url: e.target.value }; setCfg(n); }} className="flex-1 rounded-md border-gray-300 text-xs font-mono h-8 px-2" />
                                <button onClick={() => setCfg(cfg.filter((_, j) => j !== i))} className="text-red-600 text-xs px-2">✕</button>
                            </div>
                        ))}
                    </div>
                    <div className="flex items-center gap-2 mt-3">
                        <button onClick={() => setCfg([...cfg, { id: `custom-${Date.now()}`, name: 'Custom feed', url: '', enabled: true }])} className="text-xs font-mono px-3 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50">+ Add feed</button>
                        <button onClick={saveCfg} className="text-xs font-mono px-3 py-1.5 bg-truevuln-blue text-white rounded-md hover:bg-blue-600">Save</button>
                        {cfgMsg && <span className="text-xs font-mono text-gray-500">{cfgMsg}</span>}
                    </div>
                </div>
            )}

            {/* CISA KEV — actively exploited */}
            <div className="bg-white border border-gray-200 shadow-sm rounded-sm mb-6">
                <div className="px-4 py-3 border-b border-gray-100 bg-red-50">
                    <h3 className="text-sm font-bold font-mono text-red-800">CISA KEV — Actively Exploited (latest additions)</h3>
                </div>
                <ul className="divide-y divide-gray-100">
                    {kev.length === 0 && <li className="px-4 py-3 text-sm text-gray-400 font-mono">No KEV data yet — run Refresh Threat Intel.</li>}
                    {kev.map((k: any, i: number) => (
                        <li key={i} className="px-4 py-2 flex items-center justify-between gap-3 text-sm">
                            <div className="min-w-0">
                                <a href={`/vulnerabilities?cve_id=${k.cve_id}`} className="font-mono font-semibold text-truevuln-blue hover:underline">{k.cve_id}</a>
                                <span className="ml-2 text-gray-600">{k.vulnerability_name || k.short_description || ''}</span>
                            </div>
                            <div className="flex items-center gap-2 flex-none text-xs font-mono">
                                {k.in_inventory && <span className="rounded px-1.5 py-0.5 bg-red-100 text-red-700 font-bold">IN INVENTORY</span>}
                                <span className="text-gray-400">{k.date_added || ''}</span>
                            </div>
                        </li>
                    ))}
                </ul>
            </div>

            {/* RSS feeds */}
            {feeds.filter(f => f.enabled).map((f) => (
                <div key={f.id} className="bg-white border border-gray-200 shadow-sm rounded-sm mb-4">
                    <button onClick={() => setOpenFeed(openFeed === f.id ? null : f.id)} className="w-full px-4 py-3 border-b border-gray-100 bg-gray-50 flex items-center justify-between text-left">
                        <h3 className="text-sm font-bold font-mono text-gray-900">{f.name}
                            <span className="ml-2 text-xs font-normal text-gray-400">{f.items.length} items</span>
                            {f.error && <span className="ml-2 text-xs text-red-600">fetch failed: {f.error}</span>}
                        </h3>
                        <span className="text-gray-400 text-xs">{openFeed === f.id ? '▲' : '▼'}</span>
                    </button>
                    {(openFeed === f.id || feeds.filter(x => x.enabled).length <= 2) && (
                        <ul className="divide-y divide-gray-100">
                            {f.items.slice(0, 15).map((it, i) => (
                                <li key={i} className="px-4 py-2 text-sm">
                                    <a href={it.link} target="_blank" rel="noopener noreferrer" className="font-medium text-truevuln-blue hover:underline">{it.title}</a>
                                    <span className="ml-2 text-xs text-gray-400 font-mono">{it.date}</span>
                                    {it.summary && <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{it.summary}</p>}
                                </li>
                            ))}
                            {f.items.length === 0 && !f.error && <li className="px-4 py-3 text-sm text-gray-400 font-mono">No items.</li>}
                        </ul>
                    )}
                </div>
            ))}
        </div>
    );
}
