'use client';

import { useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Printer } from 'lucide-react';
import type { Shelf, Warehouse } from '@/lib/types';

interface ShelfLabelPrintProps {
  shelf: Shelf;
  warehouse: Warehouse;
  t?: any;
  tGlobal?: any;
  /** When true renders only the icon button (no text) */
  compact?: boolean;
}

export function ShelfLabelPrint({ shelf, warehouse, t, tGlobal, compact = false }: ShelfLabelPrintProps) {
  const [open, setOpen] = useState(false);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [qrDataUrl, setQrDataUrl] = useState<string>('');

  // Generate QR code from shelf reference whenever dialog opens
  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    const generate = async () => {
      try {
        const QRCode = (await import('qrcode')).default;
        const data = [
          warehouse.warehouseNumber || warehouse.id,
          shelf.shelfNumber || shelf.id,
          shelf.name,
        ]
          .filter(Boolean)
          .join('|');
        const url = await QRCode.toDataURL(data, {
          width: 220,
          margin: 1,
          color: { dark: '#000000', light: '#ffffff' },
        });
        if (!cancelled) setQrDataUrl(url);
      } catch {
        if (!cancelled) setQrDataUrl('');
      }
    };
    generate();
    return () => { cancelled = true; };
  }, [open, shelf.shelfNumber, shelf.id, shelf.name, warehouse.warehouseNumber, warehouse.id]);

  const handlePrint = () => {
    const printWindow = window.open('', '_blank', 'width=400,height=500');
    if (!printWindow) return;

    const labelHtml = `<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
  <meta charset="UTF-8" />
  <title>${t?.shelfLabelTitle ?? 'بطاقة رف'}</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: Arial, sans-serif; background: #fff; display: flex; justify-content: center; align-items: flex-start; padding: 20px; }
    .label {
      width: 9cm;
      border: 2px solid #000;
      border-radius: 6px;
      padding: 12px 14px;
      page-break-inside: avoid;
    }
    .company-row { font-size: 10px; color: #555; margin-bottom: 6px; }
    .warehouse-name { font-size: 14px; font-weight: bold; }
    .warehouse-ref  { font-family: monospace; font-size: 11px; color: #333; margin-bottom: 8px; }
    .divider { border-top: 1px dashed #bbb; margin: 8px 0; }
    .shelf-name { font-size: 16px; font-weight: bold; }
    .shelf-ref  { font-family: monospace; font-size: 12px; color: #333; }
    .qr-block { text-align: center; margin-top: 10px; }
    .qr-block img { width: 120px; height: 120px; }
    .qr-caption { font-size: 9px; color: #888; margin-top: 3px; }
    @media print {
      body { padding: 4mm; }
      @page { margin: 4mm; size: 100mm 140mm; }
    }
  </style>
</head>
<body>
  <div class="label">
    <div class="warehouse-name">${escapeHtml(warehouse.name)}</div>
    <div class="warehouse-ref">${escapeHtml(warehouse.warehouseNumber || warehouse.id)}</div>
    ${warehouse.location ? `<div class="company-row">${escapeHtml(warehouse.location)}</div>` : ''}
    <div class="divider"></div>
    <div class="shelf-name">${escapeHtml(shelf.name)}</div>
    <div class="shelf-ref">${escapeHtml(shelf.shelfNumber || shelf.id)}</div>
    ${shelf.notes ? `<div class="company-row" style="margin-top:4px;">${escapeHtml(shelf.notes)}</div>` : ''}
    ${qrDataUrl ? `
    <div class="qr-block">
      <img src="${qrDataUrl}" alt="QR" />
      <div class="qr-caption">${escapeHtml(shelf.shelfNumber || shelf.id)}</div>
    </div>` : ''}
  </div>
  <script>window.onload=function(){window.print();window.onafterprint=function(){window.close();};};<\/script>
</body>
</html>`;

    printWindow.document.write(labelHtml);
    printWindow.document.close();
  };

  return (
    <>
      <Button
        type="button"
        variant="outline"
        size="icon"
        title={t?.printLabelButton ?? 'طباعة بطاقة الرف'}
        onClick={() => setOpen(true)}
      >
        <Printer className="h-4 w-4" />
      </Button>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-sm" dir="rtl">
          <DialogHeader>
            <DialogTitle>{t?.shelfLabelPreviewTitle ?? 'معاينة بطاقة الرف'}</DialogTitle>
            <DialogDescription className="sr-only">{t?.shelfLabelPreviewDescription ?? 'معاينة بطاقة الرف قبل الطباعة.'}</DialogDescription>
          </DialogHeader>

          {/* Preview */}
          <div className="border-2 border-black rounded-lg p-4 space-y-1 text-sm bg-white" dir="rtl">
            <div className="font-bold text-base">{warehouse.name}</div>
            <div className="font-mono text-xs text-muted-foreground">{warehouse.warehouseNumber || warehouse.id}</div>
            {warehouse.location && <div className="text-xs text-muted-foreground">{warehouse.location}</div>}
            <hr className="border-dashed my-2" />
            <div className="font-bold text-lg">{shelf.name}</div>
            <div className="font-mono text-xs">{shelf.shelfNumber || shelf.id}</div>
            {shelf.notes && <div className="text-xs text-muted-foreground">{shelf.notes}</div>}
            {qrDataUrl && (
              <div className="flex justify-center mt-2">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={qrDataUrl} alt="QR" className="w-28 h-28" ref={canvasRef as any} />
              </div>
            )}
            {!qrDataUrl && (
              <div className="flex justify-center mt-2">
                <div className="w-28 h-28 border rounded flex items-center justify-center text-xs text-muted-foreground">
                  {t?.generatingQr ?? 'جاري التوليد...'}
                </div>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setOpen(false)}>
              {tGlobal?.close ?? 'إغلاق'}
            </Button>
            <Button type="button" onClick={handlePrint} disabled={!qrDataUrl}>
              <Printer className="h-4 w-4 ml-2" />
              {t?.printButton ?? 'طباعة'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}

function escapeHtml(unsafe: string): string {
  return String(unsafe ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
