import Link from "next/link";
import { ChevronRight, Gift, History, LockKeyhole, ShieldCheck, TicketCheck, UserRound, Wallet } from "lucide-react";
import { prisma } from "@/server/db";
import { requirePageUser } from "@/server/security/page-auth";
import { formatMoney } from "@/lib/utils";

export const dynamic = "force-dynamic";

export default async function ProfilePage() {
  const { user } = await requirePageUser();
  const [wallet, openBets, cryptoWithdrawals, vipProgress, pendingBonuses, latestKycCase] = await Promise.all([
    prisma.wallet.findUnique({
      where: { userId_currency: { userId: user.id, currency: user.profile?.currency ?? "EUR" } },
      include: { accounts: true }
    }),
    prisma.betTicket.count({ where: { userId: user.id, status: "OPEN" } }),
    prisma.cryptoWithdrawal.count({ where: { userId: user.id, status: "REQUESTED" } }),
    prisma.userVipProgress.findUnique({ where: { userId: user.id } }),
    prisma.userBonus.count({ where: { userId: user.id, status: "OFFERED", bonusAmount: { gt: 0 } } }),
    prisma.kycCase.findFirst({ where: { userId: user.id }, orderBy: { openedAt: "desc" } })
  ]);
  const available = wallet?.accounts.find((account) => account.type === "AVAILABLE")?.balance.toString() ?? "0";
  const bonus = wallet?.accounts.find((account) => account.type === "BONUS")?.balance.toString() ?? "0";
  const total = Number(available) + Number(bonus);
  const displayName = user.profile?.firstName ? user.profile.firstName.toUpperCase() : user.username.toUpperCase();
  const vipLabel = vipProgress?.tierKey ? vipProgress.tierKey : "Bois";
  const links = [
    ["/wallet", "Caisse", "Dépôts, retraits et transactions", Wallet, `${formatMoney(available)} disponible`],
    ["/vip", "Mes bonus", "Récompenses et conditions", Gift, `${pendingBonuses} à réclamer`],
    ["/settings", "Mon compte", "Email, mot de passe et informations", UserRound, user.email],
    ["/bets", "Historique de jeu", "Paris sportifs et résultats", History, `${openBets} ouvert(s)`],
    ["/kyc", "Vérification", "Documents et sécurité", ShieldCheck, kycMeta(latestKycCase?.status)]
  ] as const;

  return (
    <div className="mx-auto w-full max-w-[700px] space-y-2.5">
      <section className="overflow-hidden rounded-lg border border-white/10 bg-[#101521] p-3 shadow-panel">
        <div className="relative overflow-hidden rounded-lg border border-white/10 bg-[linear-gradient(135deg,#0e171f_0%,#12232b_62%,#0f181f_100%)] p-3">
          <div className="absolute inset-x-0 top-0 h-px bg-felt/60" />
          <div className="relative flex items-center justify-between gap-3">
            <div className="flex min-w-0 items-center gap-2.5">
              <span className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-felt/10 text-felt">
                <UserRound className="h-4 w-4" />
              </span>
              <div className="min-w-0">
                <div className="truncate text-lg font-bold text-white">{displayName}</div>
                <div className="mt-0.5 text-xs font-semibold text-slate-400">VIP {vipLabel}</div>
              </div>
            </div>
            <span className="rounded-full border border-felt/20 bg-felt/10 px-2.5 py-1 text-[11px] font-bold uppercase text-felt">
              Compte joueur
            </span>
          </div>

          <div className="mt-3 rounded-lg border border-white/10 bg-black/18 p-2.5">
            <BalanceLine label="Solde réel" value={formatMoney(available)} />
            <BalanceLine label="Solde bonus" value={formatMoney(bonus)} />
            <div className="mt-2 border-t border-white/10 pt-2">
              <BalanceLine label="Solde total" value={formatMoney(total)} strong />
            </div>
            <Link href="/wallet/deposit" className="mt-3 flex h-9 items-center justify-center gap-2 rounded-lg bg-felt text-sm font-bold text-ink-950 shadow-lg shadow-felt/20">
              Dépôt
              <Wallet className="h-4 w-4" />
            </Link>
          </div>
        </div>
      </section>

      <section className="grid grid-cols-2 gap-2">
        <MiniMetric icon={TicketCheck} label="Paris ouvert(s)" value={String(openBets)} helper="En cours" />
        <MiniMetric icon={LockKeyhole} label="Retraits" value={String(cryptoWithdrawals)} helper="En attente" />
      </section>

      <section className="space-y-2">
        {links.map(([href, title, body, Icon, meta]) => (
          <Link key={href} href={href} className="group flex min-h-[54px] items-center gap-3 rounded-lg border border-white/10 bg-[#101521] px-3 shadow-panel transition hover:border-felt/30">
            <span className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-white/[0.06] text-felt">
              <Icon className="h-4 w-4" />
            </span>
            <span className="min-w-0 flex-1">
              <span className="block text-sm font-bold text-white">{title}</span>
              <span className="mt-0.5 block truncate text-xs font-semibold text-slate-400">{body}</span>
            </span>
            <span className="hidden max-w-[180px] truncate text-right text-xs font-bold text-slate-500 sm:block">{meta}</span>
            <ChevronRight className="h-4 w-4 shrink-0 text-slate-300 group-hover:text-felt" />
          </Link>
        ))}
      </section>
    </div>
  );
}

function kycMeta(status?: string) {
  if (status === "PENDING") return "Action requise";
  if (status === "APPROVED") return "Validé";
  if (status === "REJECTED") return "Refusé";
  if (status === "EXPIRED") return "Expiré";
  return "Non requis";
}

function BalanceLine({ label, value, strong = false }: { label: string; value: string; strong?: boolean }) {
  return (
    <div className="flex items-center justify-between gap-3 py-0.5">
      <span className={strong ? "text-sm font-bold text-white" : "text-xs font-semibold text-slate-300"}>{label}</span>
      <span className={strong ? "text-sm font-bold text-white" : "text-xs font-bold text-white"}>{value}</span>
    </div>
  );
}

function MiniMetric({ icon: Icon, label, value, helper }: { icon: typeof TicketCheck; label: string; value: string; helper: string }) {
  return (
    <article className="rounded-lg border border-white/10 bg-[#101521] p-2.5 shadow-panel">
      <div className="flex items-center justify-between gap-2">
        <span className="grid h-7 w-7 place-items-center rounded-lg bg-felt/10 text-felt">
          <Icon className="h-4 w-4" />
        </span>
        <span className="text-base font-bold text-white">{value}</span>
      </div>
      <div className="mt-2 text-xs font-semibold text-white">{label}</div>
      <div className="mt-0.5 text-[11px] font-semibold text-slate-500">{helper}</div>
    </article>
  );
}
