'use client';

import { Ban, Copy, Download, ExternalLink, Eye } from 'lucide-react';
import { toast } from 'sonner';

import { Menu, type MenuItem } from '@/components/ui/menu';
import { ApiError, apiBlob, downloadBlob } from '@/lib/api-client';
import { canCancelShipment, isLabelReady, type ShipmentListItem } from '@/lib/shipments';

export function ShipmentRowActions({
  shipment,
  onCancel,
}: {
  shipment: ShipmentListItem;
  onCancel: (shipment: ShipmentListItem) => void;
}) {
  const cancellable = canCancelShipment(shipment.status);
  const items: MenuItem[] = [
    { label: 'View', icon: Eye, href: `/shipments/${shipment.id}` },
    {
      label: 'Download label',
      icon: Download,
      disabled: !isLabelReady(shipment),
      disabledReason: 'The label is not ready yet',
      onSelect: () => {
        void apiBlob(`/shipments/${shipment.id}/label`)
          .then((blob) => downloadBlob(blob, `${shipment.id}.pdf`))
          .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'The label could not be downloaded.'));
      },
    },
    ...(shipment.trackingNumber === undefined
      ? []
      : [{ label: 'Track', icon: ExternalLink, href: `/track/${encodeURIComponent(shipment.trackingNumber)}`, external: true } satisfies MenuItem]),
    { label: 'Duplicate', icon: Copy, href: `/shipments/new?duplicate=${shipment.id}` },
    { type: 'divider' },
    {
      label: 'Cancel',
      icon: Ban,
      danger: true,
      disabled: !cancellable,
      disabledReason: 'Only shipments that are created or have a label ready can be cancelled',
      onSelect: () => onCancel(shipment),
    },
  ];
  return <Menu items={items} label={`Actions for ${shipment.trackingNumber ?? 'shipment'}`} />;
}
