/** کارت یک سفارش با اقلام، مبالغ و خط زمانی */
import { orderStatusLabel, type SampleOrder } from "@/data/orders";
import { faDigits, formatJalali, formatToman } from "@/lib/format";
import { ProductVisual } from "@/components/product/ProductVisual";
import type { ProductSummary, ProductVariant } from "@/types/catalog";
import { OrderTimeline } from "./OrderTimeline";

export function OrderCard({ order, items, open = false }: { order: SampleOrder; items: { product: ProductSummary; variant: ProductVariant; qty: number }[]; open?: boolean }) {
  const subtotal = order.items.reduce((s, i) => s + i.price * i.qty, 0);
  return (
    <details open={open} className="group rounded-2xl border border-line [&_summary::-webkit-details-marker]:hidden">
      <summary className="flex cursor-pointer list-none flex-wrap items-center justify-between gap-2 p-4">
        <span>
          <bdi className="block text-sm font-bold">{faDigits(order.code)}</bdi>
          <span className="text-xs text-muted">{formatJalali(order.createdAt)}</span>
        </span>
        <span className="flex items-center gap-3">
          <span className="rounded-full bg-mist px-3 py-1 text-xs">{orderStatusLabel[order.status]}</span>
          <span className="text-sm font-bold">{formatToman(subtotal - order.discount + order.shippingCost)}</span>
        </span>
      </summary>
      <div className="grid gap-6 border-t border-line p-4 md:grid-cols-2">
        <ul className="space-y-3">
          {items.map((i) => (
            <li key={i.variant.id} className="flex items-center gap-3 text-sm">
              <span className="size-14 shrink-0 overflow-hidden rounded-lg bg-mist">
                <ProductVisual image={i.product.image} sizes="56px" shape={i.product.shape} tone={i.variant.colorHex ?? i.product.tone} label={i.product.brand.nameEn} className="size-full" />
              </span>
              <span className="min-w-0 flex-1">
                <span className="block truncate">{i.product.name}</span>
                <span className="text-xs text-muted">{faDigits(i.qty)} عدد{i.variant.colorName ? ` · ${i.variant.colorName}` : ""}</span>
              </span>
            </li>
          ))}
        </ul>
        <div className="space-y-4">
          <OrderTimeline history={order.history} />
          <p className="text-xs text-muted">
            {order.shippingMethod}
            {order.trackingCode && <> · کد رهگیری: <bdi className="text-ink">{order.trackingCode}</bdi></>}
          </p>
        </div>
      </div>
    </details>
  );
}
