import { useState, type MouseEvent } from 'react';
import { Button } from '@mantine/core';
import { FileText } from 'lucide-react';

import { useToast } from '@/hooks/use-toast';
import { warehouseService } from '@/services/warehouse.service';
import { extractDownloadErrorMessage } from './options';
import { openPdfBlob } from './pdf';

/** Opens (or downloads) an inventory item's GRN document — same button everywhere it appears. */
export function GrnDocumentButton({
  inventoryId,
  grnNumber,
}: {
  inventoryId: string;
  grnNumber?: string | null;
}) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);

  const openDocument = async (event: MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    if (!grnNumber) {
      toast({ variant: 'destructive', title: 'GRN document unavailable', description: 'This item has no GRN number yet.' });
      return;
    }
    setLoading(true);
    const pdfWindow = window.open('', '_blank');
    try {
      const response = await warehouseService.downloadGrnDocument(inventoryId);
      const opened = openPdfBlob(response.data, `grn-${grnNumber}.pdf`, pdfWindow);
      toast({ title: opened ? 'GRN document opened' : 'GRN document downloaded' });
    } catch (error) {
      pdfWindow?.close();
      toast({ variant: 'destructive', title: 'GRN document failed', description: await extractDownloadErrorMessage(error) });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Button
      size="compact-xs"
      variant="subtle"
      color="teal"
      leftSection={<FileText size={12} />}
      disabled={!grnNumber}
      loading={loading}
      onClick={openDocument}
    >
      {grnNumber ?? 'No GRN'}
    </Button>
  );
}
