import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { BilanList } from "@/components/BilanList";

export default async function DashboardPage() {
  const session = await auth();
  const pharmacyId = session!.user.pharmacyId!;

  const pharmacy = await prisma.pharmacy.findUniqueOrThrow({ where: { id: pharmacyId } });

  const startOfMonth = new Date();
  startOfMonth.setDate(1);
  startOfMonth.setHours(0, 0, 0, 0);

  const [bilans, monthlyCount] = await Promise.all([
    prisma.bilan.findMany({
      where: { pharmacyId },
      orderBy: { createdAt: "desc" },
      take: 20,
    }),
    prisma.bilan.count({ where: { pharmacyId, createdAt: { gte: startOfMonth } } }),
  ]);

  const overage = Math.max(0, monthlyCount - 30);

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-xl font-bold text-[#07008b]">Bienvenue dans votre espace, {pharmacy.name}</h1>
        <p className="text-sm text-slate-500 mt-1">
          Retrouvez ici votre QR code patient et les bilans reçus.
        </p>
      </div>

      <section className="grid gap-4 sm:grid-cols-3">
        <div className="bg-white border border-slate-200 rounded-xl p-4">
          <div className="text-xs text-slate-400 mb-1">Bilans ce mois-ci</div>
          <div className="text-2xl font-extrabold text-[#07008b]">{monthlyCount} / 30</div>
          {overage > 0 && (
            <div className="text-xs text-amber-600 mt-1">
              {overage} bilan{overage > 1 ? "s" : ""} supplémentaire{overage > 1 ? "s" : ""} (≈ {overage * 2} € HT)
            </div>
          )}
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-4">
          <div className="text-xs text-slate-400 mb-1">Statut du compte</div>
          <div className="text-2xl font-extrabold text-[#07008b]">
            {pharmacy.status === "ACTIVE" ? "Actif" : pharmacy.status}
          </div>
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-4">
          <div className="text-xs text-slate-400 mb-1">Lien patient</div>
          <a href={`/b/${pharmacy.slug}`} target="_blank" className="text-sm text-[#07008b] font-semibold underline break-all">
            /b/{pharmacy.slug}
          </a>
        </div>
      </section>

      <section className="bg-white border border-slate-200 rounded-xl p-5">
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-bold text-[#07008b]">Mon QR code patient</h2>
          <a
            href={`/api/pharmacies/${pharmacy.id}/qr`}
            download
            className="text-xs rounded-lg bg-[#07008b] text-white font-semibold px-3 py-1.5"
          >
            Télécharger
          </a>
        </div>
        {pharmacy.qrCodeUrl ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img src={`/api/pharmacies/${pharmacy.id}/qr`} alt="QR code patient" className="w-40 h-40" />
        ) : (
          <p className="text-sm text-slate-400">QR code non encore généré.</p>
        )}
      </section>

      <section className="bg-white border border-slate-200 rounded-xl p-5">
        <h2 className="font-bold text-[#07008b] mb-4">Bilans reçus</h2>
        <BilanList bilans={bilans} hrefFor={(id) => `/dashboard/bilans/${id}`} />
      </section>
    </div>
  );
}
