import { notFound } from "next/navigation";
import { ChevronDown } from "lucide-react";
import { AdminStatusBadge } from "@/components/admin/AdminPresentation";
import { DataTable } from "@/components/admin/DataTable";
import { updateOrderStatus } from "@/lib/order-actions";
import { prisma } from "@/lib/prisma";
import { currency } from "@/lib/utils";

const paymentStatuses = [
  ["PENDING", "Pending"],
  ["PAID", "Paid"],
  ["FAILED", "Failed"],
  ["REFUNDED", "Refunded"]
];
const fulfillmentStatuses = [
  ["NEW", "New"],
  ["PROCESSING", "Processing"],
  ["SHIPPED", "Shipped"],
  ["COMPLETED", "Completed"],
  ["CANCELLED", "Cancelled"]
];

const selectClassName = "w-full cursor-pointer appearance-none rounded border border-[#D8C98F] bg-white px-3 py-2 pr-11 font-bold text-[#171717] shadow-sm transition hover:border-[#B9922F] focus:border-[#B9922F] focus:outline-none focus:ring-2 focus:ring-[#D8C98F]";

function formatDate(date: Date) {
  return new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeStyle: "short" }).format(date);
}

function safePaymentNote(rawResponse?: string | null) {
  if (!rawResponse) return null;

  try {
    const parsed = JSON.parse(rawResponse) as {
      error?: {
        errors?: Array<{ code?: string; category?: string; detail?: string; field?: string }>;
      };
      payment?: { id?: string; status?: string; receiptNumber?: string };
    };
    const firstError = parsed.error?.errors?.[0];
    if (firstError?.code) {
      return [firstError.code, firstError.category, firstError.field].filter(Boolean).join(" / ");
    }
    if (parsed.payment?.id) {
      return `Square payment ${parsed.payment.status || "recorded"}${parsed.payment.receiptNumber ? ` / receipt ${parsed.payment.receiptNumber}` : ""}`;
    }
  } catch {
    return null;
  }

  return null;
}

export default async function AdminOrderDetailPage({ params }: { params: { id: string } }) {
  const order = await prisma.order.findUnique({
    where: { id: params.id },
    include: {
      items: { include: { product: { include: { supplier: true } } } },
      paymentLogs: { orderBy: { createdAt: "desc" } }
    }
  });
  if (!order) notFound();
  const updateOrder = updateOrderStatus.bind(null, order.id);
  return (
    <section>
      <h1 className="font-heading text-3xl font-black">{order.orderNumber}</h1>
      <div className="mt-5 grid gap-4 md:grid-cols-3">
        <div className="panel p-4"><div className="text-[#666]">Customer</div><strong>{order.customerName}</strong><p>{order.customerEmail}</p><p>{order.customerPhone}</p></div>
        <div className="panel p-4"><div className="text-[#666]">Payment</div><strong>{order.paymentStatus}</strong><p>{order.paymentMethod}</p></div>
        <div className="panel p-4"><div className="text-[#666]">Fulfillment</div><strong>{order.fulfillmentStatus}</strong><p>{order.trackingNumber || "No tracking yet"}</p></div>
      </div>
      <div className="panel mt-5 p-4">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <h2 className="text-xl font-black">Payment Activity</h2>
            <p className="mt-1 text-sm text-[#666]">Provider status and payment log summary for this order.</p>
          </div>
          <AdminStatusBadge value={order.paymentStatus} />
        </div>
        {order.paymentLogs.length ? (
          <div className="mt-4 grid gap-3">
            {order.paymentLogs.map((log) => {
              const note = safePaymentNote(log.rawResponse);
              return (
                <div key={log.id} className="grid gap-3 rounded border border-[#E5E1D8] bg-[#F7F5EF] p-3 text-sm md:grid-cols-[1fr_auto] md:items-center">
                  <div>
                    <div className="flex flex-wrap items-center gap-2">
                      <strong>{log.provider}</strong>
                      <AdminStatusBadge value={log.status} />
                      <span className="text-[#666]">{currency(String(log.amount))} {log.currency}</span>
                    </div>
                    {note ? <p className="mt-1 text-xs text-[#666]">{note}</p> : null}
                  </div>
                  <div className="text-xs font-bold uppercase text-[#666]">{formatDate(log.createdAt)}</div>
                </div>
              );
            })}
          </div>
        ) : (
          <p className="mt-4 rounded border border-[#E5E1D8] bg-[#F7F5EF] p-3 text-sm text-[#666]">No payment log has been recorded for this order yet.</p>
        )}
      </div>
      <div className="mt-6">
        <DataTable
          headers={["Product", "Supplier Internal", "Qty", "Supplier Price", "Sale Price", "Markup"]}
          rows={order.items.map((item) => [
            item.productNameSnapshot || item.product?.name || "Product snapshot unavailable",
            item.product?.supplier?.name || "Supplier unavailable",
            item.quantity,
            currency(String(item.supplierPriceSnapshot)),
            currency(String(item.totalSalePriceSnapshot)),
            currency((Number(item.totalSalePriceSnapshot) - Number(item.supplierPriceSnapshot)) * item.quantity)
          ])}
        />
      </div>
      <form action={updateOrder} className="panel mt-5 grid gap-4 p-4 md:grid-cols-2">
        <h2 className="text-xl font-black md:col-span-2">Order Controls</h2>
        <label>
          Payment Status
          <span className="relative mt-1 block">
            <select name="paymentStatus" defaultValue={order.paymentStatus} className={selectClassName}>
              {paymentStatuses.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
            </select>
            <ChevronDown className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-[#7A5310]" size={18} />
          </span>
        </label>
        <label>
          Fulfillment Status
          <span className="relative mt-1 block">
            <select name="fulfillmentStatus" defaultValue={order.fulfillmentStatus} className={selectClassName}>
              {fulfillmentStatuses.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
            </select>
            <ChevronDown className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-[#7A5310]" size={18} />
          </span>
        </label>
        <label className="md:col-span-2">
          Tracking Number
          <input name="trackingNumber" defaultValue={order.trackingNumber || ""} />
        </label>
        <label className="md:col-span-2">
          Admin Notes
          <textarea name="adminNotes" defaultValue={order.adminNotes || ""} />
        </label>
        <button className="btn btn-primary w-fit">Save Order Updates</button>
      </form>
    </section>
  );
}
