import { prisma } from "@/lib/prisma";
import { requireCrmAdmin } from "@/lib/crm/admin-access";
import CustomerAdminShell from "../CustomerAdminShell";
import {
  createPayment,
  verifyPayment,
  updatePendingPaymentStatus,
  refundVerifiedPayment,
} from "./actions";

export const dynamic = "force-dynamic";

export default async function PaymentsPage() {
  await requireCrmAdmin();

  const [payments, invoices] = await Promise.all([
    prisma.payment.findMany({
      orderBy: { createdAt: "desc" },
      take: 100,
      select: {
        paymentCode: true,
        amount: true,
        method: true,
        status: true,
        transactionRef: true,
        invoice: {
          select: { invoiceNumber: true },
        },
        client: {
          select: { name: true },
        },
      },
    }),
    prisma.invoice.findMany({
      where: {
        status: {
          in: ["ISSUED", "PARTIALLY_PAID", "OVERDUE"],
        },
      },
      orderBy: { createdAt: "desc" },
      take: 500,
      select: {
        id: true,
        invoiceNumber: true,
        totalAmount: true,
        amountPaid: true,
        client: { select: { name: true } },
          payments: {
            where: { status: "PENDING" },
            select: { amount: true },
          },
      },
    }),
  ]);

  return (
    <CustomerAdminShell>
      <main className="mx-auto max-w-6xl space-y-8 px-5 py-8">
        <h1 className="text-3xl font-bold">Payment Management</h1>

        <section className="rounded-2xl border bg-white p-6">
          <h2 className="mb-4 text-xl font-bold">Record Payment</h2>

          <p className="mb-4 text-sm text-slate-500">
            New payments remain PENDING until verified.
          </p>

          <form action={createPayment} className="grid gap-4">
            <select
              name="invoiceId"
              required
              defaultValue=""
              className="rounded-xl border p-3"
            >
              <option value="" disabled>Select Invoice</option>
              {invoices.map((invoice) => (
                <option key={invoice.id} value={invoice.id}>
                  {invoice.invoiceNumber} — {invoice.client.name}
                  {" — "}Available ₹
                    {invoice.payments
                      .reduce(
                        (balance, payment) =>
                          balance.sub(payment.amount),
                        invoice.totalAmount.sub(invoice.amountPaid),
                      )
                      .toString()}
                </option>
              ))}
            </select>

            <input
              name="amount"
              required
              inputMode="decimal"
              placeholder="Payment Amount"
              className="rounded-xl border p-3"
            />

            <select
              name="method"
              required
              defaultValue="BANK_TRANSFER"
              className="rounded-xl border p-3"
            >
              <option value="BANK_TRANSFER">Bank Transfer</option>
              <option value="UPI">UPI</option>
              <option value="CASH">Cash</option>
              <option value="CHEQUE">Cheque</option>
              <option value="CARD">Card</option>
              <option value="PAYMENT_GATEWAY">Payment Gateway</option>
              <option value="OTHER">Other</option>
            </select>

            <input
              name="transactionRef"
              maxLength={191}
              placeholder="Transaction Reference"
              className="rounded-xl border p-3"
            />

            <button
              type="submit"
              className="rounded-xl bg-blue-600 p-3 font-bold text-white"
            >
              Record Pending Payment
            </button>
          </form>
        </section>

        <section className="space-y-4">
          <h2 className="text-xl font-bold">Payments</h2>

          {payments.length === 0 && (
            <p className="rounded-xl border bg-white p-5">
              No payments recorded yet.
            </p>
          )}

          {payments.map((payment) => (
            <article
              key={payment.paymentCode}
              className="rounded-2xl border bg-white p-5"
            >
              <h3 className="font-bold">{payment.paymentCode}</h3>
              <p className="mt-2 text-sm">
                {payment.client.name} ·
                {payment.invoice?.invoiceNumber ?? "No Invoice"}
              </p>
              <p className="mt-1 text-sm">
                ₹{payment.amount.toString()} · {payment.method} ·
                {payment.status}
              </p>

              {payment.transactionRef && (
                <p className="mt-1 text-xs text-slate-500">
                  Reference: {payment.transactionRef}
                </p>
              )}

              {/* PAYMENT_UI_LIFECYCLE_STEP174 */}
              {payment.status === "PENDING" && (
                <div className="mt-3 flex flex-wrap gap-2">
                  <form action={updatePendingPaymentStatus}>
                    <input
                      type="hidden"
                      name="paymentCode"
                      value={payment.paymentCode}
                    />
                    <input
                      type="hidden"
                      name="status"
                      value="FAILED"
                    />
                    <button
                      type="submit"
                      className="rounded border px-3 py-2 text-sm font-semibold"
                    >
                      Mark Failed
                    </button>
                  </form>

                  <form action={updatePendingPaymentStatus}>
                    <input
                      type="hidden"
                      name="paymentCode"
                      value={payment.paymentCode}
                    />
                    <input
                      type="hidden"
                      name="status"
                      value="CANCELLED"
                    />
                    <button
                      type="submit"
                      className="rounded border px-3 py-2 text-sm font-semibold"
                    >
                      Cancel Payment
                    </button>
                  </form>
                </div>
              )}

              {payment.status === "VERIFIED" &&
                payment.invoice && (
                  <form
                    action={refundVerifiedPayment}
                    className="mt-3"
                  >
                    <input
                      type="hidden"
                      name="paymentCode"
                      value={payment.paymentCode}
                    />
                    <button
                      type="submit"
                      className="rounded border px-3 py-2 text-sm font-semibold"
                    >
                      Refund Payment
                    </button>
                  </form>
                )}

              {payment.status === "PENDING" && payment.invoice && (
                <form action={verifyPayment} className="mt-4">
                  <input
                    type="hidden"
                    name="paymentCode"
                    value={payment.paymentCode}
                  />
                  <button
                    type="submit"
                    className="rounded-xl bg-green-700 px-5 py-2 text-sm font-bold text-white"
                  >
                    Verify Payment
                  </button>
                </form>
              )}
            </article>
          ))}
        </section>
      </main>
    </CustomerAdminShell>
  );
}
