"use client";

import { useState, useEffect, useCallback } from "react";
import {
  AlertTriangle, Link2, ArrowRight, Image, Loader2,
  AlertCircle, FileX,
} from "lucide-react";

interface HttpErrorRow { pageUrl: string; statusCode: number; occurrences: number; firstSeen: string; lastSeen: string; referrer: string | null }
interface BrokenLinkRow { sourceUrl: string; targetUrl: string; statusCode: number; linkText: string | null; occurrences: number }
interface RedirectRow { originalUrl: string; finalUrl: string; redirectCount: number; avgRedirectTimeMs: number; occurrences: number; isChain: boolean }
interface ResourceErrorRow { pageUrl: string; resourceUrl: string; resourceType: string; occurrences: number }

// ── Runtime (client-emitted) error rows — come from the new
// js_error / resource_error / page_not_found event streams t.js
// added in the CWV + a11y modules. Distinct from the heuristic-
// based legacy rows above so both surfaces render side by side.
interface JsErrorGroup {
  message: string;
  filename: string | null;
  lineNumber: number | null;
  pageUrl: string;
  count: number;
  firstSeen: string;
  lastSeen: string;
}
interface RuntimeResourceErrorRow {
  resourceUrl: string;
  resourceType: string | null;
  pageUrl: string;
  count: number;
  lastSeen: string;
}
interface NotFoundGroup {
  requestedUrl: string;
  referrer: string | null;
  pageUrl: string;
  count: number;
  lastSeen: string;
}
interface RuntimeBlock {
  jsErrors: JsErrorGroup[];
  resourceErrors: RuntimeResourceErrorRow[];
  notFounds: NotFoundGroup[];
  totals: { jsErrors: number; resourceErrors: number; notFounds: number };
}

interface ErrorData {
  httpErrors: HttpErrorRow[];
  brokenLinks: BrokenLinkRow[];
  redirects: RedirectRow[];
  resourceErrors: ResourceErrorRow[];
  runtime?: RuntimeBlock;
}

export interface ErrorsTabProps { brandId: string; range: string }

type Section = "errors" | "broken" | "redirects" | "resources";

const SECTIONS: Array<{ key: Section; label: string; icon: typeof AlertTriangle }> = [
  { key: "errors",    label: "HTTP Errors",     icon: AlertTriangle },
  { key: "broken",    label: "Broken Links",    icon: Link2 },
  { key: "redirects", label: "Redirects",       icon: ArrowRight },
  { key: "resources", label: "Resource Errors",  icon: Image },
];

function statusBadge(code: number) {
  if (code >= 500) return "bg-red-50 text-red-700 border-red-200";
  if (code === 404) return "bg-amber-50 text-amber-700 border-amber-200";
  if (code === 200) return "bg-slate-50 text-slate-600 border-slate-200"; // soft 404
  return "bg-slate-50 text-slate-600 border-slate-200";
}

export function ErrorsTab({ brandId, range }: ErrorsTabProps) {
  const [data, setData] = useState<ErrorData | null>(null);
  const [loading, setLoading] = useState(true);
  const [section, setSection] = useState<Section>("errors");

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/site-tag/analytics/errors?brandId=${brandId}&range=${range}`);
      if (res.ok) setData(await res.json());
    } catch { /* swallow */ }
    setLoading(false);
  }, [brandId, range]);

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

  if (loading) return <div className="bg-white rounded-xl border border-slate-200 p-8 flex items-center justify-center"><Loader2 className="w-5 h-5 animate-spin text-slate-400" /></div>;

  const runtime = data?.runtime;
  const runtimeActive = !!runtime && (
    runtime.totals.jsErrors > 0 || runtime.totals.resourceErrors > 0 || runtime.totals.notFounds > 0
  );
  const empty = !data || (
    data.httpErrors.length === 0 &&
    data.brokenLinks.length === 0 &&
    data.redirects.length === 0 &&
    data.resourceErrors.length === 0 &&
    !runtimeActive
  );
  if (empty) {
    return (
      <div className="bg-white rounded-xl border border-dashed border-slate-200 p-12 text-center">
        <AlertTriangle className="w-10 h-10 text-slate-200 mx-auto mb-3" />
        <h2 className="text-lg font-bold text-slate-900 mb-1">No Errors Detected</h2>
        <p className="text-sm text-slate-500 max-w-sm mx-auto">
          The Site Tag monitors for JS exceptions, resource load failures, 404 pages, broken links, redirect chains, and missing resources in real time. No issues have been detected in this date range.
        </p>
      </div>
    );
  }

  const counts = {
    errors: data!.httpErrors.length,
    broken: data!.brokenLinks.length,
    redirects: data!.redirects.length,
    resources: data!.resourceErrors.length,
  };

  return (
    <div className="space-y-4">
      {/* ── Runtime errors (js_error / resource_error /
          page_not_found from t.js CWV + a11y modules) ───────
          Always rendered when the runtime block is present, even
          when all counts are zero — confirms the tracking is live
          rather than silently broken. */}
      {runtime && (
        <div className="space-y-3">
          <h2 className="text-base font-bold text-slate-900 flex items-center gap-2">
            <AlertCircle className="w-4 h-4 text-slate-500" />
            Runtime Errors
          </h2>
          <div className="grid grid-cols-3 gap-3">
            <RuntimeStat icon={AlertCircle}     label="JS Errors"         value={runtime.totals.jsErrors}       tone={runtime.totals.jsErrors > 0 ? "red" : "slate"} />
            <RuntimeStat icon={Image}           label="Resource Failures" value={runtime.totals.resourceErrors} tone={runtime.totals.resourceErrors > 0 ? "orange" : "slate"} />
            <RuntimeStat icon={FileX}           label="404 Pages"         value={runtime.totals.notFounds}      tone={runtime.totals.notFounds > 0 ? "red" : "slate"} />
          </div>

          {/* JS Errors — grouped by message */}
          {runtime.jsErrors.length > 0 && (
            <div className="bg-white rounded-xl border border-slate-200 overflow-hidden overflow-x-auto">
              <div className="px-5 py-3 border-b border-slate-100 flex items-center gap-2">
                <AlertCircle className="w-4 h-4 text-red-600" />
                <h3 className="font-bold text-slate-800 text-sm">JS Errors</h3>
                <span className="text-[10px] text-slate-400 ml-auto">grouped by message · top 50</span>
              </div>
              <table className="w-full text-sm">
                <thead>
                  <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50/40">
                    <th className="px-5 py-2.5">Message</th>
                    <th className="px-5 py-2.5">File</th>
                    <th className="px-5 py-2.5 text-right">Line</th>
                    <th className="px-5 py-2.5">Page</th>
                    <th className="px-5 py-2.5 text-right">Count</th>
                    <th className="px-5 py-2.5">Last Seen</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {runtime.jsErrors.map((e, i) => (
                    <tr key={`${e.message}::${i}`} className="hover:bg-slate-50 transition-colors">
                      <td className="px-5 py-2.5 text-xs text-red-700 truncate max-w-[360px]" title={e.message}>{e.message}</td>
                      <td className="px-5 py-2.5 font-mono text-[10px] text-slate-500 truncate max-w-[220px]" title={e.filename ?? ""}>{e.filename ?? "—"}</td>
                      <td className="px-5 py-2.5 text-right font-mono text-[10px] text-slate-500 tabular-nums">{e.lineNumber ?? "—"}</td>
                      <td className="px-5 py-2.5 font-mono text-[10px] text-brand-600 truncate max-w-[200px]" title={e.pageUrl}>{e.pageUrl}</td>
                      <td className="px-5 py-2.5 text-right font-bold text-slate-900 tabular-nums">{e.count}</td>
                      <td className="px-5 py-2.5 text-[11px] text-slate-500 tabular-nums">
                        {new Date(e.lastSeen).toLocaleDateString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* Resource Errors (new format) — grouped by URL */}
          {runtime.resourceErrors.length > 0 && (
            <div className="bg-white rounded-xl border border-slate-200 overflow-hidden overflow-x-auto">
              <div className="px-5 py-3 border-b border-slate-100 flex items-center gap-2">
                <Image className="w-4 h-4 text-orange-600" />
                <h3 className="font-bold text-slate-800 text-sm">Resource Errors</h3>
                <span className="text-[10px] text-slate-400 ml-auto">failed cross-origin fetches · top 50</span>
              </div>
              <table className="w-full text-sm">
                <thead>
                  <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50/40">
                    <th className="px-5 py-2.5">Resource URL</th>
                    <th className="px-5 py-2.5">Type</th>
                    <th className="px-5 py-2.5">Page</th>
                    <th className="px-5 py-2.5 text-right">Count</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {runtime.resourceErrors.map((r, i) => (
                    <tr key={`${r.resourceUrl}::${i}`} className="hover:bg-slate-50 transition-colors">
                      <td className="px-5 py-2.5 font-mono text-[11px] text-red-600 truncate max-w-[320px]" title={r.resourceUrl}>{r.resourceUrl}</td>
                      <td className="px-5 py-2.5 text-xs text-slate-600 capitalize">{r.resourceType ?? "—"}</td>
                      <td className="px-5 py-2.5 font-mono text-[10px] text-brand-600 truncate max-w-[200px]" title={r.pageUrl}>{r.pageUrl}</td>
                      <td className="px-5 py-2.5 text-right font-bold text-slate-900 tabular-nums">{r.count}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* 404 Pages — grouped by requested URL */}
          {runtime.notFounds.length > 0 && (
            <div className="bg-white rounded-xl border border-slate-200 overflow-hidden overflow-x-auto">
              <div className="px-5 py-3 border-b border-slate-100 flex items-center gap-2">
                <FileX className="w-4 h-4 text-red-600" />
                <h3 className="font-bold text-slate-800 text-sm">404 Pages</h3>
                <span className="text-[10px] text-slate-400 ml-auto">title + body heuristic · top 50</span>
              </div>
              <table className="w-full text-sm">
                <thead>
                  <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50/40">
                    <th className="px-5 py-2.5">Requested URL</th>
                    <th className="px-5 py-2.5">Referrer</th>
                    <th className="px-5 py-2.5 text-right">Count</th>
                    <th className="px-5 py-2.5">Last Seen</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {runtime.notFounds.map((n, i) => (
                    <tr key={`${n.requestedUrl}::${i}`} className="hover:bg-slate-50 transition-colors">
                      <td className="px-5 py-2.5 font-mono text-[11px] text-red-600 truncate max-w-[320px]" title={n.requestedUrl}>{n.requestedUrl}</td>
                      <td className="px-5 py-2.5 font-mono text-[10px] text-slate-500 truncate max-w-[220px]" title={n.referrer ?? ""}>{n.referrer ?? "—"}</td>
                      <td className="px-5 py-2.5 text-right font-bold text-slate-900 tabular-nums">{n.count}</td>
                      <td className="px-5 py-2.5 text-[11px] text-slate-500 tabular-nums">
                        {new Date(n.lastSeen).toLocaleDateString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* Tab bar */}
      <div className="flex items-center gap-1 bg-slate-100 rounded-xl p-1 w-fit overflow-x-auto">
        {SECTIONS.map(({ key, label, icon: Icon }) => (
          <button key={key} onClick={() => setSection(key)} className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold whitespace-nowrap transition-colors ${section === key ? "bg-white text-slate-900 shadow-sm" : "text-slate-500 hover:text-slate-700"}`}>
            <Icon className="w-3.5 h-3.5" />
            {label}
            <span className={`min-w-[20px] h-5 px-1.5 rounded-full text-[10px] font-bold inline-flex items-center justify-center ${section === key ? (counts[key] > 0 ? "bg-red-50 text-red-600" : "bg-slate-100 text-slate-400") : "bg-white text-slate-500 border border-slate-200"}`}>{counts[key]}</span>
          </button>
        ))}
      </div>

      {/* HTTP Errors */}
      {section === "errors" && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50">
                <th className="px-5 py-2.5 w-20">Status</th>
                <th className="px-5 py-2.5">Page URL</th>
                <th className="px-5 py-2.5 text-right">Hits</th>
                <th className="px-5 py-2.5">First Seen</th>
                <th className="px-5 py-2.5">Last Seen</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {data!.httpErrors.map((e, i) => (
                <tr key={i} className="hover:bg-slate-50 transition-colors">
                  <td className="px-5 py-2.5"><span className={`text-[10px] font-bold px-2 py-0.5 rounded border ${statusBadge(e.statusCode)}`}>{e.statusCode === 200 ? "Soft 404" : e.statusCode}</span></td>
                  <td className="px-5 py-2.5 font-mono text-xs text-brand-600 truncate max-w-[320px]" title={e.pageUrl}>{e.pageUrl}</td>
                  <td className="px-5 py-2.5 text-right font-bold text-slate-900 tabular-nums">{e.occurrences}</td>
                  <td className="px-5 py-2.5 text-[11px] text-slate-500 tabular-nums">{new Date(e.firstSeen).toLocaleDateString(undefined, { month: "short", day: "numeric" })}</td>
                  <td className="px-5 py-2.5 text-[11px] text-slate-500 tabular-nums">{new Date(e.lastSeen).toLocaleDateString(undefined, { month: "short", day: "numeric" })}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Broken Links */}
      {section === "broken" && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50">
                <th className="px-5 py-2.5">Source Page</th>
                <th className="px-5 py-2.5">Broken URL</th>
                <th className="px-5 py-2.5">Link Text</th>
                <th className="px-5 py-2.5 text-right">Clicks</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {data!.brokenLinks.map((b, i) => (
                <tr key={i} className="hover:bg-slate-50 transition-colors">
                  <td className="px-5 py-2.5 font-mono text-xs text-slate-700 truncate max-w-[250px]" title={b.sourceUrl}>{b.sourceUrl}</td>
                  <td className="px-5 py-2.5 font-mono text-xs text-red-600 truncate max-w-[250px]" title={b.targetUrl}>{b.targetUrl}</td>
                  <td className="px-5 py-2.5 text-xs text-slate-500 truncate max-w-[150px]">{b.linkText || "—"}</td>
                  <td className="px-5 py-2.5 text-right font-bold text-slate-900 tabular-nums">{b.occurrences}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Redirects */}
      {section === "redirects" && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50">
                <th className="px-5 py-2.5">Original URL</th>
                <th className="px-5 py-2.5">Final URL</th>
                <th className="px-5 py-2.5 text-right">Hops</th>
                <th className="px-5 py-2.5 text-right">Avg Time</th>
                <th className="px-5 py-2.5 text-right">Hits</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {data!.redirects.map((r, i) => (
                <tr key={i} className="hover:bg-slate-50 transition-colors">
                  <td className="px-5 py-2.5 font-mono text-xs text-slate-700 truncate max-w-[250px]" title={r.originalUrl}>{r.originalUrl}</td>
                  <td className="px-5 py-2.5 font-mono text-xs text-brand-600 truncate max-w-[250px]" title={r.finalUrl}>{r.finalUrl}</td>
                  <td className="px-5 py-2.5 text-right tabular-nums">
                    <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${r.isChain ? "bg-amber-50 text-amber-700 border border-amber-200" : "bg-slate-100 text-slate-600"}`}>{r.redirectCount}</span>
                  </td>
                  <td className="px-5 py-2.5 text-right text-xs text-slate-500 tabular-nums">{r.avgRedirectTimeMs}ms</td>
                  <td className="px-5 py-2.5 text-right font-bold text-slate-900 tabular-nums">{r.occurrences}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Resource Errors */}
      {section === "resources" && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50">
                <th className="px-5 py-2.5">Page URL</th>
                <th className="px-5 py-2.5">Missing Resource</th>
                <th className="px-5 py-2.5">Type</th>
                <th className="px-5 py-2.5 text-right">Hits</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {data!.resourceErrors.map((r, i) => (
                <tr key={i} className="hover:bg-slate-50 transition-colors">
                  <td className="px-5 py-2.5 font-mono text-xs text-slate-700 truncate max-w-[250px]" title={r.pageUrl}>{r.pageUrl}</td>
                  <td className="px-5 py-2.5 font-mono text-xs text-red-600 truncate max-w-[300px]" title={r.resourceUrl}>{r.resourceUrl}</td>
                  <td className="px-5 py-2.5 text-xs text-slate-500 capitalize">{r.resourceType}</td>
                  <td className="px-5 py-2.5 text-right font-bold text-slate-900 tabular-nums">{r.occurrences}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ─── Runtime stat card ─────────────────────────────────────────
// Tone maps to the semantic severity of the count: red for JS
// exceptions + 404s (functional breakage), orange for resource
// failures (degraded but page still renders), slate for zero.

function RuntimeStat({
  icon: Icon, label, value, tone,
}: {
  icon: typeof AlertCircle;
  label: string;
  value: number;
  tone: "red" | "orange" | "slate";
}) {
  const palette = tone === "red"
    ? { border: "border-red-200",    bg: "bg-red-50",    icon: "text-red-600",    value: "text-red-700" }
    : tone === "orange"
    ? { border: "border-orange-200", bg: "bg-orange-50", icon: "text-orange-600", value: "text-orange-700" }
    : { border: "border-slate-200",  bg: "bg-slate-100", icon: "text-slate-400",  value: "text-slate-400" };
  return (
    <div className={`rounded-xl border bg-white ${palette.border} px-4 py-4`}>
      <div className="flex items-center gap-2 mb-2">
        <span className={`w-7 h-7 rounded-lg ${palette.bg} ${palette.icon} flex items-center justify-center`}>
          <Icon className="w-3.5 h-3.5" />
        </span>
        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">{label}</p>
      </div>
      <p className={`text-2xl font-bold tabular-nums leading-none ${palette.value}`}>{value.toLocaleString()}</p>
    </div>
  );
}
