'use client';

import { useState } from 'react';
import { toast } from 'sonner';

import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { ApiError, api } from '@/lib/api-client';
import type { ShipmentListItem } from '@/lib/shipments';

export function CancelShipmentDialog({
  shipment,
  open,
  onClose,
  onCancelled,
}: {
  shipment: Pick<ShipmentListItem, 'id' | 'chargedMinor' | 'currency'> | null;
  open: boolean;
  onClose: () => void;
  onCancelled: (shipment: ShipmentListItem) => void;
}) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  return (
    <ConfirmDialog
      open={open}
      title="Cancel this shipment?"
      message="The label will be voided and the amount refunded to the wallet when the courier accepts the cancellation."
      confirmLabel="Cancel shipment"
      cancelLabel="Keep shipment"
      loading={loading}
      error={error}
      onClose={() => {
        if (!loading) {
          setError(null);
          onClose();
        }
      }}
      onConfirm={() => {
        if (shipment === null) return;
        setLoading(true);
        setError(null);
        void api<ShipmentListItem>(`/shipments/${shipment.id}/cancel`, { method: 'POST' })
          .then((updated) => {
            toast.success('Shipment cancelled.');
            onCancelled(updated);
            onClose();
          })
          .catch((reason: unknown) => {
            setError(reason instanceof ApiError ? reason.message : 'The shipment could not be cancelled.');
          })
          .finally(() => setLoading(false));
      }}
    />
  );
}
