import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { AccountActions } from "@/components/account/AccountActions";
import { getCurrentUser, hasPremium } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getToolBySlug } from "@/tools/registry";

export const metadata: Metadata = {
  title: "Account verwalten",
  description: "Toolaro Account, Premium-Abo, Favoriten, Verlauf, Einstellungen, Newsletter und Datenschutz verwalten.",
};

export default async function AccountPage() {
  const user = await getCurrentUser();
  if (!user) redirect("/login");
  const [favorites, history, settings, newsletter, subscriptions, billing] = await Promise.all([
    prisma.favoriteTool.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" } }),
    prisma.toolUsage.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" }, take: 20 }),
    prisma.userToolSetting.findMany({ where: { userId: user.id }, orderBy: { updatedAt: "desc" }, take: 20 }),
    prisma.newsletterSubscription.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" }, take: 5 }),
    prisma.premiumSubscription.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" }, take: 3 }),
    prisma.billingEvent.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" }, take: 10 }),
  ]);
  const premium = hasPremium(user);

  return (
    <div className="mx-auto max-w-6xl px-4 py-12">
      <div className="mb-8 flex flex-wrap items-start justify-between gap-4">
        <div>
          <p
            className="mb-2 text-[0.7rem] font-bold uppercase tracking-[0.2em] text-brand-500"
            style={{ fontFamily: '"Courier New", monospace' }}
          >
            Toolaro · Mein Konto
          </p>
          <h1 className="font-display text-3xl font-bold uppercase tracking-tight text-ink-primary">
            Mein Toolaro
          </h1>
          <p
            className="mt-1 text-[0.75rem] font-bold uppercase tracking-[0.1em] text-ink-tertiary"
            style={{ fontFamily: '"Courier New", monospace' }}
          >
            {user.email}
          </p>
        </div>
        <span
          className={`border-2 px-4 py-2 text-[0.7rem] font-bold uppercase tracking-[0.12em] ${
            premium
              ? "border-brand-500 bg-brand-50 text-brand-600"
              : "border-ink-primary/40 bg-surface-sunken text-ink-secondary"
          }`}
          style={{ fontFamily: '"Courier New", monospace' }}
        >
          {premium ? "Premium aktiv" : "Kostenlos"}
        </span>
      </div>

      <div className="grid gap-5 lg:grid-cols-2">
        <Panel title="Profil und Sicherheit">
          <Rows
            rows={[
              ["Name", user.name ?? "-"],
              ["E-Mail", user.email],
              ["E-Mail bestätigt", user.emailVerifiedAt ? "ja" : "nein"],
              ["2FA per E-Mail", user.twoFactorEnabled ? "aktiv" : "aktiviert"],
            ]}
          />
          <p className="mt-4 text-sm leading-6 text-ink-secondary">
            Passwort-Reset läuft per zeitlich begrenztem Einmal-Link. Sessions werden serverseitig
            gespeichert und können bei Passwortwechsel gelöscht werden.
          </p>
        </Panel>

        <Panel title="Abo-Status">
          <Rows
            rows={[
              ["Status", user.premiumStatus],
              ["Premium bis", user.premiumUntil?.toLocaleDateString("de-DE") ?? "-"],
              ["Werbung", premium ? "ausgeblendet" : "sichtbar"],
            ]}
          />
          <Link
            href="/pricing"
            className="mt-4 inline-block text-[0.75rem] font-bold uppercase tracking-[0.1em] text-brand-500 underline underline-offset-4 hover:text-brand-600"
            style={{ fontFamily: '"Courier New", monospace' }}
          >
            Premium ansehen
          </Link>
        </Panel>

        <Panel title="Favoriten">
          <List
            items={favorites.map((item) => getToolBySlug(item.toolSlug)?.name ?? item.toolSlug)}
            empty="Noch keine serverseitigen Favoriten."
          />
        </Panel>

        <Panel title="Zuletzt genutzte Tools">
          <List
            items={history.map(
              (item) =>
                `${getToolBySlug(item.toolSlug)?.name ?? item.toolSlug} · ${item.createdAt.toLocaleDateString("de-DE")}`
            )}
            empty="Noch kein synchronisierter Verlauf."
          />
        </Panel>

        <Panel title="Gespeicherte Tool-Einstellungen">
          <List
            items={settings.map((item) => `${getToolBySlug(item.toolSlug)?.name ?? item.toolSlug}: ${item.key}`)}
            empty="Noch keine gespeicherten Einstellungen."
          />
        </Panel>

        <Panel title="Newsletter">
          <Rows
            rows={[
              ["Aktueller Status", user.newsletterOptIn ? "aktiv" : "nicht aktiv"],
              ["Letzte Einträge", String(newsletter.length)],
            ]}
          />
        </Panel>

        <Panel title="Zahlungen und Rechnungen">
          <List
            items={[
              ...subscriptions.map((item) => `${item.plan} · ${item.status}`),
              ...billing.map(
                (item) => `${item.eventType} · ${item.createdAt.toLocaleDateString("de-DE")}`
              ),
            ]}
            empty="Noch keine Zahlungsereignisse."
          />
        </Panel>

        <Panel title="Datenschutz und Verwaltung">
          <p className="mb-4 text-sm leading-6 text-ink-secondary">
            Du kannst Daten exportieren, Newsletter-Einstellungen ändern, Verlauf/Favoriten verwalten,
            dein Abo kündigen oder den Account löschen.
          </p>
          <AccountActions newsletterOptIn={user.newsletterOptIn} />
        </Panel>
      </div>
    </div>
  );
}

function Panel({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="border-2 border-ink-primary bg-surface-base p-6 shadow-[4px_4px_0_rgb(var(--ink-primary))]">
      <h2
        className="mb-4 text-[0.7rem] font-bold uppercase tracking-[0.16em] text-ink-secondary"
        style={{ fontFamily: '"Courier New", monospace' }}
      >
        {title}
      </h2>
      {children}
    </section>
  );
}

function Rows({ rows }: { rows: Array<[string, string]> }) {
  return (
    <div className="space-y-2">
      {rows.map(([k, v]) => (
        <div key={k} className="flex justify-between gap-4 border border-ink-primary/20 bg-surface-sunken px-3 py-2 text-sm">
          <span className="text-ink-tertiary">{k}</span>
          <strong className="text-right font-mono text-ink-primary">{v}</strong>
        </div>
      ))}
    </div>
  );
}

function List({ items, empty }: { items: string[]; empty: string }) {
  if (!items.length) return <p className="text-sm text-ink-tertiary">{empty}</p>;
  return (
    <ul className="space-y-2 text-sm">
      {items.map((item) => (
        <li key={item} className="border border-ink-primary/20 bg-surface-sunken px-3 py-2 font-mono text-ink-secondary">
          {item}
        </li>
      ))}
    </ul>
  );
}
