import { useState, useRef } from 'react';
import { Modal, Button, Space, Input, message, Spin } from 'antd';
import { DownloadOutlined, CopyOutlined, CheckOutlined } from '@ant-design/icons';

interface QrCodeModalProps {
  open: boolean;
  onClose: () => void;
  url: string;
  title: string;
}

export default function QrCodeModal({ open, onClose, url, title }: QrCodeModalProps) {
  const [copied, setCopied] = useState(false);
  const [loading, setLoading] = useState(true);
  const imgRef = useRef<HTMLImageElement>(null);

  const qrSrc = `/api/qr?text=${encodeURIComponent(url)}&size=300`;

  const handleDownload = () => {
    const img = imgRef.current;
    if (!img) return;

    const canvas = document.createElement('canvas');
    canvas.width = img.naturalWidth;
    canvas.height = img.naturalHeight;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    ctx.drawImage(img, 0, 0);

    const link = document.createElement('a');
    link.download = `qr-${title.toLowerCase().replace(/[^a-z0-9]+/g, '-')}.png`;
    link.href = canvas.toDataURL('image/png');
    link.click();
  };

  const handleCopyUrl = () => {
    navigator.clipboard.writeText(url);
    setCopied(true);
    message.success('URL copied');
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <Modal
      title={`QR Code: ${title}`}
      open={open}
      onCancel={onClose}
      footer={null}
      width={400}
      destroyOnHidden
    >
      <div style={{ textAlign: 'center', padding: '16px 0' }}>
        {loading && <Spin style={{ display: 'block', marginBottom: 16 }} />}
        <img
          ref={imgRef}
          src={qrSrc}
          alt={`QR code for ${title}`}
          crossOrigin="anonymous"
          style={{ width: 300, height: 300, display: loading ? 'none' : 'block', margin: '0 auto' }}
          onLoad={() => setLoading(false)}
          onError={() => { setLoading(false); message.error('Failed to generate QR code'); }}
        />
        <div style={{ marginTop: 16 }}>
          <Input
            value={url}
            readOnly
            style={{ marginBottom: 12, textAlign: 'center' }}
            addonAfter={
              <Button
                type="text"
                size="small"
                icon={copied ? <CheckOutlined /> : <CopyOutlined />}
                onClick={handleCopyUrl}
              />
            }
          />
          <Space>
            <Button icon={<DownloadOutlined />} type="primary" onClick={handleDownload}>
              Download PNG
            </Button>
            <Button icon={copied ? <CheckOutlined /> : <CopyOutlined />} onClick={handleCopyUrl}>
              Copy URL
            </Button>
          </Space>
        </div>
      </div>
    </Modal>
  );
}
