"use client";

import { useT } from "@/i18n";
import { truncate } from "@/lib/format";
import { cn } from "@/lib/cn";
import type { Order, OrderSupplier } from "@/types/order";

/**
 * Every supplier an order is collected from, as a list row or a card shows them.
 *
 * An order can be gathered from several shops, and a list row used to draw only the first because the one
 * address it had was `pickup_address`, a mirror of the first stop. The stops now come with the list, so this
 * names all of them; when a read did not load them it falls back to that one address rather than drawing
 * nothing.
 */
export function suppliersOf(order: Pick<Order, "pickups" | "pickup_address" | "leg" | "collection_legs">): OrderSupplier[] {
  // A split order's own pickup is the hub; the suppliers are on its collection tasks.
  const fromTasks = order.leg === "delivery" ? (order.collection_legs ?? []).filter((task) => task.resolved_at == null).flatMap((task) => task.suppliers ?? []) : [];

  if (fromTasks.length > 0) {
    return fromTasks;
  }

  const stops = order.pickups ?? [];

  if (stops.length > 0) {
    return stops.map((stop) => ({ store_name: stop.store_name, address: stop.address }));
  }

  return order.pickup_address ? [{ store_name: null, address: order.pickup_address }] : [];
}

interface Props {
  suppliers: OrderSupplier[];
  /** How many to name before "+N more". Everything when omitted. */
  max?: number;
  /** One line ("A · B · +1 more") instead of a stacked list: for tight spaces. */
  inline?: boolean;
  className?: string;
}

export function OrderSuppliers({ suppliers, max, inline = false, className }: Props) {
  const t = useT();

  if (suppliers.length === 0) {
    return <span className="text-xs text-muted-foreground">—</span>;
  }

  const shown = max === undefined ? suppliers : suppliers.slice(0, max);
  const hidden = suppliers.slice(shown.length);
  const label = (supplier: OrderSupplier) => supplier.store_name || supplier.address || t("orders.stops.unnamedStore");
  // Everything that is not drawn, for a hover and for a screen reader.
  const hiddenTitle = hidden.map(label).join("\n");
  const more = hidden.length > 0 ? t("orders.suppliers.more", { count: hidden.length }) : null;

  if (inline) {
    return (
      <span className={cn("block truncate text-xs text-muted-foreground", className)} title={suppliers.map(label).join("\n")}>
        {shown.map(label).join(" · ")}
        {more ? ` · ${more}` : ""}
      </span>
    );
  }

  return (
    <ul className={cn("space-y-1", className)}>
      {shown.map((supplier, index) => (
        <li key={`${supplier.address}-${index}`} className="text-sm leading-tight">
          <span className="font-medium text-foreground">
            {suppliers.length > 1 ? <span className="me-1 text-xs text-muted-foreground">{index + 1}.</span> : null}
            {supplier.store_name || t("orders.stops.unnamedStore")}
          </span>
          <span className="block text-xs text-muted-foreground">{truncate(supplier.address, 38)}</span>
        </li>
      ))}
      {more ? (
        <li className="text-xs font-medium text-primary" title={hiddenTitle} aria-label={`${more}: ${hiddenTitle}`}>
          {more}
        </li>
      ) : null}
    </ul>
  );
}
