import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { money, fmtDate } from "../lib/format";

export function MatchBillDialog({
  open, onOpenChange, candidates, currency, onMatch, onCreateNew,
}: {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  candidates: any[];
  currency?: string;
  onMatch: (billId: string) => void;
  onCreateNew: () => void;
}) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Possible matching bill found</DialogTitle>
        </DialogHeader>
        <p className="text-sm text-muted-foreground">
          We found {candidates.length === 1 ? "a bill" : `${candidates.length} bills`} that may match this payment. Apply the payment to an existing bill, or create a new one.
        </p>
        <div className="space-y-2 max-h-72 overflow-auto">
          {candidates.map((b) => {
            const balance = Number(b.total) - Number(b.paid_amount ?? 0);
            return (
              <button
                key={b.id}
                onClick={() => onMatch(b.id)}
                className="w-full text-left rounded-md border border-border p-3 hover:bg-muted transition"
              >
                <div className="flex justify-between font-medium">
                  <span>Bill #{b.number}</span>
                  <span>{money(balance, currency)}</span>
                </div>
                <div className="text-xs text-muted-foreground mt-1">
                  Issued {fmtDate(b.issue_date)} · Total {money(b.total, currency)}
                </div>
              </button>
            );
          })}
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={onCreateNew}>No, Create New Bill</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
