import { getLocale, getTranslations, setRequestLocale } from "next-intl/server";
import { notFound } from "next/navigation";
import { StatCard } from "@/components/stat-card";
import { prisma } from "@/lib/prisma";
import { formatMoney, formatNumber } from "@/lib/money";
import { requireUser } from "@/lib/session";
import { visitSummary } from "@/lib/stats";

export default async function LinkStatsPage({
  params,
}: {
  params: Promise<{ locale: string; id: string }>;
}) {
  const { locale, id } = await params;
  setRequestLocale(locale);
  const session = await requireUser();
  const t = await getTranslations("dashboard");
  const loc = await getLocale();
  const link = await prisma.shortLink.findFirst({
    where: { id, ownerId: session.user.id },
  });
  if (!link) notFound();
  const stats = await visitSummary(session.user.id, link.id, "LINK");

  return (
    <div className="space-y-6">
      <h1 className="page-title">{link.title || link.code}</h1>
      <p className="truncate text-muted" dir="ltr">
        {link.destinationUrl}
      </p>
      <div className="grid gap-4 sm:grid-cols-3">
        <StatCard label={t("clicks")} value={formatNumber(link.clicks, loc)} />
        <StatCard label={t("unique")} value={formatNumber(link.uniqueClicks, loc)} />
        <StatCard label={t("earnings")} value={formatMoney(link.earningsMicro, loc)} />
      </div>
      <section className="card p-5">
        <h2 className="mb-3 font-semibold">{t("byCountry")}</h2>
        <ul className="space-y-2 text-sm">
          {stats.byCountry.map((row) => (
            <li key={row.country} className="flex justify-between gap-4">
              <span>{row.country}</span>
              <span>
                {formatNumber(row._count._all, loc)} · {formatMoney(row._sum.earnedMicro ?? 0, loc)}
              </span>
            </li>
          ))}
        </ul>
      </section>
      <section className="card overflow-x-auto">
        <h2 className="p-4 font-semibold">{t("recentVisits")}</h2>
        <table className="w-full min-w-[600px] text-sm">
          <thead className="text-muted">
            <tr>
              <th className="p-3 text-start">{t("date")}</th>
              <th className="p-3 text-start">{t("country")}</th>
              <th className="p-3 text-start">{t("referrer")}</th>
              <th className="p-3 text-start">{t("counted")}</th>
              <th className="p-3 text-start">{t("earnings")}</th>
            </tr>
          </thead>
          <tbody>
            {stats.recent.map((visit) => (
              <tr key={visit.id} className="border-t border-line">
                <td className="p-3">{visit.createdAt.toLocaleString(loc)}</td>
                <td className="p-3">{visit.country}</td>
                <td className="max-w-xs truncate p-3" dir="ltr">
                  {visit.referrer || "-"}
                </td>
                <td className="p-3">{visit.counted ? "✓" : "—"}</td>
                <td className="p-3">{formatMoney(visit.earnedMicro, loc)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>
    </div>
  );
}
