"use client";

import Link from "next/link";
import { ArrowUpRight } from "lucide-react";
import { OrderStatusBadge } from "@/components/shared/status-badges";
import { StatusRail, orderRail } from "@/components/shared/status-rail";
import { TableCell, TableRow } from "@/components/ui/table";
import { useT } from "@/i18n";
import { truncate } from "@/lib/format";
import type { Order, OrderCollectionLeg } from "@/types/order";

/** The collection tasks of an order, when it has any: the children of its row in the orders list. */
export function tasksOf(order: Pick<Order, "leg" | "collection_legs">): OrderCollectionLeg[] {
  // A failed collection the office dealt with is history on the order page, not a task still to be done.
  return order.leg === "delivery" ? (order.collection_legs ?? []).filter((task) => task.resolved_at == null) : [];
}

/** How many of the tasks have their goods: every stop collected, or already at the wrapping place. */
export function tasksDone(tasks: OrderCollectionLeg[]): number {
  return tasks.filter((task) => task.status === "delivered" || ((task.stops ?? []).length > 0 && (task.stops ?? []).every((stop) => stop.collected))).length;
}

/**
 * The collection tasks under an order's row, one line per supplier.
 *
 * A wrapped order is collected supplier by supplier, each by its own captain, and the list shows that as a tree: the customer's order is the
 * row, and under it (when expanded) each supplier with its task, its captain and where it stands. The tasks are not orders of their own, so
 * they carry no customer, source, fee or date: only what a dispatcher needs to see who is collecting where.
 */
export function OrderTaskRows({ order }: { order: Order }) {
  const t = useT();
  const tasks = tasksOf(order);
  const bringTo = order.pickup_address;

  return (
    <>
      {tasks.map((task, index) => {
        const supplier = task.suppliers?.[0];
        const last = index === tasks.length - 1;

        return (
          <TableRow key={task.uuid} className="bg-muted/30">
            <TableCell className="relative">
              <StatusRail tone={orderRail(task.status)} />
              <div className="flex items-start gap-1.5 ps-3">
                {/* The branch: down the line from the order above, then across into this task; the last one stops there. */}
                <span aria-hidden className="relative ms-1 block h-5 w-4 shrink-0 self-stretch">
                  <span className={last ? "absolute start-0 top-0 h-2.5 w-px bg-border" : "absolute start-0 top-0 h-full w-px bg-border"} />
                  <span className="absolute start-0 top-2.5 h-px w-3 bg-border" />
                </span>
                <div className="min-w-0">
                  <Link href={`/orders/${task.uuid}`} dir="ltr" className="whitespace-nowrap text-sm font-medium text-primary hover:underline">
                    {task.order_number}
                  </Link>
                  <p className="text-[0.7rem] text-muted-foreground">{t("orders.supplier.task")}</p>
                </div>
              </div>
            </TableCell>
            <TableCell />
            <TableCell className="max-w-[16rem]">
              <p className="text-sm font-medium text-foreground">{supplier?.store_name || supplier?.address || t("orders.stops.unnamedStore")}</p>
              {supplier?.store_name ? <p className="text-xs text-muted-foreground">{truncate(supplier.address, 40)}</p> : null}
            </TableCell>
            <TableCell className="max-w-[16rem] text-xs text-muted-foreground">
              {t("orders.tree.bringsTo")} {truncate(bringTo, 36)}
            </TableCell>
            <TableCell />
            <TableCell>
              {task.captain ? (
                <Link href={`/captains/${task.captain.uuid}`} className="text-sm text-foreground hover:underline">
                  {task.captain.name}
                </Link>
              ) : (
                <span className="text-xs text-warning">{t("orders.supplier.noCaptain")}</span>
              )}
            </TableCell>
            <TableCell>
              <OrderStatusBadge status={task.status} label={task.status_label} />
            </TableCell>
            <TableCell>
              <Link href={`/orders/${task.uuid}`} className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline">
                {t("common.view")}
                <ArrowUpRight className="h-3 w-3 rtl:-scale-x-100" aria-hidden />
              </Link>
            </TableCell>
          </TableRow>
        );
      })}
    </>
  );
}
