import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { transporterApi } from "@/lib/api/transporter";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiTransporterOrderDetail } from "@/lib/api/types";
import SafeImage from "@/components/ui/SafeImage";
import AddressBlock from "@/components/orders/AddressBlock";
import { advanceOrderStatus } from "./actions";
import AdvanceStatusButton from "./AdvanceStatusButton";
import { formatDateTime } from "@/lib/utils";
import { orderStatusLabel } from "@/lib/status";

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

// Module scope: one formatter, reused by every amount on the page.
const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });

function fmtINR(n: number) {
  return inr.format(n);
}

/** Transport steps on the canonical lifecycle, keyed by `status_code`. */
const NEXT_STATUSES: Record<string, string[]> = {
  seller_confirmed: ["loading"],
  loading: ["dispatched"],
  weighed_invoiced: ["dispatched"],
  dispatched: ["delivered"],
};

async function loadOrder(token: string, id: number): Promise<ApiTransporterOrderDetail | null> {
  try {
    return await transporterApi.order(token, id);
  } catch {
    return null;
  }
}

/**
 * Server-rendered trip detail with a Server Action for status transitions.
 *
 * The client version showed a `Loader` while an effect fetched the trip — a
 * spinner that could not even start until the bundle had hydrated. Fetching
 * during SSR removes both the spinner and the wait.
 *
 * `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 TransporterOrderDetailPage({ params }: PageProps) {
  const { id } = await params;
  const token = await requireServerToken(`/transporter/orders/${id}`);
  await requireRole(["transporter"]);

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

  if (!order) {
    return <div className="rounded-xl bg-white p-10 text-center text-gray-500 shadow-sm">Trip not found.</div>;
  }

  const nextOptions = NEXT_STATUSES[order.status_code ?? ""] ?? [];

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

      <div className="flex flex-col gap-3 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-xl font-bold text-gray-900">Trip {order.order_id ?? order.unique_id}</h1>
          <p className="text-sm text-gray-500">Status: <span className="font-medium text-gray-900">{order.status_label ?? order.status}</span></p>
        </div>
        {nextOptions.length > 0 && (
          <div className="flex flex-wrap gap-2">
            {nextOptions.map((s) => (
              // One form per transition: the target status travels as form data
              // instead of a closure, so the post works without client JS.
              <form key={s} action={advanceOrderStatus}>
                <input type="hidden" name="id" value={order.id} />
                <input type="hidden" name="status" value={s} />
                <AdvanceStatusButton status={orderStatusLabel(s)} />
              </form>
            ))}
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
        <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-2">
          <h2 className="mb-3 text-sm font-semibold text-gray-900">Product</h2>
          <div className="flex items-start gap-4">
            {order.product?.thumbnail && (
              <SafeImage
                src={order.product.thumbnail}
                alt=""
                width={80}
                height={80}
                className="h-20 w-20 rounded-lg object-cover ring-1 ring-gray-100"
              />
            )}
            <div className="text-sm">
              <div className="font-semibold text-gray-900">{order.product?.name ?? "—"}</div>
              <div className="text-gray-500">{order.brand?.name ?? "—"}</div>
              <div className="mt-1 text-gray-500">
                Qty: {Number(order.total_quantity) > 0 ? `${order.total_quantity} ${order.quantity_unit ?? "MT"}` : "Not recorded"}
              </div>
              {order.load_within && <div className="text-gray-500">Load within: {order.load_within} days</div>}
              {order.origin_city && <div className="text-gray-500">Origin: {order.origin_city}</div>}
            </div>
          </div>
        </div>

        <AddressBlock title="Pickup (Loading point)" address={order.pickup} emptyText="Loading point not provided" />
        <AddressBlock title="Drop (Ship to)" address={order.delivery} emptyText="Delivery address not provided" />

        <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
          <h2 className="mb-3 text-sm font-semibold text-gray-900">Customer</h2>
          <p className="text-sm font-medium text-gray-900">{order.customer?.name ?? "—"}</p>
          {order.customer?.contact_shared === false ? (
            <p className="mt-1 text-xs text-gray-500">Buyer contact is shared once the seller confirms the order.</p>
          ) : (
            <>
              <p className="text-sm text-gray-500">{order.customer?.phone ?? ""}</p>
              <p className="text-sm text-gray-500">{order.customer?.email ?? ""}</p>
            </>
          )}
          <h2 className="mt-4 mb-2 text-sm font-semibold text-gray-900">Seller</h2>
          <p className="text-sm font-medium text-gray-900">{order.seller?.name ?? "—"}</p>
          <p className="text-sm text-gray-500">{order.seller?.phone ?? ""}</p>
        </div>

        <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-3">
          <h2 className="mb-3 text-sm font-semibold text-gray-900">Pricing</h2>
          <dl className="grid grid-cols-2 gap-4 text-sm sm:grid-cols-3">
            <div>
              <dt className="text-xs text-gray-500">Transport</dt>
              <dd className="font-semibold text-gray-900">{fmtINR(order.transport_price)}</dd>
            </div>
            <div>
              <dt className="text-xs text-gray-500">Total</dt>
              <dd className="font-semibold text-gray-900">{fmtINR(order.total_amount)}</dd>
            </div>
            <div>
              <dt className="text-xs text-gray-500">Final</dt>
              <dd className="font-semibold text-gray-900">{fmtINR(order.final_amount)}</dd>
            </div>
          </dl>
        </div>

        {Array.isArray(order.history) && order.history.length > 0 && (
          <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-3">
            <h2 className="mb-3 text-sm font-semibold text-gray-900">History</h2>
            <ol className="space-y-2 text-sm">
              {order.history.map((h, i) => (
                <li key={i} className="flex items-center justify-between border-b border-gray-100 pb-2 last:border-b-0">
                  <span className="capitalize text-gray-900">
                    {String(h.status ?? "")}
                    {h.note ? ` — ${String(h.note)}` : ""}
                  </span>
                  <span className="text-xs text-gray-500">
                    {h.created_at ? formatDateTime(String(h.created_at)) : ""}
                  </span>
                </li>
              ))}
            </ol>
          </div>
        )}

        {order.invoices.length > 0 && (
          <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-3">
            <h2 className="mb-3 text-sm font-semibold text-gray-900">Invoices</h2>
            <ul className="grid grid-cols-2 gap-2 sm:grid-cols-4">
              {order.invoices.map((inv, i) => (
                <li key={i}>
                  <a href={inv.image} target="_blank" rel="noreferrer" className="block">
                    <SafeImage
                      src={inv.image}
                      alt="invoice"
                      width={320}
                      height={128}
                      className="h-32 w-full rounded-lg object-cover ring-1 ring-gray-100"
                    />
                  </a>
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
}
