"use client";

import { kes } from "@/components/medora/payroll";
import { onlineStageBadge, type OnlineOrderStage } from "@/components/medora/pos-ops";
import { ListTable } from "@/components/medora/record-lists";
import { Button } from "@/components/ui/button";

/*
 * Online orders list (PS-11): every order from the shop with its branch, stage, pickup or delivery, how it
 * was paid and who dispatched it. Orders still to be packed or handed over open at the till to fulfil;
 * prescription orders can't be packed until approved (PS-12), which the stage says.
 */

export type OnlineOrderRow = {
  ref: string;
  placedAt: string;
  branch: string;
  customer: string;
  stage: OnlineOrderStage;
  fulfilment: "Delivery" | "Pickup";
  tender: { method: "M-Pesa" | "Card" | "Pay on delivery"; status: "Paid" | "Unpaid" | "Refunded" };
  dispatchedBy?: string;
  rider?: string;
  total: number;
  rx?: boolean;
};

const ACTIONABLE: OnlineOrderStage[] = ["new", "rx-review", "packing", "ready"];

export function OnlineOrdersList({ rows, onFulfil }: { rows: OnlineOrderRow[]; onFulfil: (ref: string) => void }) {
  return (
    <ListTable
      rows={rows}
      rowKey={(r) => r.ref}
      search={{ placeholder: "Order or customer", text: (r) => `${r.ref} ${r.customer}` }}
      filters={[
        { label: "Branch", all: "All branches", value: (r) => r.branch },
        { label: "Fulfilment", all: "Pickup and delivery", value: (r) => r.fulfilment },
        { label: "Stage", all: "Any stage", value: (r) => (ACTIONABLE.includes(r.stage) ? "To fulfil" : r.stage === "rx-rejected" ? "Rejected" : "Done or on its way") },
      ]}
      empty="No online orders match."
      minWidth="min-w-[860px]"
      cols={[
        { key: "ref", header: "Order", cell: (r) => (<><span className="font-mono text-xs">{r.ref}</span><span className="block text-xs text-muted-foreground">{r.placedAt} · {r.branch}</span></>) },
        { key: "c", header: "Customer", cell: (r) => (<>{r.customer}{r.rx ? <span className="ml-1.5 rounded bg-status-warning-bg px-1 text-[10px] font-semibold text-status-warning-text">Rx</span> : null}</>) },
        { key: "s", header: "Stage", cell: (r) => onlineStageBadge(r.stage) },
        { key: "f", header: "Pickup or delivery", cell: (r) => r.fulfilment },
        { key: "t", header: "Paid by", cell: (r) => (<>{r.tender.method}<span className={r.tender.status === "Paid" ? "block text-xs text-status-success-text" : "block text-xs text-muted-foreground"}>{r.tender.status}</span></>) },
        { key: "d", header: "Dispatched by", cell: (r) => (r.dispatchedBy ? <>{r.dispatchedBy}{r.rider ? <span className="block text-xs text-muted-foreground">rider {r.rider}</span> : null}</> : <span className="text-muted-foreground">–</span>) },
        { key: "v", header: "Total", numeric: true, cell: (r) => kes(r.total), total: (s) => kes(s.reduce((t, r) => t + r.total, 0)) },
        {
          key: "a",
          header: "",
          cell: (r) =>
            ACTIONABLE.includes(r.stage) ? (
              <Button size="sm" variant="outline" onClick={() => onFulfil(r.ref)}>
                {r.stage === "rx-review" ? "Review Rx" : "Fulfil at till"}
              </Button>
            ) : null,
        },
      ]}
      totalsLabel={(s) => `${s.length} orders`}
    />
  );
}
