import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { INVOICE_STATUS } from "@/lib/invoice-utils";

function Stat({
  label,
  value,
  icon,
  color,
  href,
}: {
  label: string;
  value: string | number;
  icon: string;
  color: string;
  href?: string;
}) {
  const inner = (
    <div className="card flex items-center gap-4 p-5 transition hover:ring-2 hover:ring-blue-100">
      <div className={`flex h-12 w-12 items-center justify-center rounded-xl text-2xl ${color}`}>
        {icon}
      </div>
      <div>
        <div className="text-2xl font-bold">{value}</div>
        <div className="text-sm text-slate-500">{label}</div>
      </div>
    </div>
  );

  if (href) {
    return (
      <Link href={href} className="block">
        {inner}
      </Link>
    );
  }
  return inner;
}

export default async function AdminDashboard() {
  const [agencies, active, suspended, travelers, licenses, pendingInvoices] = await Promise.all([
    prisma.agency.count(),
    prisma.agency.count({ where: { status: "ACTIVE" } }),
    prisma.agency.count({ where: { status: "SUSPENDED" } }),
    prisma.traveler.count(),
    prisma.license.count({ where: { active: true } }),
    prisma.invoice.count({ where: { status: INVOICE_STATUS.PENDING } }),
  ]);

  const recent = await prisma.agency.findMany({
    take: 5,
    orderBy: { createdAt: "desc" },
    include: { license: true, _count: { select: { travelers: true } } },
  });

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Resumen general</h1>
        <p className="text-slate-500">Estado de la plataforma y agencias.</p>
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-5">
        <Stat label="Agencias totales" value={agencies} icon="🏢" color="bg-blue-100 text-blue-700" />
        <Stat label="Agencias activas" value={active} icon="✅" color="bg-emerald-100 text-emerald-700" />
        <Stat label="Suspendidas" value={suspended} icon="⛔" color="bg-red-100 text-red-700" />
        <Stat label="Viajeros totales" value={travelers} icon="🧳" color="bg-amber-100 text-amber-700" />
        <Stat
          label="Facturas pendientes"
          value={pendingInvoices}
          icon="🧾"
          color="bg-blue-100 text-blue-700"
          href="/admin/invoices"
        />
      </div>

      <div className="card p-5">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-lg font-semibold">Agencias recientes</h2>
          <Link href="/admin/agencies" className="btn-ghost text-sm text-blue-600">
            Ver todas →
          </Link>
        </div>
        {recent.length === 0 ? (
          <p className="text-sm text-slate-500">Aún no hay agencias registradas.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="text-left text-slate-500">
                <tr className="border-b border-slate-200">
                  <th className="py-2">Agencia</th>
                  <th className="py-2">Licencia</th>
                  <th className="py-2">Viajeros</th>
                  <th className="py-2">Estado</th>
                </tr>
              </thead>
              <tbody>
                {recent.map((a) => (
                  <tr key={a.id} className="border-b border-slate-100">
                    <td className="py-2 font-medium">{a.name}</td>
                    <td className="py-2">{a.license?.name ?? "—"}</td>
                    <td className="py-2">
                      {a._count.travelers}
                      {a.license ? ` / ${a.license.maxTravelers}` : ""}
                    </td>
                    <td className="py-2">
                      <span
                        className={`badge ${
                          a.status === "ACTIVE"
                            ? "bg-emerald-100 text-emerald-700"
                            : "bg-red-100 text-red-700"
                        }`}
                      >
                        {a.status === "ACTIVE" ? "Activa" : "Suspendida"}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <p className="text-sm text-slate-500">
        {licenses} tipos de licencia activos.{" "}
        <Link href="/admin/licenses" className="text-blue-600">
          Gestionar licencias
        </Link>
      </p>
    </div>
  );
}
