import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, Package, ShoppingBag, Truck, ExternalLink } from "lucide-react";
import { formatPrice } from "@/lib/utils";

export const metadata = { title: "My Orders" };
export const dynamic = "force-dynamic";

export default async function MyOrdersPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user?.email) redirect("/auth/login?next=/account/orders");

  const orders = await prisma.order.findMany({
    where: { email: session.user.email },
    orderBy: { createdAt: "desc" },
    include: {
      items: {
        include: { product: { select: { name: true, images: true } } },
      },
    },
  });

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

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto px-4 py-12">
        <div className="flex items-center gap-4 mb-8">
          <Link href="/" className="p-2 hover:bg-gray-200 rounded-xl transition-colors">
            <ArrowLeft className="h-5 w-5 text-gray-600" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">My Orders</h1>
            <p className="text-gray-500 text-sm mt-0.5">{orders.length} order{orders.length !== 1 ? "s" : ""}</p>
          </div>
        </div>

        {orders.length === 0 ? (
          <div className="bg-white rounded-2xl shadow-sm p-12 text-center">
            <ShoppingBag className="h-12 w-12 text-gray-300 mx-auto mb-4" />
            <h2 className="text-lg font-semibold text-gray-700 mb-2">No orders yet</h2>
            <p className="text-gray-400 mb-6">Start shopping to see your orders here.</p>
            <Link href="/shop" className="btn-primary">Shop Now</Link>
          </div>
        ) : (
          <div className="space-y-5">
            {orders.map((order: (typeof orders)[0]) => (
              <div key={order.id} className="bg-white rounded-2xl shadow-sm overflow-hidden">
                <div className="flex items-center justify-between p-6 border-b border-gray-100">
                  <div>
                    <p className="text-xs text-gray-400 mb-0.5">Order #{order.id.slice(-8).toUpperCase()}</p>
                    <p className="text-sm text-gray-500">{new Date(order.createdAt).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" })}</p>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className="text-lg font-bold text-gray-900">{formatPrice(order.total)}</span>
                    <span className={`text-xs font-semibold px-3 py-1.5 rounded-full ${statusColor[order.status] ?? "bg-gray-100 text-gray-600"}`}>
                      {order.status}
                    </span>
                  </div>
                </div>

                {order.trackingNumber && (
                  <div className="flex items-center gap-3 px-6 py-4 bg-primary-50/60 border-b border-primary-100">
                    <Truck className="h-5 w-5 text-primary-600 shrink-0" />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-gray-900">
                        On its way{order.carrier ? ` with ${order.carrier}` : ""}
                      </p>
                      <p className="text-xs text-gray-500 font-mono truncate">{order.trackingNumber}</p>
                    </div>
                    <a
                      href={order.trackingUrl ?? `https://t.17track.net/en#nums=${order.trackingNumber}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="btn-outline text-xs px-3 py-2 shrink-0"
                    >
                      Track
                      <ExternalLink className="h-3 w-3" />
                    </a>
                  </div>
                )}

                <div className="divide-y divide-gray-50">
                  {order.items.map((item: (typeof order.items)[0]) => (
                    <div key={item.id} className="flex items-center gap-4 px-6 py-4">
                      <div className="w-10 h-10 rounded-xl bg-gray-100 flex items-center justify-center shrink-0">
                        <Package className="h-5 w-5 text-gray-400" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-gray-900 truncate">{item.product.name}</p>
                        <p className="text-xs text-gray-400">Qty: {item.quantity}</p>
                      </div>
                      <p className="font-semibold text-gray-700 shrink-0">{formatPrice(item.price * item.quantity)}</p>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
