import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatPaise, formatDate } from "@/lib/format";
import { issueRefund, declineRefundRequest } from "@/lib/actions/payments";
import PaymentsTabs from "@/components/admin/PaymentsTabs";

export default async function AdminRefundsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;

  const [refundableOrders, refundedOrders, pendingRequests] = await Promise.all([
    prisma.order.findMany({
      where: { status: "paid", razorpayPaymentId: { not: null } },
      orderBy: { createdAt: "desc" },
    }),
    prisma.order.findMany({
      where: { refundedAmount: { gt: 0 } },
      orderBy: { refundedAt: "desc" },
    }),
    prisma.order.findMany({
      where: { refundRequestStatus: "pending" },
      orderBy: { refundRequestedAt: "desc" },
    }),
  ]);
  const stillRefundable = refundableOrders.filter((o) => o.refundedAmount < o.total);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Refunds</h1>
      <p className="mt-1 text-sm text-stone-500">
        Issues a real refund through Razorpay against the original payment — full or partial. Leave amount blank to refund whatever&apos;s left.
      </p>

      <PaymentsTabs active="/iv-manage-84x2/payments/refunds" />

      {error && <p className="mb-4 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      {pendingRequests.length > 0 && (
        <div className="mb-6 overflow-hidden rounded-lg border border-amber-200 bg-amber-50/60">
          <p className="border-b border-amber-200 p-3 text-sm font-semibold text-amber-900">Customer refund requests awaiting review</p>
          <div className="divide-y divide-amber-100">
            {pendingRequests.map((o) => (
              <div key={o.id} className="flex items-center justify-between gap-3 p-3 text-sm">
                <div>
                  <Link href={`/iv-manage-84x2/orders/${o.id}`} className="font-medium text-rose-700 hover:underline">
                    {o.orderNumber}
                  </Link>
                  <span className="ml-2 text-stone-500">{o.customerName}</span>
                  <p className="mt-1 text-xs text-stone-500">&ldquo;{o.refundRequestReason}&rdquo;</p>
                  <p className="text-xs text-stone-400">Requested {o.refundRequestedAt ? formatDate(o.refundRequestedAt) : ""}</p>
                </div>
                <form action={declineRefundRequest.bind(null, o.id)}>
                  <button type="submit" className="whitespace-nowrap text-xs text-stone-400 hover:text-red-700">
                    Decline
                  </button>
                </form>
              </div>
            ))}
          </div>
        </div>
      )}

      <form action={issueRefund} className="grid max-w-2xl grid-cols-1 gap-3 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-4">
        <select name="orderId" required className="rounded-md border border-stone-300 px-2 py-2 text-sm sm:col-span-2">
          <option value="">Select order…</option>
          {stillRefundable.map((o) => (
            <option key={o.id} value={o.id}>
              {o.orderNumber} — {o.customerName} ({formatPaise(o.total - o.refundedAmount)} refundable)
            </option>
          ))}
        </select>
        <input name="amount" type="number" min={0.01} step="0.01" placeholder="Amount ₹ (blank = full)" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <input name="reason" placeholder="Reason (optional)" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <button type="submit" className="col-span-1 rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800 sm:col-span-4">
          Issue refund
        </button>
      </form>
      {stillRefundable.length === 0 && (
        <p className="mt-2 text-xs text-stone-400">No paid orders are currently refundable.</p>
      )}

      <div className="mt-8 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {refundedOrders.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No refunds issued yet.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Order</th>
                <th className="p-3">Customer</th>
                <th className="p-3">Refunded</th>
                <th className="p-3">Reason</th>
                <th className="p-3">Date</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {refundedOrders.map((o) => (
                <tr key={o.id}>
                  <td className="p-3">
                    <Link href={`/iv-manage-84x2/orders/${o.id}`} className="font-medium text-rose-700 hover:underline">
                      {o.orderNumber}
                    </Link>
                  </td>
                  <td className="p-3 text-stone-600">{o.customerName}</td>
                  <td className="p-3 text-stone-600">
                    {formatPaise(o.refundedAmount)}
                    {o.refundedAmount >= o.total ? " (full)" : " (partial)"}
                  </td>
                  <td className="p-3 text-stone-500">{o.refundReason ?? "—"}</td>
                  <td className="p-3 text-stone-500">{o.refundedAt ? formatDate(o.refundedAt) : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
