"use client";

import * as React from "react";

import { kes } from "@/components/medora/payroll";
import { Button } from "@/components/ui/button";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { cn } from "@/lib/utils";

/*
 * Held orders (PS-10): baskets parked at the till, and what happened to each after. Recalling or cashing out
 * is anyone's; deleting needs the permission and a reason, and is logged with who and when. Processed holds
 * stay listed, so a basket that vanished can always be traced.
 */

export type HeldOrder = { ref: string; heldAt: string; cashier: string; customer?: string; items: number; total: number };
export type ProcessedHold = HeldOrder & { outcome: "Sold" | "Deleted"; by: string; at: string; saleRef?: string; reason?: string };

export const DELETE_REASONS = ["Customer left", "Duplicate basket", "Prices changed, re-entered", "Test or training"] as const;

export function HeldOrdersLog({ held, processed, canDelete, onRecall, onDelete }: { held: HeldOrder[]; processed: ProcessedHold[]; canDelete: boolean; onRecall: (ref: string) => void; onDelete: (ref: string, reason: string) => void }) {
  const [tab, setTab] = React.useState<"held" | "processed">("held");
  const [deleting, setDeleting] = React.useState<string | null>(null);
  const [reason, setReason] = React.useState("");
  return (
    <div className="space-y-3">
      <div role="tablist" aria-label="Held orders" className="flex gap-1 border-b border-border">
        {(
          [
            ["held", `Held now (${held.length})`],
            ["processed", `Processed (${processed.length})`],
          ] as const
        ).map(([k, label]) => (
          <button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)} className={cn("-mb-px cursor-pointer border-b-2 px-3 py-1.5 text-sm", tab === k ? "border-primary font-medium" : "border-transparent text-muted-foreground hover:text-foreground")}>
            {label}
          </button>
        ))}
      </div>
      {tab === "held" ? (
        <ul className="divide-y divide-[var(--color-border-subtle)] rounded-md border border-[var(--color-border-panel)] bg-card">
          {held.map((h) => (
            <li key={h.ref} className="space-y-2 px-3 py-2 text-sm">
              <div className="flex flex-wrap items-center gap-3">
                <span className="flex-1">
                  <span className="font-mono text-xs">{h.ref}</span> · {h.customer ?? "Walk-in"}
                  <span className="block text-xs text-muted-foreground">
                    Held {h.heldAt}
                    {h.cashier ? ` by ${h.cashier}` : ""} · {h.items} {h.items === 1 ? "item" : "items"}
                  </span>
                </span>
                <span className="font-medium tabular-nums">{kes(h.total)}</span>
                <Button size="sm" variant="outline" onClick={() => onRecall(h.ref)}>
                  Recall
                </Button>
                <Button size="sm" variant="ghost" className="text-status-error-text" disabled={!canDelete} title={canDelete ? undefined : "Deleting held orders needs the Delete permission on POS"} onClick={() => (setDeleting(h.ref), setReason(""))}>
                  Delete
                </Button>
              </div>
              {deleting === h.ref ? (
                <div className="flex flex-wrap items-center gap-2 rounded-md bg-muted/40 p-2">
                  <NativeSelect aria-label="Why delete it" value={reason} onChange={(e) => setReason(e.target.value)}>
                    <NativeSelectOption value="">Why delete it?</NativeSelectOption>
                    {DELETE_REASONS.map((r) => (
                      <NativeSelectOption key={r}>{r}</NativeSelectOption>
                    ))}
                  </NativeSelect>
                  <Button size="sm" variant="destructive" disabled={!reason} onClick={() => (onDelete(h.ref, reason), setDeleting(null))}>
                    Delete {h.ref}
                  </Button>
                  <Button size="sm" variant="ghost" onClick={() => setDeleting(null)}>
                    Keep it
                  </Button>
                  <span className="w-full text-xs text-muted-foreground">Logged with your name and the time. Stock was never taken, so nothing to return.</span>
                </div>
              ) : null}
            </li>
          ))}
          {!held.length ? <li className="px-3 py-6 text-center text-sm text-muted-foreground">No baskets on hold.</li> : null}
        </ul>
      ) : (
        <div className="overflow-x-auto rounded-md border border-[var(--color-border-panel)] bg-card">
          <table className="w-full min-w-[620px] text-sm">
            <thead className="bg-[var(--color-bg-surface-subtle)] text-left text-xs text-muted-foreground">
              <tr>
                <th className="px-3 py-2 font-medium">Held</th>
                <th className="px-3 py-2 font-medium">Outcome</th>
                <th className="px-3 py-2 font-medium">By and when</th>
                <th className="px-3 py-2 text-right font-medium">Total</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[var(--color-border-subtle)]">
              {processed.map((p) => (
                <tr key={p.ref}>
                  <td className="px-3 py-2">
                    <span className="font-mono text-xs">{p.ref}</span>
                    <span className="block text-xs text-muted-foreground">
                      {p.heldAt}, {p.cashier}
                    </span>
                  </td>
                  <td className="px-3 py-2">
                    <span className={cn("rounded px-1.5 py-0.5 text-[11px] font-medium", p.outcome === "Sold" ? "bg-status-success-bg text-status-success-text" : "bg-status-error-bg text-status-error-text")}>{p.outcome}</span>
                    <span className="mt-0.5 block text-xs text-muted-foreground">{p.outcome === "Sold" ? `as ${p.saleRef}` : p.reason}</span>
                  </td>
                  <td className="px-3 py-2 text-xs">
                    {p.by}, {p.at}
                  </td>
                  <td className="px-3 py-2 text-right tabular-nums">{kes(p.total)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
