"use client";

import Link from "next/link";
import { Boxes, PackageOpen } from "lucide-react";
import { useT } from "@/i18n";
import { cn } from "@/lib/cn";
import type { Order, OrderLeg } from "@/types/order";

/**
 * Which half of a wrapped delivery a row is.
 *
 * A wrapped order is two rows with consecutive numbers, the same neighbourhood and nothing on
 * the page saying one fetches the goods for the other — so without this badge the pair reads as
 * a duplicate somebody should probably delete.
 *
 * Nothing is drawn for an ordinary order, which is almost all of them: a badge on every row
 * would be noise that teaches nobody anything.
 */
export function OrderLegBadge({ leg, label, className }: { leg?: OrderLeg | null; label?: string | null; className?: string }) {
  const t = useT();

  if (!leg) {
    return null;
  }

  const Icon = leg === "collection" ? Boxes : PackageOpen;

  return (
    <span
      className={cn(
        "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium",
        leg === "collection"
          ? "border-warning/30 bg-warning-soft/60 text-warning"
          : "border-primary/20 bg-primary-soft/60 text-primary",
        className,
      )}
    >
      <Icon className="h-3 w-3" aria-hidden />
      {label ?? t(leg === "collection" ? "orders.legs.collection" : "orders.legs.delivery")}
    </span>
  );
}

/**
 * The other half of a wrapped order, as a link.
 *
 * Walkable from **both** ends deliberately. From the delivery you need to know who is fetching
 * the goods and how far they have got; from the collection you need to know whose order it is,
 * because a collection row carries a wrapping shop's name and address and none of the
 * customer's — the `-C` on its number is a naming convention, not somewhere you can click.
 *
 * Compact by default for a table cell; `block` gives the fuller form for a detail panel.
 */
export function WrappedOrderLink({ order, variant = "inline" }: { order: Order; variant?: "inline" | "block" }) {
  const t = useT();

  const parent = order.parent_order ?? null;
  const children = order.collection_legs ?? [];

  if (!parent && children.length === 0) {
    return null;
  }

  if (variant === "inline") {
    // One line under an order number in a table: the relationship, not the detail.
    return (
      <span className="text-xs text-muted-foreground">
        {parent ? (
          <>
            {t("orders.wrapped.forParent")}{" "}
            <Link href={`/orders/${parent.uuid}`} className="font-medium text-primary hover:underline">
              {parent.order_number}
            </Link>
          </>
        ) : (
          <>
            {t("orders.wrapped.collectedBy")}{" "}
            {children.map((leg, index) => (
              <span key={leg.uuid}>
                {index > 0 ? ", " : ""}
                <Link href={`/orders/${leg.uuid}`} className="font-medium text-primary hover:underline">
                  {leg.order_number}
                </Link>
              </span>
            ))}
          </>
        )}
      </span>
    );
  }

  return (
    <div className="space-y-2">
      {parent ? (
        <Row
          label={t("orders.wrapped.forParent")}
          href={`/orders/${parent.uuid}`}
          number={parent.order_number}
          caption={parent.customer_name}
          status={parent.status_label}
        />
      ) : null}

      {children.map((leg) => (
        <Row
          key={leg.uuid}
          label={t("orders.wrapped.collectedBy")}
          href={`/orders/${leg.uuid}`}
          number={leg.order_number}
          caption={leg.failed_reason}
          status={leg.status_label}
        />
      ))}
    </div>
  );
}

function Row({
  label,
  href,
  number,
  caption,
  status,
}: {
  label: string;
  href: string;
  number: string;
  caption?: string | null;
  status: string;
}) {
  return (
    <div className="flex items-start justify-between gap-3 rounded-lg border border-border/60 px-3 py-2">
      <div className="min-w-0">
        <p className="text-xs text-muted-foreground">{label}</p>
        <Link href={href} className="text-sm font-semibold text-primary hover:underline">
          {number}
        </Link>
        {caption ? <p className="truncate text-xs text-muted-foreground">{caption}</p> : null}
      </div>
      <span className="shrink-0 text-xs text-muted-foreground">{status}</span>
    </div>
  );
}
