import {notFound, redirect} from "next/navigation";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {RegisterPaymentForm} from "@/features/invoices/components/register-payment-form";

export default async function PaymentsPage({params}: {params: Promise<{tenantSlug: string; locale: string}>}) {
  const {tenantSlug, locale} = await params;
  const session = await auth();
  if (!session?.user?.id) redirect(`/${locale}/auth/sign-in`);

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) notFound();

  const db = getTenantDb(tenant.id);
  const payments = await db.paymentTransaction.findMany({
    include: {
      booking: {
        include: {
          customerProfile: {
            include: {user: {select: {firstName: true, lastName: true, email: true}}}
          }
        }
      }
    },
    orderBy: {createdAt: "desc"}
  });

  const statusColors: Record<string, string> = {
    PENDING: "bg-yellow-100 text-yellow-700",
    AUTHORIZED: "bg-blue-100 text-blue-700",
    PAID: "bg-green-100 text-green-700",
    PARTIALLY_REFUNDED: "bg-orange-100 text-orange-700",
    REFUNDED: "bg-slate-100 text-slate-600",
    FAILED: "bg-red-100 text-red-700",
    VOIDED: "bg-gray-100 text-gray-500"
  };

  const totalRevenue = payments
    .filter((p) => p.status === "PAID")
    .reduce((sum, p) => sum + Number(p.amount), 0);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Payments</h1>
          <p className="mt-1 text-slate-500">{payments.length} transactions</p>
        </div>
        <div className="rounded-xl border border-green-200 bg-green-50 px-4 py-3 text-right">
          <p className="text-xs font-medium text-green-600 uppercase">Total Collected</p>
          <p className="text-xl font-bold text-green-700">
            {tenant.currency} {totalRevenue.toFixed(2)}
          </p>
        </div>
      </div>

      <div className="rounded-2xl border border-blue-100 bg-blue-50 p-4">
        <p className="mb-3 text-sm font-medium text-blue-800">Register a Manual Payment</p>
        <RegisterPaymentForm
          tenantId={tenant.id}
          tenantSlug={tenantSlug}
          currency={tenant.currency}
          outstanding={0}
        />
      </div>

      <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead>
            <tr className="border-b border-slate-200">
              <th className="px-3 py-3 text-left font-semibold">Booking #</th>
              <th className="px-3 py-3 text-left font-semibold">Customer</th>
              <th className="px-3 py-3 text-left font-semibold">Method</th>
              <th className="px-3 py-3 text-left font-semibold">Reference</th>
              <th className="px-3 py-3 text-left font-semibold">Amount</th>
              <th className="px-3 py-3 text-left font-semibold">Status</th>
              <th className="px-3 py-3 text-left font-semibold">Paid At</th>
            </tr>
          </thead>
          <tbody>
            {payments.map((pmt) => {
              const user = pmt.booking?.customerProfile.user;
              const customerName = user
                ? user.firstName
                  ? `${user.firstName} ${user.lastName ?? ""}`.trim()
                  : user.email
                : "—";
              return (
                <tr key={pmt.id} className="border-b border-slate-100 hover:bg-slate-50">
                  <td className="px-3 py-3 font-mono text-xs">{pmt.booking?.bookingNumber ?? "—"}</td>
                  <td className="px-3 py-3">{customerName}</td>
                  <td className="px-3 py-3">{pmt.method.replace(/_/g, " ")}</td>
                  <td className="px-3 py-3 font-mono text-xs text-slate-500">{pmt.providerReference ?? "—"}</td>
                  <td className="px-3 py-3 font-semibold">{pmt.currency} {Number(pmt.amount).toFixed(2)}</td>
                  <td className="px-3 py-3">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${statusColors[pmt.status] ?? "bg-slate-100"}`}>
                      {pmt.status.replace(/_/g, " ")}
                    </span>
                  </td>
                  <td className="px-3 py-3">{pmt.paidAt ? new Date(pmt.paidAt).toLocaleDateString() : "—"}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
