"use client";

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

/**
 * A wrapped order's two rows, drawn as the parent and child they are.
 *
 * The delivery leg is the order the store placed and the one the customer is waiting for; the
 * collection legs hang off it as the internal errands that fetch its goods. Drawing them as a
 * tree says which is which without a sentence — and, because the tree is the same picture from
 * either row, a dispatcher who arrived on the collection leg sees at once that it is somebody
 * else's errand rather than an order in its own right.
 *
 * The row being looked at is marked, because the two are one click apart and it is otherwise
 * genuinely easy to act on the wrong one.
 *
 * Connectors are drawn with `start-*` rather than `left-*`, so the tree mirrors in Arabic
 * instead of pointing the wrong way.
 */

interface Node {
  uuid: string;
  order_number: string;
  leg: OrderLeg;
  status: OrderStatus;
  status_label: string;
  caption: string | null;
  failed_reason: string | null;
  current: boolean;
}

export function WrappedOrderTree({ order }: { order: Order }) {
  const t = useT();

  if (!order.leg) {
    return null;
  }

  const isCollection = order.leg === "collection";
  const parentRef = order.parent_order ?? null;

  const root: Node | null = isCollection
    ? parentRef
      ? {
          uuid: parentRef.uuid,
          order_number: parentRef.order_number,
          leg: "delivery",
          status: parentRef.status,
          status_label: parentRef.status_label,
          caption: parentRef.customer_name,
          failed_reason: null,
          current: false,
        }
      : null
    : {
        uuid: order.uuid,
        order_number: order.order_number,
        leg: "delivery",
        status: order.status,
        status_label: order.status_label,
        caption: order.customer_name,
        failed_reason: order.failed_reason ?? null,
        current: true,
      };

  const children: Node[] = isCollection
    ? [
        {
          uuid: order.uuid,
          order_number: order.order_number,
          leg: "collection",
          status: order.status,
          status_label: order.status_label,
          caption: order.pickups?.length
            ? t("orders.journey.supplierCount", { count: order.pickups.length })
            : order.pickup_address,
          failed_reason: order.failed_reason ?? null,
          current: true,
        },
      ]
    : (order.collection_legs ?? []).map((leg) => ({
        uuid: leg.uuid,
        order_number: leg.order_number,
        leg: "collection" as const,
        status: leg.status,
        status_label: leg.status_label,
        caption: null,
        failed_reason: leg.failed_reason,
        current: false,
      }));

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

  return (
    <div>
      {root ? <NodeCard node={root} /> : null}

      <ul className="mt-1">
        {children.map((child, index) => (
          <li key={child.uuid} className="relative ps-7">
            {/*
              The trunk runs the full height for every child but the last, where it stops at the
              elbow — so the tree closes instead of trailing a line into nothing.
            */}
            <span
              aria-hidden
              className={cn(
                "absolute start-3 top-0 w-px bg-border",
                index === children.length - 1 ? "h-6" : "h-full",
              )}
            />
            <span aria-hidden className="absolute start-3 top-6 h-px w-4 bg-border" />

            <div className="pt-2">
              <NodeCard node={child} />
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}

function NodeCard({ node }: { node: Node }) {
  const t = useT();

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

  return (
    <div
      className={cn(
        "rounded-xl border px-3 py-2.5 transition-colors",
        node.current
          ? "border-primary/40 bg-primary-soft/40 ring-1 ring-primary/15"
          : "border-border/70 bg-card hover:border-border",
      )}
    >
      <div className="flex items-start gap-2.5">
        <span
          className={cn(
            "mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",
            node.leg === "collection"
              ? "bg-warning-soft/70 text-warning"
              : "bg-primary-soft/70 text-primary",
          )}
        >
          <Icon className="h-3.5 w-3.5" aria-hidden />
        </span>

        <div className="min-w-0 flex-1">
          <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
            {node.current ? (
              <span className="text-sm font-semibold text-foreground">{node.order_number}</span>
            ) : (
              <Link
                href={`/orders/${node.uuid}`}
                className="text-sm font-semibold text-primary hover:underline"
              >
                {node.order_number}
              </Link>
            )}

            <OrderStatusBadge status={node.status} label={node.status_label} />

            {node.current ? (
              <span className="rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
                {t("orders.tree.youAreHere")}
              </span>
            ) : null}
          </div>

          <p className="mt-0.5 text-xs text-muted-foreground">
            {t(node.leg === "collection" ? "orders.tree.collectionRole" : "orders.tree.deliveryRole")}
            {node.caption ? ` · ${node.caption}` : ""}
          </p>

          {node.failed_reason ? (
            <p className="mt-1 text-xs text-destructive">{node.failed_reason}</p>
          ) : null}
        </div>
      </div>
    </div>
  );
}
