"use client";

import { PackageCheck, TriangleAlert } from "lucide-react";
import { Alert } from "@/components/ui/alert";
import { useT } from "@/i18n";
import type { Order } from "@/types/order";

/**
 * Why a wrapped order cannot be handed to a captain yet — or that it now can.
 *
 * Some stores have their goods wrapped before delivery. Such an order is **two rows**: a
 * collection leg that gathers the goods from the suppliers and leaves them with the wrapping
 * shop, and this delivery leg, which takes the finished parcel to the customer. The first
 * captain is released the moment they hand the goods over, which is why they are two orders.
 *
 * The delivery leg sits in ordinary `pending` the whole time — **it has no status of its own**,
 * because whether the parcel is ready is already recorded by the collection leg, and a second
 * copy here would be free to drift from it. That is exactly why this banner has to exist: from
 * the status alone, a blocked delivery is indistinguishable from work a dispatcher could hand
 * out right now, and the only other way to find out is to click Assign and be told 409.
 *
 * Nothing is drawn for an ordinary order, which is almost all of them.
 */
export function CollectionStatus({ order }: { order: Order }) {
  const t = useT();

  const legs = order.collection_legs ?? [];

  // Not a wrapped order, or a read that does not carry the legs. Saying nothing is right in both
  // cases: inventing "ready" for an order we have not been told about would be worse than silence.
  if (legs.length === 0) {
    return null;
  }

  const failed = legs.filter((leg) => leg.status === "delivery_failed");
  const outstanding = legs.filter((leg) => leg.status !== "delivered");

  // A failed collection is not a delay — the goods are not coming, and somebody has to decide
  // whether to send another captain for them or call the customer's order off. It outranks the
  // ordinary "still on its way" message even when another leg is still moving.
  if (failed.length > 0) {
    return (
      <Alert variant="destructive" title={t("orders.collection.failed")} icon={TriangleAlert}>
        {failed[0].failed_reason
          ? t("orders.collection.failedWithReason", {
              order: failed[0].order_number,
              reason: failed[0].failed_reason,
            })
          : t("orders.collection.failedHint", { order: failed[0].order_number })}
      </Alert>
    );
  }

  if (outstanding.length > 0) {
    return (
      <Alert variant="warning" title={t("orders.collection.waiting")}>
        {order.assignment_blocked_reason ??
          t("orders.collection.waitingHint", {
            order: outstanding[0].order_number,
            status: outstanding[0].status_label,
          })}
      </Alert>
    );
  }

  return (
    <Alert variant="success" title={t("orders.collection.arrived")} icon={PackageCheck}>
      {t("orders.collection.arrivedHint")}
    </Alert>
  );
}
