import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatPaise, formatDate } from "@/lib/format";
import { parseDateRange, dateRangeWhere } from "@/lib/reports";
import ReportsTabs from "@/components/admin/ReportsTabs";
import StatusBadge from "@/components/admin/StatusBadge";
import ScrollableTable from "@/components/admin/ScrollableTable";

const STATUSES = ["pending", "paid", "failed", "shipped", "delivered", "cancelled"];

export default async function AdminOrderReportPage({
  searchParams,
}: {
  searchParams: Promise<{ from?: string; to?: string; status?: string }>;
}) {
  const params = await searchParams;
  const range = parseDateRange(params);
  const createdAt = dateRangeWhere(range);
  const status = params.status ?? "";

  const orders = await prisma.order.findMany({
    where: { ...(createdAt ? { createdAt } : {}), ...(status ? { status } : {}) },
    orderBy: { createdAt: "desc" },
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Order Report</h1>
      <p className="mt-1 text-sm text-stone-500">Every order, any status, with the full price breakdown. Leave dates blank for all-time.</p>

      <ReportsTabs active="/iv-manage-84x2/reports/orders" />

      <form action="/iv-manage-84x2/reports/orders" className="mb-6 flex flex-wrap items-end gap-3 rounded-lg border border-rose-100 bg-white p-3">
        <label className="text-xs text-stone-500">
          From
          <input type="date" name="from" defaultValue={range.fromStr} className="mt-1 block rounded-md border border-stone-300 px-2 py-1.5 text-sm" />
        </label>
        <label className="text-xs text-stone-500">
          To
          <input type="date" name="to" defaultValue={range.toStr} className="mt-1 block rounded-md border border-stone-300 px-2 py-1.5 text-sm" />
        </label>
        <label className="text-xs text-stone-500">
          Status
          <select name="status" defaultValue={status} className="mt-1 block rounded-md border border-stone-300 px-2 py-1.5 text-sm">
            <option value="">All</option>
            {STATUSES.map((s) => (
              <option key={s} value={s}>{s}</option>
            ))}
          </select>
        </label>
        <button type="submit" className="rounded-md bg-rose-700 px-4 py-1.5 text-sm font-semibold text-white hover:bg-rose-800">
          Filter
        </button>
        {(range.fromStr || range.toStr || status) && (
          <a href="/iv-manage-84x2/reports/orders" className="text-xs text-stone-400 hover:text-rose-700">
            Clear filters
          </a>
        )}
      </form>

      {orders.length === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">No orders match this filter.</p>
      ) : (
        <ScrollableTable>
          <table className="w-full min-w-[900px] text-sm">
            <thead className="sticky top-0 z-10 bg-rose-50 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">Subtotal</th>
                <th className="p-3">Discount</th>
                <th className="p-3">Shipping</th>
                <th className="p-3">Total</th>
                <th className="p-3">Status</th>
                <th className="p-3">Date</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {orders.map((o) => (
                <tr key={o.id}>
                  <td className="whitespace-nowrap p-3">
                    <Link href={`/iv-manage-84x2/orders/${o.id}`} className="font-medium text-rose-700 hover:underline">
                      {o.orderNumber}
                    </Link>
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{o.customerName}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{formatPaise(o.subtotal)}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{o.discountAmount > 0 ? `−${formatPaise(o.discountAmount)}` : "—"}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{formatPaise(o.shippingFee)}</td>
                  <td className="whitespace-nowrap p-3 font-medium text-stone-800">{formatPaise(o.total)}</td>
                  <td className="whitespace-nowrap p-3"><StatusBadge status={o.status} /></td>
                  <td className="whitespace-nowrap p-3 text-stone-500">{formatDate(o.createdAt)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </ScrollableTable>
      )}
    </div>
  );
}
