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';
import { MachineryRecord } from '../../types/machinery';

interface QRCodeDialogProps {
  open: boolean;
  onClose: () => void;
  machinery: MachineryRecord | null;
}

export function QRCodeDialog({ open, onClose, machinery }: QRCodeDialogProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    if (machinery && canvasRef.current) {
      QRCode.toCanvas(canvasRef.current, machinery.qrCode, {
        width: 300,
        margin: 2,
      });
    }
  }, [machinery]);

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

  const handlePrint = () => {
    if (canvasRef.current && machinery) {
      const printWindow = window.open('', '_blank');
      if (printWindow) {
        const url = canvasRef.current.toDataURL('image/png');
        printWindow.document.write(`
          <html>
            <head>
              <title>打印二维码 - ${machinery.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;
                }
              </style>
            </head>
            <body>
              <img src="${url}" alt="QR Code" />
              <div class="info">
                <h2>${machinery.name}</h2>
                <p>型号: ${machinery.model}</p>
                <p>发动机号: ${machinery.engineNumber}</p>
                <p>车架号: ${machinery.chassisNumber}</p>
              </div>
              <script>
                window.onload = function() {
                  window.print();
                  window.onafterprint = function() {
                    window.close();
                  }
                }
              </script>
            </body>
          </html>
        `);
        printWindow.document.close();
      }
    }
  };

  if (!machinery) 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} />
          </div>

          <div className="text-center space-y-1">
            <p>{machinery.name}</p>
            <p className="text-sm text-muted-foreground">{machinery.model}</p>
            <p className="text-sm text-muted-foreground">
              发动机号: {machinery.engineNumber}
            </p>
          </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>
      </DialogContent>
    </Dialog>
  );
}
