"use client";

import { cn } from "@/lib/cn";
import { ExpandableText } from "@/components/shared/expandable-text";
import { formatDateTime } from "@/lib/format";
import type { Locale } from "@/i18n/types";
import type { OrderStatus } from "@/types/order";
import type { PortalOrderTimelineStep } from "@/types/portal";

/**
 * What happened to an order, oldest first, with the newest step marked.
 *
 * The dot colour follows the meaning of the step rather than its position: a delivery is green, a
 * failure red, a cancellation neutral. A cancelled order is a decision, not a fault, so drawing it
 * red would send somebody looking for a problem that does not exist.
 */
const DOT: Record<OrderStatus, string> = {
  pending: "bg-warning",
  assigned: "bg-primary",
  accepted: "bg-primary",
  collecting: "bg-primary",
  picked_up: "bg-primary",
  on_the_way: "bg-primary",
  delivered: "bg-success",
  delivery_failed: "bg-destructive",
  cancelled: "bg-muted-foreground",
  // Amber, because it is a job somebody still has to do, not an outcome.
  awaiting_return: "bg-warning",
  returned: "bg-muted-foreground",
};

export function OrderTimeline({
  steps,
  locale,
  emptyText,
}: {
  steps: PortalOrderTimelineStep[];
  locale: Locale;
  emptyText: string;
}) {
  if (steps.length === 0) {
    return <p className="text-sm text-muted-foreground">{emptyText}</p>;
  }

  return (
    <ol className="relative list-none space-y-5 ps-6 before:absolute before:inset-y-1 before:start-[0.4rem] before:w-px before:bg-border">
      {steps.map((step, index) => {
        const latest = index === steps.length - 1;

        return (
          <li key={`${step.status}-${step.at ?? index}`} className="relative min-w-0">
            <span
              aria-hidden
              className={cn(
                "absolute -start-6 top-1 h-3 w-3 rounded-full ring-4 ring-surface",
                DOT[step.status] ?? "bg-muted-foreground",
                latest ? "scale-110" : "opacity-70",
              )}
            />
            <p className={cn("text-sm", latest ? "font-semibold text-foreground" : "font-medium text-foreground/80")}>
              {step.status_label}
            </p>
            <p className="numeric text-xs text-muted-foreground">{formatDateTime(step.at, locale)}</p>
            {step.note ? <ExpandableText text={step.note} className="mt-1 text-xs text-muted-foreground" /> : null}
          </li>
        );
      })}
    </ol>
  );
}
