"use client";

import { useState } from "react";
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { formatCurrency } from "../lib/format-utils";
import type { Order } from "../types";

interface CancelOrderDialogProps {
  order: Order;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onConfirm: (options: { refund: boolean }) => void;
}

/**
 * Destructive-action confirmation for cancelling an order.
 * For paid orders, the admin can opt to refund the grand total.
 */
export function CancelOrderDialog({
  order,
  open,
  onOpenChange,
  onConfirm,
}: CancelOrderDialogProps) {
  const [refund, setRefund] = useState(true);
  const chargeable = order.payment.status === "paid";

  const handleConfirm = () => {
    onConfirm({ refund: chargeable ? refund : false });
    onOpenChange(false);
    setRefund(true);
  };

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Cancel this order?</AlertDialogTitle>
          <AlertDialogDescription>
            This will stop fulfillment for{" "}
            <span className="font-medium text-foreground">
              {order.orderNumber}
            </span>{" "}
            ({formatCurrency(order.grandTotal)}) and move it to{" "}
            <span className="font-medium text-foreground">Cancelled</span>. The
            customer will not be charged further.
          </AlertDialogDescription>
        </AlertDialogHeader>

        {chargeable && (
          <label className="flex items-start gap-3 rounded-lg border bg-muted/30 p-3.5 text-sm cursor-pointer">
            <Checkbox
              checked={refund}
              onCheckedChange={(checked) => setRefund(checked === true)}
              className="mt-0.5"
            />
            <span className="space-y-0.5">
              <span className="font-medium">Refund {formatCurrency(order.grandTotal)}</span>
              <span className="block text-muted-foreground">
                Issue a full refund to the customer&apos;s original payment
                method.
              </span>
            </span>
          </label>
        )}

        <AlertDialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Keep order
          </Button>
          <Button variant="destructive" onClick={handleConfirm}>
            Cancel order
            {chargeable && refund ? ` + refund` : ""}
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}