import { prisma } from "@/lib/prisma";
import { formatPrice } from "@/lib/utils";
import AdminOrderActions from "@/components/admin/AdminOrderActions";
import AdminCJSyncButton from "@/components/admin/AdminCJSyncButton";
import { AlertTriangle, ExternalLink } from "lucide-react";

export const dynamic = "force-dynamic";

const CJ_BADGE: Record<string, string> = {
  PLACED: "bg-blue-100 text-blue-700",
  SHIPPED: "bg-purple-100 text-purple-700",
  DELIVERED: "bg-green-100 text-green-700",
  FAILED: "bg-red-100 text-red-700",
  ADDRESS_INCOMPLETE: "bg-red-100 text-red-700",
  NOT_CONFIGURED: "bg-amber-100 text-amber-700",
};

export default async function AdminOrdersPage() {
  const orders = await prisma.order.findMany({
    orderBy: { createdAt: "desc" },
    include: { items: { include: { product: { select: { name: true, cjVariantId: true } } } } },
  });

  const failedCount = orders.filter(
    (o: (typeof orders)[0]) =>
      !o.cjOrderId && o.cjStatus && ["FAILED", "ADDRESS_INCOMPLETE", "NOT_CONFIGURED"].includes(o.cjStatus)
  ).length;

  return (
    <div className="p-8">
      <div className="flex items-start justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Orders</h1>
          <p className="text-gray-500 mt-1">{orders.length} total orders</p>
        </div>
        <AdminCJSyncButton />
      </div>

      {failedCount > 0 && (
        <div className="flex items-start gap-3 bg-red-50 border border-red-100 text-red-700 rounded-xl p-4 mb-6">
          <AlertTriangle className="h-5 w-5 shrink-0 mt-0.5" />
          <div className="text-sm">
            <p className="font-semibold">{failedCount} order(s) did not reach CJ Dropshipping.</p>
            <p className="text-red-600/80 mt-0.5">
              Hover the CJ column for the exact error, fix the cause, then use &ldquo;Retry failed&rdquo;.
            </p>
          </div>
        </div>
      )}

      <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-gray-100 bg-gray-50">
                <th className="text-left px-6 py-4 font-semibold text-gray-600">Order ID</th>
                <th className="text-left px-6 py-4 font-semibold text-gray-600">Customer</th>
                <th className="text-left px-6 py-4 font-semibold text-gray-600">Items</th>
                <th className="text-right px-6 py-4 font-semibold text-gray-600">Total</th>
                <th className="text-center px-6 py-4 font-semibold text-gray-600">Status</th>
                <th className="text-left px-6 py-4 font-semibold text-gray-600">CJ / Tracking</th>
                <th className="text-left px-6 py-4 font-semibold text-gray-600">Date</th>
                <th className="text-right px-6 py-4 font-semibold text-gray-600">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {orders.map((order: (typeof orders)[0]) => {
                const cjItemCount = order.items.filter(
                  (i: (typeof order.items)[0]) => i.product.cjVariantId
                ).length;

                return (
                  <tr key={order.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-6 py-4 font-mono text-xs text-gray-500">{order.id.slice(0, 8)}...</td>
                    <td className="px-6 py-4">
                      <div className="font-medium text-gray-900">{order.email}</div>
                      <div className="text-xs text-gray-400 mt-0.5 max-w-xs truncate">
                        {[order.shippingName, order.shippingAddress, order.shippingCity, order.shippingState, order.shippingZip]
                          .filter(Boolean)
                          .join(", ")}
                      </div>
                    </td>
                    <td className="px-6 py-4 text-gray-500">
                      {order.items.length} item(s)
                      {cjItemCount > 0 && (
                        <span className="block text-[11px] text-gray-400">{cjItemCount} via CJ</span>
                      )}
                    </td>
                    <td className="px-6 py-4 text-right font-bold text-gray-900">{formatPrice(order.total)}</td>
                    <td className="px-6 py-4 text-center">
                      <span className={`text-xs font-semibold px-2.5 py-1 rounded-full ${
                        order.status === "DELIVERED" ? "bg-green-100 text-green-700"
                        : order.status === "SHIPPED" ? "bg-blue-100 text-blue-700"
                        : order.status === "PROCESSING" ? "bg-amber-100 text-amber-700"
                        : order.status === "CANCELLED" ? "bg-red-100 text-red-700"
                        : "bg-gray-100 text-gray-600"
                      }`}>
                        {order.status}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      {order.cjStatus ? (
                        <span
                          className={`text-xs font-semibold px-2.5 py-1 rounded-full ${
                            CJ_BADGE[order.cjStatus] ?? "bg-gray-100 text-gray-600"
                          }`}
                          title={order.cjError ?? order.cjOrderId ?? undefined}
                        >
                          {order.cjStatus}
                        </span>
                      ) : cjItemCount > 0 ? (
                        <span className="text-xs text-gray-400">Not sent</span>
                      ) : (
                        <span className="text-xs text-gray-300">Manual</span>
                      )}

                      {order.trackingNumber && (
                        <a
                          href={order.trackingUrl ?? `https://t.17track.net/en#nums=${order.trackingNumber}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="flex items-center gap-1 text-[11px] font-mono text-primary-600 hover:underline mt-1"
                        >
                          {order.trackingNumber}
                          <ExternalLink className="h-3 w-3" />
                        </a>
                      )}
                      {order.carrier && (
                        <div className="text-[11px] text-gray-400">{order.carrier}</div>
                      )}
                      {order.cjError && (
                        <div className="text-[11px] text-red-500 mt-1 max-w-[200px] truncate" title={order.cjError}>
                          {order.cjError}
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4 text-gray-500 text-xs">{new Date(order.createdAt).toLocaleDateString()}</td>
                    <td className="px-6 py-4">
                      <AdminOrderActions orderId={order.id} currentStatus={order.status} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {orders.length === 0 && (
            <div className="text-center py-12 text-gray-400">No orders yet.</div>
          )}
        </div>
      </div>
    </div>
  );
}
