'use client';

/**
 * Incidents — Incident analytics. State-driven banner (active vs all-clear) →
 * KPI row → bar chart (left) + leaderboard & alert timeline (right). The banner
 * and timeline empty-states are driven by data.overview.activeIncidents.
 */
import { AlertTriangle, CheckCircle2, ArrowUpRight } from 'lucide-react';
import { useSentinelContext } from '../../_components/SentinelDataContext';
import { BarChart, CountUp, Delta, FadeUp, Sparkline, StatusDot } from '../../_components/primitives';
import { relTime } from '@/lib/executive/status';

const MEDAL = ['#f4d23c', '#c9ccd6', '#e0a06b'];

function barColor(n: number): string {
    return n >= 5 ? 'var(--crit)' : n >= 3 ? 'var(--warn)' : 'var(--ok)';
}

const Eyebrow = ({ children }: { children: React.ReactNode }) => <div className="eyebrow" style={{ marginBottom: 8 }}>{children}</div>;

export default function IncidentsPage() {
    const { data, cycle } = useSentinelContext();
    if (!data) return null;
    const active = data.overview.activeIncidents;
    const total30d = data.topIssues.reduce((s, t) => s + t.incidents, 0);
    const downtime30d = data.topIssues.reduce((s, t) => s + t.downtime, 0);
    const mttr = total30d > 0 ? (downtime30d / total30d).toFixed(1) : '0';
    const downNow = data.recentAlerts.filter((a) => a.status === 'down').length;
    const incidentSeries = data.monthlyTrends.map((m) => m.incidents);
    const leaderboard = [...data.topIssues].sort((a, b) => b.incidents - a.incidents);
    const maxIncidents = Math.max(...leaderboard.map((t) => t.incidents), 1);
    // Wallboard view never scrolls — cap the timeline to what fits the panel.
    const timeline = data.recentAlerts.slice(0, 7);

    return (
        <div key={cycle} style={{ display: 'grid', gridTemplateRows: 'auto auto 1fr', gap: 12, height: '100%', minHeight: 0 }}>
            {/* state-driven banner */}
            {active > 0 ? (
                <FadeUp style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '16px 20px', background: 'color-mix(in srgb, var(--crit) 13%, transparent)', border: '1px solid color-mix(in srgb, var(--crit) 45%, transparent)', position: 'relative', overflow: 'hidden' }}>
                    <span style={{ width: 44, height: 44, flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'color-mix(in srgb, var(--crit) 20%, transparent)', color: 'var(--crit-fg)', position: 'relative' }}>
                        <AlertTriangle size={22} strokeWidth={2} />
                        <span style={{ position: 'absolute', top: 6, right: 6, width: 7, height: 7, borderRadius: '50%', background: 'var(--crit)', animation: 'nocPulse 1.6s ease-in-out infinite' }} />
                    </span>
                    <div style={{ flex: 1 }}>
                        <div style={{ fontFamily: 'var(--font-heading)', fontSize: 17, fontWeight: 700, color: 'var(--fg)' }}>
                            <span style={{ color: 'var(--crit-fg)' }}>{active}</span> active incident{active > 1 ? 's' : ''} — immediate attention required
                        </div>
                        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-2)', marginTop: 2 }}>{downNow} monitor{downNow !== 1 ? 's' : ''} currently down · on-call paged</div>
                    </div>
                    <button type="button" className="pill" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '10px 18px', border: 'none', cursor: 'pointer', background: 'linear-gradient(135deg, var(--crit), var(--magenta))', color: '#fff', fontFamily: 'var(--font-heading)', fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                        Open incident room <ArrowUpRight size={15} />
                    </button>
                </FadeUp>
            ) : (
                <FadeUp style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '16px 20px', background: 'color-mix(in srgb, var(--ok) 12%, transparent)', border: '1px solid color-mix(in srgb, var(--ok) 40%, transparent)' }}>
                    <span style={{ width: 44, height: 44, flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'color-mix(in srgb, var(--ok) 18%, transparent)', color: 'var(--ok-fg)' }}>
                        <CheckCircle2 size={22} strokeWidth={2} />
                    </span>
                    <div style={{ flex: 1 }}>
                        <div style={{ fontFamily: 'var(--font-heading)', fontSize: 17, fontWeight: 700, color: 'var(--fg)' }}>All clear — 0 active incidents</div>
                        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-2)', marginTop: 2 }}>All monitored services are responding normally.</div>
                    </div>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ok-fg)' }}><StatusDot status="healthy" size={7} /> stable</span>
                </FadeUp>
            )}

            {/* KPI row */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
                <Kpi index={0} label="Active incidents">
                    <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 600, color: active > 0 ? 'var(--crit-fg)' : 'var(--ok-fg)' }}><CountUp value={active} /></span>
                </Kpi>
                <Kpi index={1} label="Avg time to resolve">
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                        <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 600, color: 'var(--fg)' }}>{mttr}</span>
                        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)' }}>min · MTTR</span>
                    </div>
                </Kpi>
                <Kpi index={2} label="Incidents · 30d">
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                        <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 600, color: 'var(--fg)' }}><CountUp value={total30d} /></span>
                        <Delta value={data.overview.incidentsTrend} goodWhenUp={false} />
                    </div>
                    <div style={{ marginTop: 6 }}><Sparkline data={incidentSeries} w={150} h={28} color="var(--crit)" /></div>
                </Kpi>
                <Kpi index={3} label="Downtime · 30d">
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                        <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 600, color: 'var(--warn-fg)' }}><CountUp value={downtime30d} /></span>
                        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)' }}>min</span>
                    </div>
                </Kpi>
            </div>

            {/* body grid */}
            <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 12, minHeight: 0 }}>
                <FadeUp index={4} className="glass-card" style={{ padding: 20, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
                    <Eyebrow>Incident trend · 12 months</Eyebrow>
                    <div style={{ flex: 1, minHeight: 0, display: 'flex', alignItems: 'flex-end' }}>
                        <BarChart values={incidentSeries} labels={data.monthlyTrends.map((m) => m.month)} colors={incidentSeries.map(barColor)} h="100%" />
                    </div>
                </FadeUp>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 12, minHeight: 0 }}>
                    <FadeUp index={5} className="glass-card" style={{ padding: 18 }}>
                        <Eyebrow>Most affected monitors · 30d</Eyebrow>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                            {leaderboard.slice(0, 5).map((t, i) => (
                                <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                                    <span className="tnum" style={{ width: 22, height: 22, flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-mono)', color: i < 3 ? '#1a1f2e' : 'var(--fg-3)', background: i < 3 ? MEDAL[i] : 'var(--card-bg-2)', borderRadius: '50%' }}>{i + 1}</span>
                                    <div style={{ flex: 1, minWidth: 0 }}>
                                        <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name}</div>
                                        <div style={{ height: 4, marginTop: 4, background: 'var(--hair)', borderRadius: 0 }}><div style={{ width: `${(t.incidents / maxIncidents) * 100}%`, height: '100%', background: barColor(t.incidents) }} /></div>
                                    </div>
                                    <span className="tnum" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--crit-fg)', flex: 'none' }}>{t.incidents}× · {t.downtime}m</span>
                                </div>
                            ))}
                        </div>
                    </FadeUp>

                    <FadeUp index={6} className="glass-card" style={{ padding: 18, flex: 1, minHeight: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
                        <Eyebrow>Alert timeline</Eyebrow>
                        {data.recentAlerts.length === 0 ? (
                            <div style={{ textAlign: 'center', padding: '24px 0', color: 'var(--fg-3)' }}>
                                <CheckCircle2 size={28} style={{ color: 'var(--ok-fg)', margin: '0 auto 8px' }} />
                                <div style={{ fontSize: 13 }}>No active alerts</div>
                                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>All monitors are responding…</div>
                            </div>
                        ) : (
                            <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, overflow: 'hidden' }}>
                                {timeline.map((a, i) => {
                                    const down = a.status === 'down';
                                    return (
                                        <div key={i} style={{ display: 'flex', gap: 12, paddingBottom: 12, position: 'relative' }}>
                                            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 'none' }}>
                                                <span style={{ width: 10, height: 10, borderRadius: '50%', background: down ? 'var(--crit)' : 'var(--ok)', boxShadow: down ? '0 0 8px var(--crit)' : 'none', marginTop: 3 }} />
                                                {i < timeline.length - 1 && <span style={{ width: 1, flex: 1, background: 'var(--hair)', marginTop: 3 }} />}
                                            </div>
                                            <div style={{ flex: 1, minWidth: 0 }}>
                                                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                                                    <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.monitorName}</span>
                                                    <span className="tnum" style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--fg-3)', flex: 'none' }}>{relTime(a.timestamp)}</span>
                                                </div>
                                                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: down ? 'var(--crit-fg)' : 'var(--ok-fg)' }}>{down ? 'Went down — no response' : `Recovered · ${a.responseTime}ms`}</div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </FadeUp>
                </div>
            </div>
        </div>
    );
}

function Kpi({ label, children, index }: { label: string; children: React.ReactNode; index: number }) {
    return (
        <FadeUp index={index} className="card" style={{ padding: 16 }}>
            <Eyebrow>{label}</Eyebrow>
            {children}
        </FadeUp>
    );
}
