// app/orders/page.tsx
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { Download, CheckCircle2, FileArchive, Package, ArrowLeft } from "lucide-react";
import Image from "next/image";
import Link from "next/link";

export const dynamic = "force-dynamic";

export default async function OrdersPage() {
  const session = await getServerSession(authOptions);

  if (!session?.user) {
    redirect("/");
  }

  const userId = (session.user as any).id;

  const orders = await prisma.order.findMany({
    where: {
      userId: userId,
      status: "COMPLETED",
    },
    include: {
      items: {
        include: {
          product: true,
        },
      },
    },
    orderBy: { createdAt: "desc" },
  });

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100 py-12 px-4 sm:px-6 max-w-5xl mx-auto space-y-8">
      <div className="flex items-center justify-between border-b border-zinc-800/80 pb-6">
        <div>
          <Link href="/" className="text-xs text-zinc-400 hover:text-white flex items-center gap-1 mb-2">
            <ArrowLeft className="h-3.5 w-3.5" /> Back to Store
          </Link>
          <h1 className="text-3xl font-black text-white tracking-tight">My Purchases & Downloads</h1>
          <p className="text-xs text-zinc-400 mt-1">Download your full ZIP bundles with source vector templates anytime.</p>
        </div>
        <div className="px-4 py-2 rounded-2xl bg-zinc-900 border border-zinc-800 text-xs font-semibold text-zinc-300">
          Total Completed Orders: <strong className="text-indigo-400">{orders.length}</strong>
        </div>
      </div>

      {orders.length === 0 ? (
        <div className="text-center py-20 bg-zinc-900/40 rounded-3xl border border-zinc-900 space-y-3">
          <Package className="h-12 w-12 text-zinc-600 mx-auto" />
          <h3 className="text-lg font-semibold text-white">No purchases found</h3>
          <p className="text-xs text-zinc-500">Your purchased templates will appear here with instant download links.</p>
          <Link
            href="/"
            className="inline-block mt-2 px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-xs font-semibold hover:bg-indigo-500 transition"
          >
            Browse Catalog
          </Link>
        </div>
      ) : (
        <div className="space-y-6">
          {orders.map((order) => (
            <div
              key={order.id}
              className="bg-zinc-900/60 border border-zinc-800 rounded-2xl p-6 space-y-5 shadow-lg"
            >
              {/* Order Header */}
              <div className="flex flex-wrap items-center justify-between gap-4 border-b border-zinc-800 pb-4 text-xs">
                <div>
                  <span className="text-zinc-500 block">Order ID</span>
                  <span className="font-mono font-bold text-zinc-200">{order.orderId || order.id}</span>
                </div>

                <div>
                  <span className="text-zinc-500 block">Date</span>
                  <span className="text-zinc-300 font-medium">
                    {new Date(order.createdAt).toLocaleDateString("en-IN", {
                      day: "numeric",
                      month: "short",
                      year: "numeric",
                    })}
                  </span>
                </div>

                <div>
                  <span className="text-zinc-500 block">Total Paid</span>
                  <span className="font-bold text-white text-sm">₹{Number(order.totalAmount).toFixed(2)}</span>
                </div>

                <div>
                  <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 font-semibold text-[11px]">
                    <CheckCircle2 className="h-3 w-3" /> Paid & Unlocked
                  </span>
                </div>
              </div>

              {/* Purchased Items & Download Links */}
              <div className="space-y-3">
                {order.items.map((item) => (
                  <div
                    key={item.id}
                    className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 p-4 rounded-xl bg-zinc-950 border border-zinc-800/80"
                  >
                    <div className="flex items-center gap-4">
                      <div className="relative h-16 w-20 rounded-lg overflow-hidden bg-zinc-900 flex-shrink-0 border border-zinc-800">
                        <Image
                          src={item.product.thumbnailUrl}
                          alt={item.product.title}
                          fill
                          className="object-cover"
                        />
                      </div>
                      <div>
                        <span className="text-[10px] font-bold text-indigo-400 uppercase tracking-wide">
                          {item.product.category}
                        </span>
                        <h4 className="text-sm font-semibold text-white line-clamp-1">
                          {item.product.title}
                        </h4>
                        <p className="text-xs text-zinc-500 mt-0.5">
                          Format: <strong className="text-zinc-300">.{item.product.fileType}</strong> • Size: {item.product.fileSize}
                        </p>
                      </div>
                    </div>

                    <a
                      href={`/api/download/${order.id}/${item.productId}`}
                      className="flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-bold transition shadow-md shadow-indigo-600/20 active:scale-95"
                    >
                      <Download className="h-4 w-4" /> Download ZIP Bundle
                    </a>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}