import { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from '../../../bootstrap';
import { pathFromTab, PANEL_ROUTES } from '../../../navigation/panelRoutes';
import { timeAgo, timeUntil } from '../../../utils/timeAgo';
import { useTimeTicker } from '../../../utils/useTimeTicker';
import {
    commandLabel,
    commandStatusClass,
    commandStatusLabel,
    formatDuration,
    formatTimestamp,
    healthDotClass,
    healthStatusClass,
    healthStatusLabel,
    infraDotClass,
    infraStatusClass,
    infraStatusLabel,
    type InfrastructureMonitor,
    type WebsiteHealthStatus,
} from '../../../utils/dashboard';
import { CollapsibleSection } from '../../../components/CollapsibleSection';
import { ListPagination } from '../../../components/ListPagination';
import { EventDetailsDrawer } from '../../monitoring/components/EventDetailsDrawer';
import { ActiveIncidentsPanel } from './ActiveIncidentsPanel';
import type { ActiveIncident } from '../types/activeIncident';
import {
    Activity, AlertTriangle, CheckCircle, Clock,
    Database, Eye, Globe, HardDrive, Key, Radio, Send, Server,
    Shield, ShieldAlert, Terminal, WifiOff, Code,
} from 'lucide-react';

interface WebsiteRow {
    id: string;
    site_name: string;
    domain: string;
    health_status: WebsiteHealthStatus;
    health_status_label?: string;
    health_factors: string[];
    last_heartbeat_at: string | null;
    next_expected_heartbeat_at: string | null;
    heartbeat_interval_seconds: number;
    heartbeat_interval_label?: string;
    missed_heartbeats: number;
    security_score: number;
}

interface PendingCommandRow {
    id: number;
    command: string;
    status: string;
    created_at: string;
    started_at: string | null;
    completed_at: string | null;
    duration_seconds: number | null;
    agent?: { id: string; site_name: string; domain: string } | null;
}

interface DashboardSummary {
    websites: number;
    healthy: number;
    warning: number;
    offline: number;
    critical: number;
    pending_actions: number;
    alerts: number;
    open_incidents?: number;
}

interface AuditLog {
    id: number;
    agent_id: string;
    severity: string;
    event: string;
    message: string;
    logged_at: string;
    incident_status?: string | null;
    agent?: { site_name: string; domain: string };
}

interface DashboardViewProps {}

const POLL_INTERVAL_MS = 15000;
const INFRA_POLL_INTERVAL_MS = 30000;
const INFRA_PAGE_SIZE = 4;
const SECURITY_EVENTS_PAGE_SIZE = 5;

const iconMap: Record<string, React.ElementType> = {
    database: Database,
    redis: Server,
    queue: Radio,
    storage: Server,
    telegram: Send,
    scheduler: Clock,
    disk_usage: HardDrive,
    php_version: Code,
};

function SeverityBadge({ severity }: { severity: string }) {
    const styles: Record<string, string> = {
        critical: 'bg-rose-500/15 text-rose-400 border-rose-500/25',
        warning: 'bg-orange-500/10 text-orange-400 border-orange-500/20',
        success: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20',
        info: 'bg-blue-500/10 text-blue-400 border-blue-500/20',
    };

    return (
        <span className={`inline-flex rounded-md border px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wide ${styles[severity] || styles.info}`}>
            {severity}
        </span>
    );
}

function PanelTitle({ icon: Icon, title, meta }: { icon: React.ElementType; title: string; meta?: React.ReactNode }) {
    return (
        <div className="flex min-h-11 items-center justify-between gap-3 border-b border-slate-800/60 px-4 py-2.5">
            <div className="flex items-center gap-2">
                <Icon className="h-4 w-4 text-slate-500" />
                <h2 className="text-sm font-bold text-white">{title}</h2>
            </div>
            {meta}
        </div>
    );
}

export function DashboardView(_props: DashboardViewProps = {}) {
    const navigate = useNavigate();
    const nowTick = useTimeTicker(POLL_INTERVAL_MS);
    const [summary, setSummary] = useState<DashboardSummary | null>(null);
    const [websites, setWebsites] = useState<WebsiteRow[]>([]);
    const [pendingCommands, setPendingCommands] = useState<PendingCommandRow[]>([]);
    const [infraHealth, setInfraHealth] = useState<InfrastructureMonitor[]>([]);
    const [infraLastUpdated, setInfraLastUpdated] = useState<Date | null>(null);
    const [activeIncidents, setActiveIncidents] = useState<ActiveIncident[]>([]);
    const [selectedIncidentLog, setSelectedIncidentLog] = useState<any | null>(null);
    const [relatedIncidentEvents, setRelatedIncidentEvents] = useState<any[]>([]);
    const [logs, setLogs] = useState<AuditLog[]>([]);
    const [incidentActionId, setIncidentActionId] = useState<number | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
    const [infraPage, setInfraPage] = useState(1);
    const [securityEventsPage, setSecurityEventsPage] = useState(1);

    const refreshInfrastructure = useCallback(async () => {
        try {
            const response = await axios.get('/health-status');
            setInfraHealth(response.data.infrastructure ?? []);
            setInfraLastUpdated(new Date(response.data.refreshed_at ?? Date.now()));
        } catch (error) {
            console.error('Infrastructure health fetch error', error);
        }
    }, []);

    const applyRefreshPayload = useCallback((data: any) => {
        setSummary(data.summary ?? null);
        setWebsites(data.websites ?? []);
        setPendingCommands(data.pending_commands ?? []);
        if (Array.isArray(data.infrastructure) && data.infrastructure.length > 0) {
            setInfraHealth(data.infrastructure);
            setInfraLastUpdated(new Date(data.refreshed_at ?? Date.now()));
        }
        setActiveIncidents(data.active_incidents ?? []);
        setLastUpdated(new Date(data.refreshed_at ?? Date.now()));
    }, []);

    const refreshLiveData = useCallback(async (silent = false) => {
        silent ? setIsRefreshing(true) : setIsLoading(true);

        try {
            const response = await axios.get('/dashboard/refresh');
            applyRefreshPayload(response.data);
        } catch (error) {
            console.error('Dashboard refresh error', error);
        } finally {
            setIsLoading(false);
            setIsRefreshing(false);
        }
    }, [applyRefreshPayload]);

    const loadSecurityEvents = useCallback(async () => {
        try {
            const response = await axios.get('/audit-logs');
            setLogs(response.data.logs || []);
        } catch (error) {
            console.error('Audit log fetch error', error);
        }
    }, []);

    useEffect(() => {
        refreshLiveData(false);
        refreshInfrastructure();
        loadSecurityEvents();
    }, [refreshLiveData, refreshInfrastructure, loadSecurityEvents]);

    useEffect(() => {
        const timer = window.setInterval(() => refreshLiveData(true), POLL_INTERVAL_MS);
        return () => window.clearInterval(timer);
    }, [refreshLiveData]);

    useEffect(() => {
        const timer = window.setInterval(() => refreshInfrastructure(), INFRA_POLL_INTERVAL_MS);
        return () => window.clearInterval(timer);
    }, [refreshInfrastructure]);

    const handleIncidentAction = useCallback(async (
        incidentId: number,
        action: 'acknowledge' | 'resolve' | 'archive',
    ) => {
        setIncidentActionId(incidentId);
        try {
            await axios.post(`/incidents/${incidentId}/${action}`);
            await refreshLiveData(true);
        } catch (error) {
            console.error(`Incident ${action} error`, error);
        } finally {
            setIncidentActionId(null);
        }
    }, [refreshLiveData]);

    const handleBulkIncidentAction = useCallback(async (
        incidentIds: number[],
        action: 'acknowledge' | 'resolve',
    ) => {
        if (incidentIds.length === 0) {
            return;
        }

        setIncidentActionId(incidentIds[0]);
        try {
            for (const incidentId of incidentIds) {
                await axios.post(`/incidents/${incidentId}/${action}`);
            }
            await refreshLiveData(true);
        } catch (error) {
            console.error(`Bulk incident ${action} error`, error);
        } finally {
            setIncidentActionId(null);
        }
    }, [refreshLiveData]);

    const openIncident = (incident: ActiveIncident) => {
        if (incident.agent?.id) {
            navigate(`${PANEL_ROUTES.website(incident.agent.id)}?incident=${incident.id}`);
            return;
        }

        navigate(PANEL_ROUTES.logs);
    };

    const openIncidentDrawer = async (incident: ActiveIncident) => {
        try {
            const response = await axios.get(`/audit-logs/${incident.id}`);
            setSelectedIncidentLog(response.data.log);
            setRelatedIncidentEvents(response.data.related_events || []);
        } catch (error) {
            console.error('Error loading incident details', error);
            setSelectedIncidentLog({
                ...incident,
                attack_description: {
                    description: incident.description,
                    attack_type_label: incident.attack_type_label,
                    severity_label: incident.severity_label,
                },
            });
            setRelatedIncidentEvents([]);
        }
    };

    const latestWebsites = useMemo(
        () => [...websites]
            .sort((a, b) => {
                const aTime = a.last_heartbeat_at ? new Date(a.last_heartbeat_at).getTime() : 0;
                const bTime = b.last_heartbeat_at ? new Date(b.last_heartbeat_at).getTime() : 0;
                return bTime - aTime;
            })
            .slice(0, 6),
        [websites],
    );

    const infraTotalPages = Math.max(1, Math.ceil(infraHealth.length / INFRA_PAGE_SIZE));
    const paginatedInfra = useMemo(() => {
        const start = (infraPage - 1) * INFRA_PAGE_SIZE;
        return infraHealth.slice(start, start + INFRA_PAGE_SIZE);
    }, [infraHealth, infraPage]);

    const securityEventsTotalPages = Math.max(1, Math.ceil(logs.length / SECURITY_EVENTS_PAGE_SIZE));
    const paginatedSecurityEvents = useMemo(() => {
        const start = (securityEventsPage - 1) * SECURITY_EVENTS_PAGE_SIZE;
        return logs.slice(start, start + SECURITY_EVENTS_PAGE_SIZE);
    }, [logs, securityEventsPage]);

    useEffect(() => {
        if (infraPage > infraTotalPages) {
            setInfraPage(infraTotalPages);
        }
    }, [infraPage, infraTotalPages]);

    useEffect(() => {
        if (securityEventsPage > securityEventsTotalPages) {
            setSecurityEventsPage(securityEventsTotalPages);
        }
    }, [securityEventsPage, securityEventsTotalPages]);

    if (isLoading && !summary) {
        return (
            <div className="flex items-center justify-center py-24">
                <div className="h-7 w-7 animate-spin rounded-full border-2 border-rose-500/20 border-t-rose-500" />
            </div>
        );
    }

    const overview = [
        { label: 'Websites', value: summary?.websites ?? 0, detail: 'Monitored estate', icon: Globe, color: 'text-slate-200' },
        { label: 'Healthy', value: summary?.healthy ?? 0, detail: 'Reporting normally', icon: CheckCircle, color: 'text-emerald-400' },
        { label: 'Warning', value: summary?.warning ?? 0, detail: 'Needs attention', icon: AlertTriangle, color: (summary?.warning ?? 0) ? 'text-amber-400' : 'text-slate-400' },
        { label: 'Offline', value: summary?.offline ?? 0, detail: 'Missed heartbeats', icon: WifiOff, color: (summary?.offline ?? 0) ? 'text-slate-300' : 'text-slate-400' },
        { label: 'Critical', value: summary?.critical ?? 0, detail: 'Immediate review', icon: ShieldAlert, color: (summary?.critical ?? 0) ? 'text-rose-400' : 'text-slate-400' },
    ];

    const openAgent = (agentId: string) => {
        navigate(PANEL_ROUTES.website(agentId));
    };

    return (
        <div className="mx-auto max-w-[1600px] space-y-4 animate-fade-in">
            <ActiveIncidentsPanel
                incidents={activeIncidents}
                lastUpdated={lastUpdated}
                isRefreshing={isRefreshing}
                incidentActionId={incidentActionId}
                nowTick={nowTick}
                onRefresh={() => refreshLiveData(true)}
                onOpenQueue={() => navigate(PANEL_ROUTES.logs)}
                onInvestigate={openIncident}
                onAcknowledge={(incidentId) => handleIncidentAction(incidentId, 'acknowledge')}
                onResolve={(incidentId) => handleIncidentAction(incidentId, 'resolve')}
                onBulkAcknowledge={(incidentIds) => handleBulkIncidentAction(incidentIds, 'acknowledge')}
                onBulkResolve={(incidentIds) => handleBulkIncidentAction(incidentIds, 'resolve')}
                onOpenDrawer={openIncidentDrawer}
            />

            <section aria-labelledby="system-overview-heading">
                <div className="mb-2 flex items-center justify-between">
                    <h2 id="system-overview-heading" className="text-[10px] font-bold uppercase tracking-[0.18em] text-slate-500">System Overview</h2>
                    <span className="text-[10px] text-slate-600">{summary?.pending_actions ?? 0} pending actions</span>
                </div>
                <div className="grid grid-cols-2 gap-2.5 sm:grid-cols-3 xl:grid-cols-5">
                    {overview.map(({ label, value, detail, icon: Icon, color }) => (
                        <div key={label} className="rounded-xl border border-slate-800/80 bg-slate-900/50 px-3.5 py-3">
                            <div className="flex items-center justify-between gap-2">
                                <p className="truncate text-[10px] font-semibold uppercase tracking-wider text-slate-500">{label}</p>
                                <Icon className={`h-3.5 w-3.5 shrink-0 ${color}`} />
                            </div>
                            <p className={`mt-1.5 text-2xl font-black leading-none ${color}`}>{value}</p>
                            <p className="mt-1.5 text-[9px] text-slate-600">{detail}</p>
                        </div>
                    ))}
                </div>
            </section>

            <CollapsibleSection
                id="infrastructure-heading"
                title="Infrastructure Health"
                icon={Activity}
                defaultOpen={false}
                badge={
                    infraHealth.length > 0 ? (
                        <span className="rounded-full border border-slate-700/80 bg-slate-800/80 px-2 py-0.5 text-[9px] font-semibold text-slate-400">
                            {infraHealth.length} monitors
                        </span>
                    ) : null
                }
                subtitle={
                    <>
                        Refreshes every 30s
                        {infraLastUpdated ? ` · Last checked ${timeAgo(infraLastUpdated.toISOString(), nowTick)}` : ''}
                    </>
                }
            >
                {infraHealth.length === 0 ? (
                    <div className="px-4 py-8 text-center text-xs text-slate-600">No infrastructure monitors available.</div>
                ) : (
                    <>
                        <div className="grid grid-cols-1 gap-2 p-4 sm:grid-cols-2 xl:grid-cols-4">
                            {paginatedInfra.map((monitor) => {
                                const Icon = iconMap[monitor.key] || Server;
                                return (
                                    <div key={monitor.key} className="rounded-xl border border-slate-800 bg-slate-950/35 px-3 py-2.5">
                                        <div className="flex items-start justify-between gap-2">
                                            <div className="flex min-w-0 items-center gap-2">
                                                <span className={`mt-1 h-1.5 w-1.5 shrink-0 rounded-full ${infraDotClass(monitor.status)}`} />
                                                <Icon className="h-3.5 w-3.5 shrink-0 text-slate-500" />
                                                <p className="truncate text-[10px] font-semibold text-slate-300">{monitor.label}</p>
                                            </div>
                                            <span className={`inline-flex shrink-0 rounded-md border px-1.5 py-0.5 text-[8px] font-bold uppercase ${infraStatusClass(monitor.status)}`}>
                                                {infraStatusLabel(monitor.status)}
                                            </span>
                                        </div>
                                        <p className="mt-2 text-[10px] leading-relaxed text-slate-400">{monitor.summary}</p>
                                        <p className="mt-1.5 text-[9px] text-slate-600">
                                            Last checked {timeAgo(monitor.last_checked_at, nowTick)}
                                        </p>
                                    </div>
                                );
                            })}
                        </div>
                        <ListPagination
                            page={infraPage}
                            totalPages={infraTotalPages}
                            totalItems={infraHealth.length}
                            pageSize={INFRA_PAGE_SIZE}
                            onPageChange={setInfraPage}
                        />
                    </>
                )}
            </CollapsibleSection>

            <div className="grid grid-cols-1 gap-4 xl:grid-cols-5">
                <section className="overflow-hidden rounded-2xl border border-slate-800/80 bg-slate-900/40 xl:col-span-3">
                    <PanelTitle icon={Radio} title="Latest Check-ins" meta={<button onClick={() => navigate(PANEL_ROUTES.websites)} className="text-[10px] font-semibold text-slate-500 transition hover:text-slate-200">View all websites</button>} />
                    {latestWebsites.length === 0 ? (
                        <div className="py-10 text-center text-xs text-slate-600">No websites registered yet.</div>
                    ) : (
                        <div className="divide-y divide-slate-800/50">
                            {latestWebsites.map((website) => (
                                <button key={website.id} onClick={() => openAgent(website.id)} className="flex w-full items-center gap-3 px-4 py-2.5 text-left transition hover:bg-slate-800/20">
                                    <span className={`h-2 w-2 shrink-0 rounded-full ${healthDotClass(website.health_status)}`} />
                                    <span className="min-w-0 flex-1">
                                        <span className="block truncate text-xs font-semibold text-white">{website.site_name}</span>
                                        <span className="block truncate font-mono text-[10px] text-slate-500">{website.domain}</span>
                                    </span>
                                    <span className="text-right">
                                        <span className={`inline-flex rounded-md border px-1.5 py-0.5 text-[9px] font-bold uppercase ${healthStatusClass(website.health_status)}`}>
                                            {website.health_status_label || healthStatusLabel(website.health_status, website.missed_heartbeats)}
                                        </span>
                                        <span className="mt-1 block text-[9px] text-slate-600">
                                            Last {timeAgo(website.last_heartbeat_at, nowTick)}
                                        </span>
                                        <span className="block text-[9px] text-slate-600">
                                            {website.heartbeat_interval_label || `Every ${Math.round((website.heartbeat_interval_seconds || 300) / 60)} minutes`}
                                        </span>
                                        <span className="block text-[9px] text-slate-700">
                                            Missed {website.missed_heartbeats ?? 0}
                                            {' · '}
                                            Expected {timeUntil(website.next_expected_heartbeat_at, nowTick)}
                                        </span>
                                    </span>
                                </button>
                            ))}
                        </div>
                    )}
                </section>

                <section className="overflow-hidden rounded-2xl border border-slate-800/80 bg-slate-900/40 xl:col-span-2">
                    <PanelTitle
                        icon={Terminal}
                        title="Pending Actions"
                        meta={<span className={`rounded-full px-2 py-0.5 text-[9px] font-bold ${pendingCommands.length ? 'border border-amber-500/20 bg-amber-500/10 text-amber-400' : 'bg-slate-800 text-slate-500'}`}>{pendingCommands.length} active</span>}
                    />
                    {pendingCommands.length === 0 ? (
                        <div className="flex flex-col items-center justify-center gap-2 py-10">
                            <CheckCircle className="h-6 w-6 text-emerald-500/30" />
                            <p className="text-xs text-slate-600">Action queue is clear</p>
                        </div>
                    ) : (
                        <div className="overflow-x-auto">
                            <table className="min-w-full text-left text-[10px]">
                                <thead className="border-b border-slate-800/60 text-slate-500 uppercase tracking-wider">
                                    <tr>
                                        <th className="px-3 py-2 font-semibold">Website</th>
                                        <th className="px-3 py-2 font-semibold">Command</th>
                                        <th className="px-3 py-2 font-semibold">Status</th>
                                        <th className="px-3 py-2 font-semibold hidden lg:table-cell">Created</th>
                                        <th className="px-3 py-2 font-semibold hidden xl:table-cell">Started</th>
                                        <th className="px-3 py-2 font-semibold hidden xl:table-cell">Completed</th>
                                        <th className="px-3 py-2 font-semibold">Duration</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-slate-800/40">
                                    {pendingCommands.slice(0, 8).map((command) => (
                                        <tr
                                            key={command.id}
                                            onClick={() => command.agent?.id && openAgent(command.agent.id)}
                                            className={`transition ${command.agent?.id ? 'cursor-pointer hover:bg-slate-800/20' : ''}`}
                                        >
                                            <td className="px-3 py-2 text-slate-300">{command.agent?.site_name || 'Unknown'}</td>
                                            <td className="px-3 py-2 font-semibold text-white">{commandLabel(command.command)}</td>
                                            <td className="px-3 py-2">
                                                <span className={`inline-flex rounded-md border px-1.5 py-0.5 text-[9px] font-bold uppercase ${commandStatusClass(command.status)}`}>
                                                    {commandStatusLabel(command.status)}
                                                </span>
                                            </td>
                                            <td className="px-3 py-2 text-slate-500 hidden lg:table-cell">{timeAgo(command.created_at, nowTick)}</td>
                                            <td className="px-3 py-2 text-slate-500 hidden xl:table-cell">{formatTimestamp(command.started_at)}</td>
                                            <td className="px-3 py-2 text-slate-500 hidden xl:table-cell">{formatTimestamp(command.completed_at)}</td>
                                            <td className="px-3 py-2 text-slate-400">{formatDuration(command.duration_seconds)}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    )}
                </section>
            </div>

            <CollapsibleSection
                id="security-events-heading"
                title="Recent Security Events"
                icon={ShieldAlert}
                defaultOpen={false}
                badge={
                    logs.length > 0 ? (
                        <span className="rounded-full border border-slate-700/80 bg-slate-800/80 px-2 py-0.5 text-[9px] font-semibold text-slate-400">
                            {logs.length} events
                        </span>
                    ) : null
                }
                meta={
                    <button
                        type="button"
                        onClick={(event) => {
                            event.stopPropagation();
                            navigate(PANEL_ROUTES.logs);
                        }}
                        className="text-[10px] font-semibold text-slate-500 transition hover:text-slate-200"
                    >
                        Open event log
                    </button>
                }
            >
                {logs.length === 0 ? (
                    <div className="flex flex-col items-center justify-center gap-2 py-10">
                        <Shield className="h-6 w-6 text-emerald-500/30" />
                        <p className="text-xs text-slate-600">No security events detected</p>
                    </div>
                ) : (
                    <>
                        <div className="divide-y divide-slate-800/50">
                            {paginatedSecurityEvents.map((log) => (
                                <button
                                    key={log.id}
                                    onClick={() => navigate(PANEL_ROUTES.logs)}
                                    className="flex w-full items-start gap-3 px-4 py-2.5 text-left transition hover:bg-slate-800/20"
                                >
                                    <div className="w-14 shrink-0 pt-0.5"><SeverityBadge severity={log.severity} /></div>
                                    <div className="min-w-0 flex-1">
                                        <p className="truncate text-xs font-semibold text-slate-200">{log.message}</p>
                                        <p className="mt-0.5 truncate text-[10px] text-slate-500">
                                            <span className="font-mono">{log.event}</span>
                                            {log.agent && ` · ${log.agent.site_name}`}
                                        </p>
                                    </div>
                                    <span className="shrink-0 text-[10px] text-slate-600">{timeAgo(log.logged_at, nowTick)}</span>
                                </button>
                            ))}
                        </div>
                        <ListPagination
                            page={securityEventsPage}
                            totalPages={securityEventsTotalPages}
                            totalItems={logs.length}
                            pageSize={SECURITY_EVENTS_PAGE_SIZE}
                            onPageChange={setSecurityEventsPage}
                        />
                    </>
                )}
            </CollapsibleSection>

            <section className="rounded-2xl border border-slate-800/80 bg-slate-900/40 p-4" aria-labelledby="quick-actions-heading">
                <div className="flex flex-col gap-3 lg:flex-row lg:items-center">
                    <div className="lg:w-36 lg:shrink-0">
                        <h2 id="quick-actions-heading" className="text-[10px] font-bold uppercase tracking-[0.18em] text-slate-500">Quick Actions</h2>
                        <p className="mt-1 text-[9px] text-slate-600">Common operator tasks</p>
                    </div>
                    <div className="flex flex-wrap gap-2">
                        {[
                            { label: 'Add activation key', icon: Key, tab: 'keys', style: 'border-indigo-500/20 text-indigo-400 hover:bg-indigo-500/10' },
                            { label: 'Edit security policy', icon: Shield, tab: 'policies', style: 'border-rose-500/20 text-rose-400 hover:bg-rose-500/10' },
                            { label: 'Review audit log', icon: Eye, tab: 'logs', style: 'border-slate-700 text-slate-400 hover:bg-slate-800/50' },
                            { label: 'Review malware reports', icon: AlertTriangle, tab: 'logs', style: 'border-amber-500/20 text-amber-400 hover:bg-amber-500/10' },
                        ].map(({ label, icon: Icon, tab, style }) => (
                            <button key={label} onClick={() => navigate(pathFromTab(tab))} className={`flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold transition ${style}`}>
                                <Icon className="h-3.5 w-3.5" />
                                {label}
                            </button>
                        ))}
                    </div>
                </div>
            </section>

            <EventDetailsDrawer
                log={selectedIncidentLog}
                relatedEvents={relatedIncidentEvents}
                onClose={() => {
                    setSelectedIncidentLog(null);
                    setRelatedIncidentEvents([]);
                }}
            />
        </div>
    );
}
