"use client";

import { useState } from "react";
import { Button, Dialog, Field, Input } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { api, ApiError } from "@/lib/api";
import { formatPaise, paiseToInput, rupeesToPaise } from "@/lib/format";
import type { Payment } from "@/lib/types";

/** Refund part or all of an online payment through Razorpay. For a recharge, the wallet gives back its share first. */
export function RefundDialog({ payment, onClose, onDone }: { payment: Payment; onClose: () => void; onDone: () => void }) {
  const toast = useToast();
  const remaining = payment.total_paise - payment.refunded_paise;
  const [amount, setAmount] = useState(paiseToInput(remaining));
  const [reason, setReason] = useState("");
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [busy, setBusy] = useState(false);
  const paise = rupeesToPaise(amount) ?? 0;
  const walletShare = payment.purpose === "recharge" ? Math.floor((paise * payment.amount_paise) / payment.total_paise) : 0;
  async function save() {
    setBusy(true);
    setErrors({});
    try {
      await api.post(`/admin/payments/${payment.id}/refund`, { amount, reason });
      toast("success", `Refund of ${formatPaise(paise)} started`);
      onDone();
    } catch (e) {
      if (e instanceof ApiError && Object.keys(e.fields).length) setErrors(e.fields);
      else toast("error", (e as Error).message);
    } finally {
      setBusy(false);
    }
  }
  return (
    <Dialog
      open
      onClose={onClose}
      title="Refund payment"
      description={`${payment.receipt}: ${formatPaise(payment.total_paise)} paid${payment.refunded_paise ? `, ${formatPaise(payment.refunded_paise)} already refunded` : ""}.`}
      footer={
        <>
          <Button onClick={onClose}>Cancel</Button>
          <Button variant="danger" loading={busy} onClick={save} disabled={!paise}>
            Refund {paise ? formatPaise(paise) : ""}
          </Button>
        </>
      }
    >
      <div className="space-y-4">
        <Field label="Amount to refund (₹, including GST)" htmlFor="rf-amount" error={errors.amount}>
          <Input id="rf-amount" inputMode="decimal" value={amount} onChange={(e) => setAmount(e.target.value)} invalid={!!errors.amount} />
        </Field>
        <Field label="Reason" htmlFor="rf-reason" error={errors.reason} hint="Kept in the audit log and shown to finance.">
          <Input id="rf-reason" value={reason} onChange={(e) => setReason(e.target.value)} invalid={!!errors.reason} />
        </Field>
        {walletShare > 0 && <p className="rounded-md bg-amber-soft px-3 py-2 text-[13px] text-amber">{formatPaise(walletShare)} will be taken out of the customer&apos;s wallet, because it was credited from this payment.</p>}
        <p className="text-[13px] text-muted">Razorpay sends the money back to the original card or UPI account in 5–7 working days. Reseller earnings on this payment are reversed in proportion.</p>
      </div>
    </Dialog>
  );
}
