"use client";

import { useState, useTransition } from "react";
import { BadgeDollarSign, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { DetailCard } from "./detail-card";
import { formatCurrency } from "../../lib/format-utils";
import type { Order } from "../../types";
import { updatePaymentStatus, recordRefund } from "@/lib/actions/orders";

interface PaymentActionsCardProps {
  order: Order;
  /** The card only ever advances payment to paid / refunded / partial-refund. */
  onOrderUpdated: (payment: {
    status: "paid" | "refunded" | "partial-refund";
  }) => void;
}

const CONFIRMABLE: Record<string, boolean> = {
  pending: true,
  failed: true,
};

const REFUNDABLE: Record<string, boolean> = {
  paid: true,
  "partial-refund": true,
};

/**
 * Card the admin uses to close the manual-verification loop: confirm a wallet
 * / card transaction after checking the TrxID (→ PAID), and record reconciled
 * full or partial refunds against a paid order. Refunds write a ledger line
 * via `recordRefund` (server-side, amount-capped); payment confirmation is the
 * only allowed path from PENDING → PAID.
 */
export function PaymentActionsCard({
  order,
  onOrderUpdated,
}: PaymentActionsCardProps) {
  const [, startTransition] = useTransition();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [refundOpen, setRefundOpen] = useState(false);
  const [refundAmount, setRefundAmount] = useState("");

  const canConfirm = CONFIRMABLE[order.payment.status];
  const canRefund = REFUNDABLE[order.payment.status];

  const handleConfirm = () => {
    setBusy(true);
    setError(null);
    startTransition(() => {
      void updatePaymentStatus(order.id, "paid").then((result) => {
        setBusy(false);
        if (!result.ok) {
          setError(result.error);
          return;
        }
        onOrderUpdated({ status: "paid" });
      });
    });
  };

  const submitRefund = () => {
    const amount = Number(refundAmount);
    if (!Number.isFinite(amount) || amount <= 0) {
      setError("Enter a refund amount greater than 0.");
      return;
    }
    setBusy(true);
    setError(null);
    startTransition(() => {
      void recordRefund(order.id, { amount, reason: "Manual refund" }).then((result) => {
        setBusy(false);
        if (!result.ok) {
          setError(result.error);
          return;
        }
        onOrderUpdated({
          status: amount >= order.grandTotal ? "refunded" : "partial-refund",
        });
        setRefundOpen(false);
        setRefundAmount("");
      });
    });
  };

  return (
    <>
      <DetailCard
        title="Payment actions"
        icon={<BadgeDollarSign className="h-4 w-4 text-muted-foreground" />}
      >
        <div className="flex flex-col gap-2.5">
          <p className="text-xs leading-relaxed text-muted-foreground">
            {order.payment.status === "paid"
              ? "Payment collected. You can record a refund against it."
              : order.payment.status === "pending" && order.payment.transactionId
                ? "A transaction ID was provided — verify it in your merchant wallet, then confirm the payment."
                : "Confirm payment once the funds reach your merchant account."}
          </p>

          {error && (
            <p className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">
              {error}
            </p>
          )}

          <div className="flex flex-wrap gap-2">
            {canConfirm && (
              <Button size="sm" onClick={handleConfirm} disabled={busy}>
                {busy ? "Saving..." : "Confirm payment"}
              </Button>
            )}
            {canRefund && (
              <Button
                size="sm"
                variant="outline"
                onClick={() => setRefundOpen(true)}
                disabled={busy}
              >
                <RotateCcw className="mr-1.5 h-3.5 w-3.5" />
                Record refund
              </Button>
            )}
          </div>
          {order.payment.transactionId && (
            <p className="text-xs text-muted-foreground">
              Reference:{" "}
              <span className="font-mono text-foreground/80">
                {order.payment.transactionId}
              </span>
            </p>
          )}
        </div>
      </DetailCard>

      <Dialog open={refundOpen} onOpenChange={setRefundOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Record a refund</DialogTitle>
            <DialogDescription>
              Refund amount for {order.orderNumber} — up to{" "}
              {formatCurrency(order.grandTotal)}.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-2 py-1">
            <Label htmlFor="refund-amount">Amount (৳)</Label>
            <Input
              id="refund-amount"
              type="number"
              min={0}
              step="0.01"
              value={refundAmount}
              onChange={(e) => setRefundAmount(e.target.value)}
              placeholder={String(order.grandTotal)}
            />
            {error && refundOpen && (
              <p className="text-xs text-destructive">{error}</p>
            )}
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setRefundOpen(false);
                setError(null);
              }}
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={submitRefund}
              disabled={busy || !refundAmount.trim()}
            >
              {busy ? "Saving..." : "Issue refund"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}