import type { ReactNode } from 'react';

import type { Metadata } from 'next';
import { refresh } from 'next/cache';
import { notFound } from 'next/navigation';

import {
  type ApiCallLogEntry,
  type ApiCallTrigger,
  clearRecentApiCalls,
  getRecentApiCalls,
  isApiDebugEnabled,
} from '@/services/openApiFetch';

// Internal debug view of recent data requests made through the openApiFetch wrapper
// (served by the Java API or by the Next fetch cache). Outside production every page sits
// behind Basic auth (src/proxy.ts), so it is only visible to the team. Deliberately
// styled on its own (not the design system): it is a measuring tool.
export const dynamic = 'force-dynamic';

export const metadata: Metadata = {
  robots: { index: false, follow: false },
};

async function clearApiCalls() {
  'use server';
  if (!isApiDebugEnabled()) return;
  clearRecentApiCalls();
  refresh();
}

const TRIGGERS: Record<ApiCallTrigger, { label: string; className: string; hint: string }> = {
  build: {
    label: 'build',
    className: 'bg-slate-200 text-slate-700',
    hint: 'next build előrenderelés (másik folyamat, ritkán látszik itt)',
  },
  isr: {
    label: 'ISR',
    className: 'bg-indigo-100 text-indigo-800',
    hint: 'statikus oldal első renderelése vagy háttérfrissítése (látogatás vagy prefetch indította)',
  },
  revalidate: {
    label: 'admin frissítés',
    className: 'bg-pink-100 text-pink-800',
    hint: 'revalidatePath után újrarenderelt oldal',
  },
  'page-load': {
    label: 'oldalbetöltés',
    className: 'bg-teal-100 text-teal-800',
    hint: 'dinamikus oldal teljes betöltése',
  },
  navigation: {
    label: 'navigáció',
    className: 'bg-cyan-100 text-cyan-800',
    hint: 'kliensoldali navigáció egy dinamikus oldalra (RSC kérés)',
  },
  prefetch: {
    label: 'prefetch',
    className: 'bg-amber-100 text-amber-800',
    hint: 'egy link előtöltése egy dinamikus oldalra',
  },
  api: {
    label: 'API route',
    className: 'bg-violet-100 text-violet-800',
    hint: 'a Next /api/... végpontja hívta (a böngésző fetch-e indította)',
  },
  other: { label: 'egyéb', className: 'bg-slate-100 text-slate-600', hint: 'ismeretlen kontextus' },
};

const timeFormatter = new Intl.DateTimeFormat('hu-HU', {
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  fractionalSecondDigits: 3,
  timeZone: 'Europe/Budapest',
});

function Badge({
  className,
  title,
  children,
}: {
  className: string;
  title?: string;
  children: ReactNode;
}) {
  return (
    <span
      title={title}
      className={`inline-flex items-center whitespace-nowrap rounded-md px-1.5 py-0.5 font-sans text-[11px] font-semibold ${className}`}
    >
      {children}
    </span>
  );
}

function statusClass(outcome: string) {
  if (outcome.startsWith('2')) return 'bg-emerald-100 text-emerald-800';
  if (outcome.startsWith('3')) return 'bg-sky-100 text-sky-800';
  if (outcome.startsWith('4')) return 'bg-orange-100 text-orange-800';
  return 'bg-red-100 text-red-800';
}

function sourceClass(source: string) {
  if (source === 'java') return 'bg-emerald-600 text-white';
  if (source.startsWith('stale')) return 'bg-amber-100 text-amber-900';
  if (source.startsWith('cache')) return 'bg-sky-100 text-sky-800';
  return 'bg-slate-100 text-slate-600';
}

function durationClass(ms: number) {
  if (ms >= 1000) return 'text-red-600 font-semibold';
  if (ms >= 300) return 'text-amber-600 font-semibold';
  return 'text-slate-500';
}

/** Path in ink, query keys blue, values amber, separators muted. */
function UrlView({ value }: { value: string }) {
  const queryStart = value.indexOf('?');
  const path = queryStart === -1 ? value : value.slice(0, queryStart);
  const query = queryStart === -1 ? undefined : value.slice(queryStart + 1);
  return (
    <span className="break-all">
      <span className="text-slate-900">{path}</span>
      {query !== undefined && <span className="text-slate-400">?</span>}
      {query?.split('&').map((pair, index) => {
        const [key, ...rest] = pair.split('=');
        return (
          <span key={index}>
            {index > 0 && <span className="text-slate-400">&amp;</span>}
            <span className="text-sky-700">{key}</span>
            {rest.length > 0 && (
              <>
                <span className="text-slate-400">=</span>
                <span className="text-amber-700">{rest.join('=')}</span>
              </>
            )}
          </span>
        );
      })}
    </span>
  );
}

const JSON_TOKEN =
  /("(?:\\.|[^"\\])*")(\s*:)?|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g;

/** Keys blue, strings amber, numbers violet, literals rose; works on truncated JSON too. */
function JsonView({ value }: { value: string }) {
  const parts: ReactNode[] = [];
  let last = 0;
  for (const match of value.matchAll(JSON_TOKEN)) {
    const index = match.index ?? 0;
    if (index > last)
      parts.push(
        <span key={`p${last}`} className="text-slate-400">
          {value.slice(last, index)}
        </span>
      );
    const [token, string, colon] = match;
    const className = colon
      ? 'text-sky-700'
      : string
        ? 'text-amber-700'
        : /^(true|false|null)$/.test(token)
          ? 'text-rose-600'
          : 'text-violet-700';
    parts.push(
      <span key={index} className={className}>
        {colon ? string : token}
      </span>
    );
    if (colon)
      parts.push(
        <span key={`c${index}`} className="text-slate-400">
          {colon}
        </span>
      );
    last = index + token.length;
  }
  if (last < value.length)
    parts.push(
      <span key="end" className="text-slate-400">
        {value.slice(last)}
      </span>
    );
  return <span className="whitespace-pre-wrap break-all">{parts}</span>;
}

type CallGroup = {
  key: string;
  page: string | null;
  route: string | null;
  trigger: ApiCallTrigger;
  calls: ApiCallLogEntry[];
};

// Consecutive calls of the same render belong together (newest first).
function groupCalls(calls: ApiCallLogEntry[]): CallGroup[] {
  const groups: CallGroup[] = [];
  for (const call of calls) {
    const key = `${call.trigger}|${call.page ?? ''}`;
    const current = groups.at(-1);
    if (current?.key === key) current.calls.push(call);
    else
      groups.push({
        key,
        page: call.page,
        route: call.route,
        trigger: call.trigger,
        calls: [call],
      });
  }
  return groups;
}

function Stat({
  label,
  value,
  className = 'text-slate-900',
}: {
  label: string;
  value: ReactNode;
  className?: string;
}) {
  return (
    <div className="rounded-lg border border-slate-200 bg-white px-3 py-2">
      <div className="text-[11px] font-medium uppercase tracking-wide text-slate-500">{label}</div>
      <div className={`text-lg font-semibold tabular-nums ${className}`}>{value}</div>
    </div>
  );
}

export default function ApiCallsPage() {
  if (!isApiDebugEnabled()) notFound();

  const calls = getRecentApiCalls();
  const groups = groupCalls(calls);
  const javaCalls = calls.filter((call) => call.source === 'java');
  const javaAverage = javaCalls.length
    ? Math.round(javaCalls.reduce((sum, call) => sum + call.durationMs, 0) / javaCalls.length)
    : null;
  const failures = calls.filter((call) => !call.outcome.startsWith('2')).length;

  return (
    <div className="min-h-screen bg-slate-50 px-4 py-6 font-sans text-slate-800 sm:px-8">
      <div className="mx-auto flex max-w-[1600px] flex-col gap-5">
        <header className="flex flex-wrap items-end justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-slate-900">openApiFetch</h1>
            <p className="text-sm text-slate-500">
              A szerverfolyamat utolsó {calls.length} lekérése az <code>openApiFetch</code>{' '}
              wrapperen át (max. 300), legfrissebb elöl. Valódi Java-hívás csak a{' '}
              <span className="font-semibold text-emerald-700">java</span> jelvényű sor; a többit a
              Next fetch-cache szolgálta ki. A cache-ből kiszolgált oldalak nem renderelődnek, ezért
              azok itt meg sem jelennek.
            </p>
          </div>
          <div className="flex gap-2">
            <a
              href=""
              className="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 shadow-sm hover:bg-slate-100"
            >
              Frissítés
            </a>
            <form action={clearApiCalls}>
              <button
                type="submit"
                className="rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-700"
              >
                Lista törlése
              </button>
            </form>
          </div>
        </header>

        <section className="grid grid-cols-2 gap-3 sm:grid-cols-5">
          <Stat label="Lekérések" value={calls.length} />
          <Stat label="Valódi Java-hívás" value={javaCalls.length} className="text-emerald-700" />
          <Stat
            label="Fetch-cache"
            value={calls.length - javaCalls.length}
            className="text-sky-700"
          />
          <Stat label="Átlag Java ms" value={javaAverage ?? '–'} />
          <Stat
            label="Hibás"
            value={failures}
            className={failures ? 'text-red-600' : 'text-slate-900'}
          />
        </section>

        <details className="rounded-lg border border-slate-200 bg-white px-4 py-3 text-sm">
          <summary className="cursor-pointer font-semibold text-slate-700">Jelmagyarázat</summary>
          <div className="mt-3 grid gap-x-8 gap-y-2 md:grid-cols-2">
            <div className="space-y-1.5">
              <div className="font-semibold text-slate-600">Mi renderelt (csoportfejléc)</div>
              {Object.entries(TRIGGERS).map(([key, trigger]) => (
                <div key={key} className="flex items-start gap-2">
                  <Badge className={trigger.className}>{trigger.label}</Badge>
                  <span className="text-slate-600">{trigger.hint}</span>
                </div>
              ))}
            </div>
            <div className="space-y-1.5">
              <div className="font-semibold text-slate-600">Honnan jött a válasz</div>
              <div className="flex gap-2">
                <Badge className={sourceClass('java')}>java</Badge>
                <span className="text-slate-600">
                  valódi Java-hívás, a Node megvárta (ms = Java válaszidő)
                </span>
              </div>
              <div className="flex gap-2">
                <Badge className={sourceClass('cache 1s')}>cache Ns</Badge>
                <span className="text-slate-600">
                  friss Next fetch-cache, a Java N másodperce adta
                </span>
              </div>
              <div className="flex gap-2">
                <Badge className={sourceClass('stale')}>stale cache Ns</Badge>
                <span className="text-slate-600">
                  lejárt cache: a régi adat ment ki, a Next a háttérben újra lekéri
                </span>
              </div>
              <div className="flex gap-2">
                <Badge className={sourceClass('?')}>?</Badge>
                <span className="text-slate-600">nem volt Date header; „-” = hálózati hiba</span>
              </div>
              <div className="pt-2 text-slate-600">
                ms: <span className="text-slate-500">gyors</span> ·{' '}
                <span className="font-semibold text-amber-600">≥ 300</span> ·{' '}
                <span className="font-semibold text-red-600">≥ 1000</span>. Az URL-ben és a bodyban
                a <span className="text-sky-700">kulcsok</span> kékek, az{' '}
                <span className="text-amber-700">értékek</span> borostyánszínűek.
              </div>
            </div>
          </div>
        </details>

        {groups.length === 0 && (
          <div className="rounded-lg border border-dashed border-slate-300 bg-white p-10 text-center text-slate-500">
            Nincs rögzített hívás. Nyiss meg egy oldalt egy másik lapon, majd frissítsd ezt.
          </div>
        )}

        {groups.map((group, groupIndex) => {
          const trigger = TRIGGERS[group.trigger];
          const newest = group.calls[0];
          const oldest = group.calls.at(-1)!;
          return (
            <section
              key={`${group.key}-${groupIndex}`}
              className="overflow-hidden rounded-lg border border-slate-200 bg-white shadow-sm"
            >
              <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-b border-slate-200 bg-slate-100 px-4 py-2">
                <Badge className={trigger.className} title={trigger.hint}>
                  {trigger.label}
                </Badge>
                <span className="font-mono text-sm font-semibold">
                  {group.page ? (
                    <UrlView value={group.page} />
                  ) : (
                    <span className="text-slate-400">ismeretlen oldal</span>
                  )}
                </span>
                {group.route && group.route !== group.page && (
                  <span className="font-mono text-xs text-slate-500">{group.route}</span>
                )}
                <span className="ml-auto text-xs tabular-nums text-slate-500">
                  {group.calls.length} hívás · {timeFormatter.format(new Date(oldest.at))}
                  {group.calls.length > 1 && ` – ${timeFormatter.format(new Date(newest.at))}`}
                </span>
              </div>
              <div className="overflow-x-auto">
                {/* Fixed columns keep every group aligned with the others. */}
                <table className="w-full min-w-[1100px] table-fixed text-left font-mono text-xs">
                  <colgroup>
                    <col className="w-[7.5rem]" />
                    <col />
                    <col className="w-[5.5rem]" />
                    <col className="w-[9.5rem]" />
                    <col className="w-[4rem]" />
                    <col className="w-[8.5rem]" />
                    <col className="w-[32%]" />
                  </colgroup>
                  <thead className="bg-white text-[11px] uppercase tracking-wide text-slate-400">
                    <tr>
                      <th className="px-3 py-1.5 font-medium">Idő</th>
                      <th className="px-3 py-1.5 font-medium">Hívás</th>
                      <th className="px-3 py-1.5 font-medium">Státusz</th>
                      <th className="px-3 py-1.5 font-medium">Forrás</th>
                      <th className="px-3 py-1.5 text-right font-medium">ms</th>
                      <th className="px-3 py-1.5 font-medium">Cache</th>
                      <th className="px-3 py-1.5 font-medium">Body</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {group.calls.map((call, index) => (
                      <tr key={`${call.at}-${index}`} className="align-top hover:bg-slate-50">
                        <td className="whitespace-nowrap px-3 py-1.5 tabular-nums text-slate-500">
                          {timeFormatter.format(new Date(call.at))}
                        </td>
                        <td className="px-3 py-1.5">
                          <Badge
                            className={
                              call.method === 'GET'
                                ? 'mr-2 bg-blue-100 text-blue-800'
                                : 'mr-2 bg-purple-100 text-purple-800'
                            }
                          >
                            {call.method}
                          </Badge>
                          <UrlView value={call.path} />
                        </td>
                        <td className="px-3 py-1.5">
                          <Badge className={statusClass(call.outcome)}>{call.outcome}</Badge>
                        </td>
                        <td className="px-3 py-1.5">
                          <Badge className={sourceClass(call.source)}>{call.source}</Badge>
                        </td>
                        <td
                          className={`px-3 py-1.5 text-right tabular-nums ${durationClass(call.durationMs)}`}
                        >
                          {call.durationMs}
                        </td>
                        <td className="whitespace-nowrap px-3 py-1.5 text-slate-500">
                          {call.cache}
                        </td>
                        <td className="px-3 py-1.5">
                          {call.body ? (
                            <JsonView value={call.body} />
                          ) : (
                            <span className="text-slate-300">–</span>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>
          );
        })}
      </div>
    </div>
  );
}
