/**
 * KRA - QR Code Upload Component
 * Generates QR code for mobile scan upload
 */

import React, { useState, useCallback } from 'react';
import { Modal, Button } from 'antd';
import { MobileOutlined } from '@ant-design/icons';
import QRCode from 'react-qr-code';
import { useToken } from '@/models';

interface QRCodeUploadProps {
  /** Class ID for file categorization */
  classId?: number;
  /** Callback when upload finishes */
  onSuccess?: (url?: string) => void;
  /** Button text */
  buttonText?: string;
  /** Logo URL to display in QR code center */
  logoUrl?: string;
}

const QRCodeUpload: React.FC<QRCodeUploadProps> = ({
  classId = 0,
  onSuccess,
  buttonText = '扫码上传',
  logoUrl,
}) => {
  const token = useToken();
  const [visible, setVisible] = useState(false);
  const [codeUrl, setCodeUrl] = useState('');

  // Generate QR code URL
  const createQrCode = useCallback(() => {
    const { protocol, host } = window.location;
    const url = `${protocol}//${host}/#/scanUpload?id=${classId}&token=${token}&t=${Date.now()}`;
    setCodeUrl(url);
    setVisible(true);
  }, [classId, token]);

  // Handle finish
  const handleFinish = () => {
    setVisible(false);
    setCodeUrl('');
    onSuccess?.();
  };

  // Handle cancel
  const handleCancel = () => {
    setVisible(false);
    setCodeUrl('');
  };

  return (
    <>
      <Button type="primary" icon={<MobileOutlined />} onClick={createQrCode}>
        {buttonText}
      </Button>

      <Modal
        title="扫码上传"
        open={visible}
        width={360}
        onCancel={handleCancel}
        footer={[
          <Button key="cancel" onClick={handleCancel}>
            取消
          </Button>,
          <Button key="finish" type="primary" onClick={handleFinish}>
            完成上传
          </Button>,
        ]}
        centered
      >
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            padding: 20,
          }}
        >
          <div
            style={{
              padding: 16,
              backgroundColor: '#fff',
              borderRadius: 8,
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
            }}
          >
            {codeUrl && (
              <QRCode
                value={codeUrl}
                size={256}
                level="M"
                fgColor="#52c41a"
                bgColor="#ffffff"
              />
            )}
          </div>
          <div
            style={{
              marginTop: 16,
              color: '#666',
              fontSize: 14,
              textAlign: 'center',
            }}
          >
            请使用手机扫描二维码上传文件
          </div>
        </div>
      </Modal>
    </>
  );
};

export default QRCodeUpload;
