"use client";

import { Boxes, Check, PackageCheck, TriangleAlert } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useI18n, useT } from "@/i18n";
import { formatDateTime } from "@/lib/format";
import type { Fulfillment, FulfillmentState, Order } from "@/types/order";

/** How loudly to draw each state: a stuck collection is a problem, everything else is progress. */
function tone(state: FulfillmentState): "success" | "warning" | "destructive" | "secondary" | "info" {
  switch (state) {
    case "delivered":
      return "success";
    case "collection_failed":
    case "delivery_failed":
      return "destructive";
    case "cancelled":
      return "secondary";
    case "awaiting_assignment":
    case "awaiting_collection":
      return "warning";
    default:
      return "info";
  }
}

/**
 * Where the whole order stands in being fulfilled.
 *
 * An order can be carried out in several pieces by several captains: three suppliers, three collection legs, a delivery that waits for all
 * of them. The status on each row says where THAT row is; this says where the whole order is, how far collection has got, what is coming
 * against what was ordered, what needs a person, and who had the goods. It is drawn from facts already on the order and stored nowhere, so
 * it cannot disagree with the rows it is drawn from.
 */
export function FulfillmentCard({ order }: { order: Order }) {
  const t = useT();
  const { locale } = useI18n();
  const f: Fulfillment | undefined = order.fulfillment;

  if (!f) {
    return null;
  }

  const issues = Object.entries(f.open_issues).filter(([, count]) => (count ?? 0) > 0);
  const collection = f.collection;
  const percent = collection && collection.suppliers > 0 ? Math.round((collection.suppliers_collected / collection.suppliers) * 100) : 0;

  return (
    <Card className="mb-6">
      <CardHeader className="pb-3">
        <CardTitle className="flex flex-wrap items-center gap-2">
          <PackageCheck className="h-4 w-4 text-muted-foreground" aria-hidden />
          {t("orders.fulfillment.title")}
          <Badge variant={tone(f.state)}>{t(`orders.fulfillment.state.${f.state}` as never)}</Badge>
          <span className="text-xs font-normal text-muted-foreground">{t(`orders.fulfillment.strategy.${f.strategy}` as never)}</span>
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {collection ? (
          <div>
            <div className="flex flex-wrap items-baseline justify-between gap-2 text-sm">
              <span className="font-medium text-foreground">
                {t("orders.fulfillment.suppliers", { collected: collection.suppliers_collected, total: collection.suppliers })}
              </span>
              {collection.legs_delivered !== undefined ? (
                <span className="text-xs text-muted-foreground">
                  {t("orders.fulfillment.legs", { delivered: collection.legs_delivered, total: collection.legs })}
                  {(collection.legs_unassigned ?? 0) > 0 ? ` · ${t("orders.fulfillment.unassigned", { count: collection.legs_unassigned ?? 0 })}` : ""}
                </span>
              ) : null}
            </div>
            <div className="mt-2 h-2 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuenow={percent} aria-valuemin={0} aria-valuemax={100}>
              <div className="h-full rounded-full bg-primary" style={{ width: `${percent}%` }} />
            </div>
          </div>
        ) : null}

        {f.items.ordered !== undefined ? (
          <div className="flex flex-wrap gap-2 text-xs">
            <Badge variant="secondary" className="font-normal">{t("orders.fulfillment.itemsOrdered", { count: f.items.ordered })}</Badge>
            <Badge variant="secondary" className="font-normal">{t("orders.fulfillment.itemsComing", { count: f.items.coming ?? 0 })}</Badge>
            {(f.items.missing ?? 0) > 0 ? (
              <Badge variant="warning" className="font-normal">{t("orders.fulfillment.itemsMissing", { count: f.items.missing ?? 0 })}</Badge>
            ) : null}
          </div>
        ) : null}

        {issues.length > 0 ? (
          <ul className="space-y-1 text-sm">
            {issues.map(([key, count]) => (
              <li key={key} className="flex items-center gap-2 text-warning">
                <TriangleAlert className="h-4 w-4" aria-hidden />
                {t(`orders.fulfillment.issue.${key}` as never, { count: count ?? 0 })}
              </li>
            ))}
          </ul>
        ) : null}

        {f.custody.length > 0 ? (
          <div>
            <p className="mb-2 flex items-center gap-1 text-xs font-medium text-muted-foreground">
              <Boxes className="h-3 w-3" aria-hidden />
              {t("orders.fulfillment.custody")}
            </p>
            <ol className="space-y-1.5">
              {f.custody.map((step, index) => (
                <li key={`${step.step}-${index}`} className="flex items-start gap-2 text-sm">
                  <Check className="mt-0.5 h-4 w-4 shrink-0 text-success" aria-hidden />
                  <span>
                    <span className="font-medium text-foreground">{t(`orders.fulfillment.step.${step.step}` as never)}</span>
                    {step.by ? <span> · {step.by}</span> : null}
                    {step.where ? <span className="text-muted-foreground"> · {step.where}</span> : null}
                    {step.at ? <span className="block text-xs text-muted-foreground">{formatDateTime(step.at, locale)}</span> : null}
                  </span>
                </li>
              ))}
            </ol>
          </div>
        ) : null}
      </CardContent>
    </Card>
  );
}
