import { useEffect, useRef } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog';
import { Button } from '../ui/button';
import { Download, Printer } from 'lucide-react';
import QRCode from 'qrcode';

interface WarehouseLocation {
  id: string;
  code: string;
  name: string;
  warehouseId: string;
  warehouseName: string;
  status: '空闲' | '使用中' | '维护中' | '禁用';
  notes?: string;
}

interface LocationQRCodeDialogProps {
  open: boolean;
  onClose: () => void;
  location: WarehouseLocation | null;
}

export function LocationQRCodeDialog({ open, onClose, location }: LocationQRCodeDialogProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    if (location && canvasRef.current) {
      // 生成二维码内容，包含库位的关键信息
      const qrData = JSON.stringify({
        type: 'warehouse_location',
        id: location.id,
        code: location.code,
        name: location.name,
        warehouseId: location.warehouseId,
        warehouseName: location.warehouseName,
      });

      QRCode.toCanvas(canvasRef.current, qrData, {
        width: 300,
        margin: 2,
      });
    }
  }, [location]);

  const handleDownload = () => {
    if (canvasRef.current && location) {
      const url = canvasRef.current.toDataURL('image/png');
      const link = document.createElement('a');
      link.download = `库位-${location.code}-${location.name}-QRCode.png`;
      link.href = url;
      link.click();
    }
  };

  const handlePrint = () => {
    if (canvasRef.current && location) {
      const printWindow = window.open('', '_blank');
      if (printWindow) {
        const url = canvasRef.current.toDataURL('image/png');
        printWindow.document.write(`
          <html>
            <head>
              <title>打印库位二维码 - ${location.name}</title>
              <style>
                body {
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  margin: 20px;
                  font-family: sans-serif;
                }
                img {
                  max-width: 300px;
                }
                .info {
                  text-align: center;
                  margin-top: 20px;
                }
                .info h2 {
                  margin: 10px 0;
                  font-size: 24px;
                }
                .info p {
                  margin: 5px 0;
                  font-size: 14px;
                  color: #666;
                }
                .code {
                  font-size: 18px;
                  font-weight: bold;
                  color: #333;
                  margin: 10px 0;
                }
              </style>
            </head>
            <body>
              <img src="${url}" alt="库位二维码" />
              <div class="info">
                <div class="code">${location.code}</div>
                <h2>${location.name}</h2>
                <p>所属仓库: ${location.warehouseName}</p>
                <p>状态: ${location.status}</p>
                ${location.notes ? `<p>备注: ${location.notes}</p>` : ''}
              </div>
              <script>
                window.onload = function() {
                  window.print();
                  window.onafterprint = function() {
                    window.close();
                  }
                }
              </script>
            </body>
          </html>
        `);
        printWindow.document.close();
      }
    }
  };

  if (!location) return null;

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>库位二维码</DialogTitle>
          <DialogDescription className="sr-only">
            查看和下载库位二维码，用于库位标识和扫码查询
          </DialogDescription>
        </DialogHeader>

        <div className="flex flex-col items-center space-y-4">
          <div className="border rounded-lg p-4 bg-white">
            <canvas ref={canvasRef} width={300} height={300} />
          </div>

          <div className="text-center space-y-1">
            <p className="font-mono text-sm text-muted-foreground">{location.code}</p>
            <p className="font-medium">{location.name}</p>
            <p className="text-sm text-muted-foreground">{location.warehouseName}</p>
            <div className="mt-2">
              <span className={`inline-flex px-2 py-1 rounded text-xs ${
                location.status === '使用中' ? 'bg-green-100 text-green-800' :
                location.status === '空闲' ? 'bg-gray-100 text-gray-800' :
                location.status === '维护中' ? 'bg-orange-100 text-orange-800' :
                'bg-red-100 text-red-800'
              }`}>
                {location.status}
              </span>
            </div>
          </div>

          <div className="flex gap-2 w-full">
            <Button variant="outline" className="flex-1" onClick={handleDownload}>
              <Download className="w-4 h-4 mr-2" />
              下载
            </Button>
            <Button variant="outline" className="flex-1" onClick={handlePrint}>
              <Printer className="w-4 h-4 mr-2" />
              打印
            </Button>
          </div>

          <div className="text-xs text-muted-foreground text-center">
            <p>扫描此二维码可快速查询库位信息</p>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
