import { Metadata } from "next";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { serialize } from "@/lib/serialize";
import { formatPrice, formatDate } from "@/lib/utils";
import { cn } from "@/lib/utils";
import AdminOrderStatus from "./AdminOrderStatus";

export const metadata: Metadata = { title: "Manage Orders" };

const statusColors: Record<string,string> = {
  PENDING:"bg-amber-100 text-amber-700", CONFIRMED:"bg-sky-100 text-sky-700",
  PROCESSING:"bg-blue-100 text-blue-700", SHIPPED:"bg-purple-100 text-purple-700",
  DELIVERED:"bg-emerald-100 text-emerald-700", CANCELLED:"bg-red-100 text-red-700",
};

export default async function AdminOrdersPage({ searchParams }: { searchParams: Promise<{ page?: string; status?: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session || !["ADMIN","SUPER_ADMIN"].includes(session.user?.role || "")) redirect("/");

  const params = await searchParams;
  const page = parseInt(params.page || "1");
  const limit = 15;
  const where = params.status ? { status: params.status as "PENDING"|"CONFIRMED"|"PROCESSING"|"SHIPPED"|"DELIVERED"|"CANCELLED"|"REFUNDED" } : {};

  const [rawOrders, total] = await Promise.all([
    prisma.order.findMany({ where, include: { user: { select: { name: true, email: true } }, items: { select: { quantity: true, name: true } } }, orderBy: { createdAt: "desc" }, skip: (page-1)*limit, take: limit }),
    prisma.order.count({ where }),
  ]);

  const orders = serialize(rawOrders) as unknown as Array<{ id: string; orderNumber: string; status: string; paymentStatus: string; total: number; createdAt: string; shippingName: string; shippingPhone: string; shippingCity: string; user: { name?: string; email: string }; items: { quantity: number; name: string }[] }>;
  const pages = Math.ceil(total / limit);

  return (
    <div className="max-w-7xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-black text-slate-900">Orders</h1>
          <p className="text-slate-500 text-sm">{total} orders total</p>
        </div>
      </div>

      {/* Status filters */}
      <div className="flex gap-2 flex-wrap mb-5">
        {[null, "PENDING","CONFIRMED","PROCESSING","SHIPPED","DELIVERED","CANCELLED"].map((s) => (
          <a key={s || "all"} href={s ? `?status=${s}` : "?"}
            className={cn("px-3 py-1.5 rounded-xl text-xs font-bold transition-colors", params.status === s || (!params.status && !s) ? "bg-sky-500 text-white" : "bg-white border border-slate-200 text-slate-600 hover:border-sky-300")}>
            {s || "All Orders"}
          </a>
        ))}
      </div>

      <div className="bg-white rounded-2xl border border-slate-100 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-slate-50 border-b border-slate-100">
              <tr>
                {["Order","Customer","Items","Total","Status","Payment","Date","Action"].map((h) => (
                  <th key={h} className="px-4 py-3 text-left text-xs font-bold text-slate-500 uppercase tracking-wider whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {orders.map((order) => (
                <tr key={order.id} className="hover:bg-slate-50 transition-colors">
                  <td className="px-4 py-3">
                    <p className="text-sm font-black text-slate-800">#{order.orderNumber}</p>
                    <p className="text-xs text-slate-500">{order.shippingCity}</p>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-sm font-medium text-slate-800">{order.shippingName}</p>
                    <p className="text-xs text-slate-500">{order.shippingPhone}</p>
                  </td>
                  <td className="px-4 py-3 text-sm text-slate-600">
                    {order.items.reduce((s, i) => s + i.quantity, 0)} items
                  </td>
                  <td className="px-4 py-3 text-sm font-black text-slate-800 whitespace-nowrap">{formatPrice(order.total)}</td>
                  <td className="px-4 py-3">
                    <span className={cn("text-xs font-bold px-2 py-1 rounded-full", statusColors[order.status] || "bg-slate-100 text-slate-600")}>{order.status}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={cn("text-xs font-bold px-2 py-1 rounded-full", order.paymentStatus === "PAID" ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700")}>{order.paymentStatus}</span>
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500 whitespace-nowrap">{formatDate(order.createdAt)}</td>
                  <td className="px-4 py-3">
                    <AdminOrderStatus orderId={order.id} currentStatus={order.status} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {orders.length === 0 && (
          <div className="text-center py-12 text-slate-400">
            <p className="font-medium">No orders found</p>
          </div>
        )}

        {pages > 1 && (
          <div className="flex justify-center gap-2 p-4 border-t border-slate-100">
            {Array.from({ length: pages }, (_, i) => i + 1).map((p) => (
              <a key={p} href={`?page=${p}${params.status ? `&status=${params.status}` : ""}`}
                className={`w-9 h-9 rounded-lg flex items-center justify-center text-sm font-bold ${p === page ? "bg-sky-500 text-white" : "border border-slate-200 text-slate-600"}`}>{p}</a>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
