import { getLocale, getTranslations, setRequestLocale } from "next-intl/server";
import { Link } from "@/i18n/navigation";
import { CopyButton } from "@/components/copy-button";
import { prisma } from "@/lib/prisma";
import { formatMoney, formatNumber } from "@/lib/money";
import { publicAppUrl, requireUser } from "@/lib/session";

export default async function LinksPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string }>;
  searchParams: Promise<{ type?: string }>;
}) {
  const { locale } = await params;
  const query = await searchParams;
  setRequestLocale(locale);
  const session = await requireUser();
  const t = await getTranslations("dashboard");
  const loc = await getLocale();
  const type = query.type === "FREE" || query.type === "PAID" ? query.type : undefined;
  const links = await prisma.shortLink.findMany({
    where: { ownerId: session.user.id, ...(type ? { monetization: type } : {}) },
    orderBy: { createdAt: "desc" },
  });
  const origin = await publicAppUrl();

  return (
    <div className="space-y-6">
      <h1 className="page-title">{t("linksTitle")}</h1>
      <div className="flex flex-wrap gap-2 text-sm">
        <Link href="/dashboard/links" className={`rounded-full px-3 py-1.5 ${!type ? "bg-brand text-white" : "border border-line"}`}>
          {t("allTypes")}
        </Link>
        <Link href="/dashboard/links?type=PAID" className={`rounded-full px-3 py-1.5 ${type === "PAID" ? "bg-brand text-white" : "border border-line"}`}>
          {t("paid")}
        </Link>
        <Link href="/dashboard/links?type=FREE" className={`rounded-full px-3 py-1.5 ${type === "FREE" ? "bg-brand text-white" : "border border-line"}`}>
          {t("free")}
        </Link>
      </div>
      <div className="card overflow-x-auto">
        <table className="w-full min-w-[700px] text-sm">
          <thead className="bg-background text-muted">
            <tr>
              <th className="p-3 text-start">{t("code")}</th>
              <th className="p-3 text-start">{t("destination")}</th>
              <th className="p-3 text-start">{t("type")}</th>
              <th className="p-3 text-start">{t("clicks")}</th>
              <th className="p-3 text-start">{t("earnings")}</th>
              <th className="p-3 text-start">{t("stats")}</th>
            </tr>
          </thead>
          <tbody>
            {links.length === 0 ? (
              <tr>
                <td className="p-4 text-muted" colSpan={6}>
                  {t("noItems")}
                </td>
              </tr>
            ) : (
              links.map((link) => (
                <tr key={link.id} className="border-t border-line">
                  <td className="p-3">
                    <div className="flex items-center gap-2">
                      <span dir="ltr">{link.code}</span>
                      <CopyButton value={`${origin}/s/${link.code}`} />
                    </div>
                  </td>
                  <td className="max-w-xs truncate p-3" dir="ltr">
                    {link.destinationUrl}
                  </td>
                  <td className="p-3">{link.monetization === "FREE" ? t("free") : t("paid")}</td>
                  <td className="p-3">{formatNumber(link.clicks, loc)}</td>
                  <td className="p-3">{formatMoney(link.earningsMicro, loc)}</td>
                  <td className="p-3">
                    <Link className="text-brand" href={`/dashboard/links/${link.id}`}>
                      {t("stats")}
                    </Link>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
