import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { customerApi } from "@/lib/api/customer";
import { requireServerToken } from "@/lib/auth/server";
import { orNotFound } from "@/lib/api/notFound";
import type { ApiOrderDetail } from "@/lib/api/types";
import { formatCurrency, formatDateTime } from "@/lib/utils";
import AddressBlock from "@/components/orders/AddressBlock";
import OrderPriceBreakup, { OrderTerms } from "@/components/orders/OrderPriceBreakup";

type PageProps = {
  params: Promise<{ id: string }>;
};

const fmtINR = formatCurrency;

/** Not the caller's order → the 404 page; any other failure → the error boundary. */
function loadOrder(token: string, id: number): Promise<ApiOrderDetail> {
  return orNotFound(customerApi.order(token, id));
}

/**
 * Server-rendered detail view. The client version showed a `Loader` while an
 * effect fetched the order — a spinner that could not start until the bundle
 * had hydrated. Fetching during SSR removes both the spinner and the wait: the
 * first HTML response already carries the order.
 *
 * `params` is a promise in Next 15, so it is awaited rather than unwrapped with
 * `use()`; there is no Suspense boundary to fall back to on the server.
 */
export default async function OrderDetailPage({ params }: PageProps) {
  const { id } = await params;
  const token = await requireServerToken(`/orders/${id}`);

  const order = await loadOrder(token, Number(id));


  return (
    <div className="space-y-4">
      <Link href="/orders" className="inline-flex items-center gap-1 text-sm text-gray-600 hover:text-[#CC1414]">
        <ArrowLeft className="h-4 w-4" /> Back to orders
      </Link>

      <div className="rounded-xl bg-white p-6 shadow-sm ring-1 ring-gray-100">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">{order.product?.name ?? "Order"}</h1>
            <p className="text-sm text-gray-500">Order ID: {order.order_id ?? order.unique_id}</p>
            <p className="text-sm text-gray-500">Brand: {order.brand?.name ?? "—"}</p>
          </div>
          <div className="flex flex-col items-end gap-2">
            <span className="rounded-full bg-amber-50 px-3 py-1 text-xs font-semibold uppercase text-amber-700 ring-1 ring-amber-200">
              {order.status}
            </span>
            <Link
              href={`/orders/${id}/ledger`}
              className="rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-700 hover:border-[#CC1414] hover:text-[#CC1414]"
            >
              View Ledger →
            </Link>
          </div>
        </div>

        <div className="mt-6 grid grid-cols-2 gap-4 md:grid-cols-4">
          <Metric label="Order Date" value={formatDateTime(order.created_at)} />
          <Metric label="Total" value={fmtINR(order.summary?.order_total ?? order.total_amount)} />
          <Metric label="Paid" value={fmtINR(order.paid_amount)} tone="text-emerald-600" />
          <Metric label="Due" value={fmtINR(order.due_amount)} tone="text-red-600" />
        </div>
        {order.summary && (
          <div className="mt-5 border-t border-gray-100 pt-4">
            <OrderTerms summary={order.summary} creditDays={order.summary.buyer_credit_days} />
          </div>
        )}
      </div>

      {order.summary && <OrderPriceBreakup summary={order.summary} />}

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
        <AddressBlock title="Billing (Bill to)" address={order.billing} emptyText="Billing address not provided" />
        <AddressBlock
          title="Delivery (Ship to)"
          address={order.delivery}
          emptyText="Delivery address not provided — our team has been notified and will confirm it with you."
        />
        {order.purpose && <Card title="Purpose">{order.purpose}</Card>}
        {order.description && <Card title="Description">{order.description}</Card>}
      </div>

      {Array.isArray(order.history) && order.history.length > 0 && (
        <div className="rounded-xl bg-white p-6 shadow-sm ring-1 ring-gray-100">
          <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Timeline</h2>
          <ol className="space-y-2 text-sm">
            {(order.history as Array<{ status: string; created_at: string }>).map((h, i) => (
              <li key={i} className="flex items-center gap-3">
                <span className="h-2 w-2 rounded-full bg-[#CC1414]" />
                <span className="font-medium text-gray-900">{h.status}</span>
                <span className="text-xs text-gray-500">{formatDateTime(h.created_at)}</span>
              </li>
            ))}
          </ol>
        </div>
      )}
    </div>
  );
}

function Metric({ label, value, tone }: { label: string; value: string; tone?: string }) {
  return (
    <div>
      <div className="text-xs uppercase text-gray-500">{label}</div>
      <div className={`mt-1 truncate text-lg font-semibold tabular-nums ${tone ?? "text-gray-900"}`}>{value}</div>
    </div>
  );
}

function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
      <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">{title}</div>
      <div className="break-words text-sm text-gray-700">{children}</div>
    </div>
  );
}
