import { Metadata } from "next";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import Link from "next/link";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { serialize } from "@/lib/serialize";
import { Package, ShoppingBag, Users, TrendingUp, Eye, Clock, CheckCircle2, XCircle } from "lucide-react";
import { formatPrice } from "@/lib/utils";

export const metadata: Metadata = { title: "Admin Dashboard" };

export default async function AdminDashboard() {
  const session = await getServerSession(authOptions);
  if (!session || !["ADMIN","SUPER_ADMIN"].includes(session.user?.role || "")) redirect("/");

  const [totalProducts, totalOrders, totalUsers, recentOrders, revenue, pendingOrders] = await Promise.all([
    prisma.product.count({ where: { status: "ACTIVE" } }),
    prisma.order.count(),
    prisma.user.count({ where: { role: "CUSTOMER" } }),
    prisma.order.findMany({ orderBy: { createdAt: "desc" }, take: 8, include: { user: { select: { name: true, email: true } }, items: { select: { quantity: true } } } }),
    prisma.order.aggregate({ _sum: { total: true }, where: { paymentStatus: "PAID" } }),
    prisma.order.count({ where: { status: "PENDING" } }),
  ]);

  const orders = serialize(recentOrders) as unknown as Array<{ id: string; orderNumber: string; status: string; total: number; createdAt: string; user: { name?: string; email: string }; items: { quantity: number }[] }>;
  const totalRevenue = revenue._sum.total ? parseFloat(revenue._sum.total.toString()) : 0;

  const statCards = [
    { label: "Total Products", value: totalProducts, icon: Package, color: "text-sky-600", bg: "bg-sky-50", href: "/admin/products" },
    { label: "Total Orders", value: totalOrders, icon: ShoppingBag, color: "text-purple-600", bg: "bg-purple-50", href: "/admin/orders" },
    { label: "Customers", value: totalUsers, icon: Users, color: "text-emerald-600", bg: "bg-emerald-50", href: "/admin/users" },
    { label: "Revenue (Paid)", value: formatPrice(totalRevenue), icon: TrendingUp, color: "text-amber-600", bg: "bg-amber-50", href: "/admin/orders" },
  ];

  const statusIcon = (s: string) => s === "DELIVERED" ? <CheckCircle2 className="w-4 h-4 text-emerald-500" /> : s === "CANCELLED" ? <XCircle className="w-4 h-4 text-red-500" /> : <Clock className="w-4 h-4 text-amber-500" />;
  const statusColor: 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" };

  return (
    <div className="max-w-7xl mx-auto">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-black text-slate-900">Admin Dashboard</h1>
          <p className="text-slate-500 text-sm mt-1">Welcome back, {session.user?.name}</p>
        </div>
        <div className="flex gap-3">
          <Link href="/admin/products/new" className="bg-sky-500 text-white px-4 py-2 rounded-xl font-bold text-sm hover:bg-sky-600 transition-colors">+ Add Product</Link>
          <Link href="/" className="border border-slate-200 text-slate-600 px-4 py-2 rounded-xl font-bold text-sm hover:bg-slate-50 transition-colors flex items-center gap-2">
            <Eye className="w-4 h-4" /> View Store
          </Link>
        </div>
      </div>

      {/* Stat cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {statCards.map(({ label, value, icon: Icon, color, bg, href }) => (
          <Link key={label} href={href} className="bg-white rounded-2xl border border-slate-100 p-5 hover:border-sky-200 hover:shadow-md transition-all">
            <div className="flex items-center justify-between mb-3">
              <div className={`w-10 h-10 rounded-xl ${bg} flex items-center justify-center`}>
                <Icon className={`w-5 h-5 ${color}`} />
              </div>
            </div>
            <p className="text-2xl font-black text-slate-900">{value}</p>
            <p className="text-slate-500 text-sm mt-1">{label}</p>
          </Link>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Recent Orders */}
        <div className="lg:col-span-2 bg-white rounded-2xl border border-slate-100 overflow-hidden">
          <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
            <h2 className="font-black text-slate-800">Recent Orders</h2>
            <Link href="/admin/orders" className="text-sky-600 text-sm font-medium hover:text-sky-700">View All</Link>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-slate-50">
                <tr>
                  {["Order #","Customer","Items","Total","Status"].map((h) => (
                    <th key={h} className="px-4 py-3 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">{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">
                      <Link href={`/admin/orders`} className="text-sky-600 font-bold text-sm hover:underline">#{order.orderNumber}</Link>
                    </td>
                    <td className="px-4 py-3">
                      <p className="text-sm font-medium text-slate-800">{order.user.name || "—"}</p>
                      <p className="text-xs text-slate-500 truncate max-w-28">{order.user.email}</p>
                    </td>
                    <td className="px-4 py-3 text-sm text-slate-600">{order.items.reduce((s,i) => s + i.quantity, 0)}</td>
                    <td className="px-4 py-3 text-sm font-bold text-slate-800">{formatPrice(order.total)}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-full ${statusColor[order.status] || "bg-slate-100 text-slate-600"}`}>
                        {statusIcon(order.status)} {order.status}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Quick actions */}
        <div className="space-y-4">
          <div className="bg-white rounded-2xl border border-slate-100 p-5">
            <h2 className="font-black text-slate-800 mb-4">Quick Actions</h2>
            <div className="space-y-3">
              {[
                { label: "Add New Product", href: "/admin/products/new", color: "bg-sky-500 text-white" },
                { label: "Manage Products", href: "/admin/products", color: "bg-slate-100 text-slate-700" },
                { label: "View All Orders", href: "/admin/orders", color: "bg-slate-100 text-slate-700" },
                { label: "Manage Users", href: "/admin/users", color: "bg-slate-100 text-slate-700" },
              ].map(({ label, href, color }) => (
                <Link key={label} href={href} className={`block px-4 py-3 rounded-xl text-sm font-bold text-center transition-colors hover:opacity-90 ${color}`}>{label}</Link>
              ))}
            </div>
          </div>

          <div className="bg-amber-50 rounded-2xl border border-amber-100 p-5">
            <div className="flex items-center gap-2 mb-2">
              <Clock className="w-5 h-5 text-amber-600" />
              <h3 className="font-bold text-amber-800">Pending Orders</h3>
            </div>
            <p className="text-3xl font-black text-amber-600">{pendingOrders}</p>
            <p className="text-amber-600 text-sm mt-1">orders need attention</p>
            <Link href="/admin/orders?status=PENDING" className="mt-3 block text-center bg-amber-500 text-white py-2 rounded-xl text-sm font-bold hover:bg-amber-600 transition-colors">
              Process Now
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
