import type { Metadata } from "next";
import Link from "next/link";
import { AlertTriangle, Gauge, KeyRound, Terminal } from "lucide-react";
import { db } from "@/lib/db";
import { money } from "@/lib/serialize";
import { getOptionalUser } from "@/lib/guards";
import { getGeneralSettings } from "@/lib/settings";
import { affiliatesTexts } from "@/lib/i18n/affiliates";
import { commonTexts } from "@/lib/i18n/common";
import { PanelShell } from "@/components/panel/shell";
import { PublicNavbar } from "@/components/public/navbar";
import {
  API_ACTIONS,
  API_CONTENT_TYPE,
  API_DELAY_VALUES,
  API_ERROR_EXAMPLE,
  API_ERROR_REFERENCE,
  API_HTTP_NOTE,
  API_METHOD,
  API_RATE_LIMIT,
  API_RESPONSE_FORMAT,
  API_VERSION,
  apiEndpointUrl,
} from "@/lib/api-docs";
import { ActionSection } from "./_components/action-section";
import { CodeBlock } from "./_components/code-block";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "API — SMM Panel",
  description:
    "Documentation for the SMM Panel API v2: services, add, status, refill, refill_status, cancel and balance.",
};

const texts = affiliatesTexts.api;

function EndpointCard({ endpoint }: { endpoint: string }) {
  return (
    <div className="rounded-2xl border bg-card shadow-sm">
      <div className="flex flex-col gap-4 border-b px-5 py-5 sm:px-6">
        <div className="flex flex-wrap items-center gap-3">
          <span className="rounded-md bg-blue-600 px-2.5 py-1 font-mono text-xs font-semibold tracking-wide text-white">
            {API_METHOD}
          </span>
          <code className="font-mono text-sm break-all sm:text-base">{endpoint}</code>
        </div>
        <p className="max-w-3xl text-sm text-muted-foreground">{API_HTTP_NOTE}</p>
      </div>

      <dl className="grid gap-px bg-border sm:grid-cols-2 lg:grid-cols-4">
        <div className="bg-card px-5 py-4 sm:px-6">
          <dt className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
            {texts.httpMethod}
          </dt>
          <dd className="mt-1 font-mono text-sm">{API_METHOD}</dd>
        </div>
        <div className="bg-card px-5 py-4 sm:px-6">
          <dt className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
            {texts.contentType}
          </dt>
          <dd className="mt-1 font-mono text-sm break-all">{API_CONTENT_TYPE}</dd>
        </div>
        <div className="bg-card px-5 py-4 sm:px-6">
          <dt className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
            {texts.responseFormat}
          </dt>
          <dd className="mt-1 font-mono text-sm">{API_RESPONSE_FORMAT}</dd>
        </div>
        <div className="bg-card px-5 py-4 sm:px-6">
          <dt className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
            {texts.rateLimitTitle}
          </dt>
          <dd className="mt-1 font-mono text-sm">
            {API_RATE_LIMIT.requests}/{API_RATE_LIMIT.windowSeconds}s
          </dd>
        </div>
      </dl>
    </div>
  );
}

function DocsBody({ endpoint, panelName }: { endpoint: string; panelName: string }) {
  return (
    <div className="space-y-8">
      <header className="space-y-2">
        <div className="flex items-center gap-2 text-xs font-semibold tracking-wider text-primary uppercase">
          <Terminal className="size-3.5" />
          {panelName} API {API_VERSION}
        </div>
        <h1 className="font-display text-2xl font-semibold tracking-tight sm:text-3xl">
          {texts.title}
        </h1>
        <p className="max-w-3xl text-sm text-muted-foreground sm:text-base">{texts.subtitle}</p>
      </header>

      <EndpointCard endpoint={endpoint} />

      <div className="grid gap-4 lg:grid-cols-2">
        <div className="flex gap-3 rounded-2xl border bg-card p-5 shadow-sm">
          <div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary">
            <KeyRound className="size-[18px]" />
          </div>
          <div className="space-y-2">
            <p className="font-display text-sm font-semibold">{texts.apiKeyTitle}</p>
            <p className="text-sm text-muted-foreground">{texts.apiKeyHint}</p>
            <Link
              href="/account"
              className="inline-flex text-sm font-medium text-primary transition-colors hover:underline"
            >
              {texts.apiKeyCta} →
            </Link>
          </div>
        </div>

        <div className="flex gap-3 rounded-2xl border bg-card p-5 shadow-sm">
          <div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-cyan-500/10 text-cyan-600 dark:text-cyan-400">
            <Gauge className="size-[18px]" />
          </div>
          <div className="space-y-2">
            <p className="font-display text-sm font-semibold">{texts.rateLimitTitle}</p>
            <p className="text-sm text-muted-foreground">{API_RATE_LIMIT.note}</p>
          </div>
        </div>
      </div>

      <nav className="rounded-2xl border bg-muted/30 p-4 sm:p-5">
        <p className="mb-3 text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
          {texts.onThisPage}
        </p>
        <div className="flex flex-wrap gap-2">
          {API_ACTIONS.map((action) => (
            <a
              key={action.id}
              href={`#${action.id}`}
              className="rounded-lg border bg-card px-2.5 py-1.5 font-mono text-xs transition-colors hover:border-primary/40 hover:text-primary"
            >
              {action.action}
            </a>
          ))}
          <a
            href="#errors"
            className="rounded-lg border bg-card px-2.5 py-1.5 font-mono text-xs transition-colors hover:border-primary/40 hover:text-primary"
          >
            errors
          </a>
        </div>
      </nav>

      <div className="space-y-8">
        {API_ACTIONS.map((action, i) => (
          <ActionSection
            key={action.id}
            action={action}
            endpoint={endpoint}
            index={i + 1}
          />
        ))}
      </div>

      <section id="delay-values" className="scroll-mt-24 rounded-2xl border bg-card p-5 shadow-sm sm:p-6">
        <h2 className="font-display text-lg font-semibold tracking-tight">
          {texts.delayValuesTitle}
        </h2>
        <p className="mt-1.5 max-w-3xl text-sm text-muted-foreground">
          A Subscriptions order is rejected with <code className="font-mono">Incorrect request</code>{" "}
          when <code className="font-mono">delay</code> is not one of these minute values.
        </p>
        <div className="mt-4 flex flex-wrap gap-1.5">
          {API_DELAY_VALUES.map((value) => (
            <span
              key={value}
              className="rounded-md border bg-muted/40 px-2 py-1 font-mono text-xs"
            >
              {value}
            </span>
          ))}
        </div>
      </section>

      <section id="errors" className="scroll-mt-24">
        <div className="rounded-2xl border bg-card shadow-sm">
          <div className="border-b px-5 py-5 sm:px-6">
            <div className="flex items-center gap-2">
              <AlertTriangle className="size-4 text-rose-500" />
              <h2 className="font-display text-lg font-semibold tracking-tight">
                {texts.errorsTitle}
              </h2>
            </div>
            <p className="mt-1.5 max-w-3xl text-sm text-muted-foreground">{texts.errorsHint}</p>
          </div>
          <div className="space-y-5 px-5 py-5 sm:px-6">
            <div className="overflow-x-auto rounded-xl border">
              <table className="w-full min-w-[520px] text-sm">
                <thead>
                  <tr className="border-b bg-muted/40 text-left">
                    <th className="px-3 py-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                      {texts.errorColumn}
                    </th>
                    <th className="px-3 py-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                      {texts.errorWhenColumn}
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {API_ERROR_REFERENCE.map((row) => (
                    <tr key={row.error} className="border-b align-top last:border-0">
                      <td className="px-3 py-2.5 font-mono text-[13px] whitespace-nowrap text-rose-600 dark:text-rose-400">
                        {row.error}
                      </td>
                      <td className="px-3 py-2.5 text-muted-foreground">{row.when}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <CodeBlock tone="response" label="200 OK — error body" code={API_ERROR_EXAMPLE} />
          </div>
        </div>
      </section>
    </div>
  );
}

export default async function ApiDocsPage() {
  const [sessionUser, general] = await Promise.all([
    getOptionalUser(),
    getGeneralSettings(),
  ]);

  const endpoint = apiEndpointUrl(process.env.APP_URL ?? "http://localhost:3000");
  const panelName = general.panelName || commonTexts.appName;

  if (sessionUser) {
    const row = await db.user.findUnique({
      where: { id: sessionUser.id },
      select: { balance: true },
    });

    return (
      <PanelShell
        user={{
          id: sessionUser.id,
          username: sessionUser.username,
          role: sessionUser.role,
          balance: money(row?.balance ?? 0, general.currencySymbol || "$"),
          impersonated: Boolean(sessionUser.impersonatedBy),
        }}
      >
        <DocsBody endpoint={endpoint} panelName={panelName} />
      </PanelShell>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <PublicNavbar />
      <main className="mx-auto w-full max-w-screen-xl px-4 py-10 sm:px-6 lg:px-8 lg:py-14">
        <DocsBody endpoint={endpoint} panelName={panelName} />
      </main>
    </div>
  );
}
