import { QRCodeSVG } from 'qrcode.react';

interface QRCodeProps {
  value: string;
  size?: number;
  includeMargin?: boolean;
  level?: 'L' | 'M' | 'Q' | 'H';
  className?: string;
}

/**
 * QR Code display component using SVG rendering.
 *
 * For Synor wallet addresses, the QR code encodes the full address
 * in the format: synor:<bech32-address>
 *
 * Error correction levels:
 * - L: ~7% recovery
 * - M: ~15% recovery (default)
 * - Q: ~25% recovery
 * - H: ~30% recovery (recommended for addresses)
 */
export function QRCode({
  value,
  size = 200,
  includeMargin = true,
  level = 'H',
  className = '',
}: QRCodeProps) {
  return (
    <div className={`bg-white p-4 rounded-lg inline-block ${className}`}>
      <QRCodeSVG
        value={value}
        size={size}
        level={level}
        includeMargin={includeMargin}
        bgColor="#ffffff"
        fgColor="#000000"
      />
    </div>
  );
}

/**
 * Generate a Synor payment URI for QR codes.
 * Format: synor:<address>?amount=<amount>&label=<label>&message=<message>
 */
export function createPaymentUri(
  address: string,
  options?: {
    amount?: string;
    label?: string;
    message?: string;
  }
): string {
  const params = new URLSearchParams();

  if (options?.amount) {
    params.set('amount', options.amount);
  }
  if (options?.label) {
    params.set('label', options.label);
  }
  if (options?.message) {
    params.set('message', options.message);
  }

  const queryString = params.toString();
  return queryString ? `${address}?${queryString}` : address;
}

/**
 * Parse a Synor payment URI from a QR code scan.
 */
export function parsePaymentUri(uri: string): {
  address: string;
  amount?: string;
  label?: string;
  message?: string;
} | null {
  // Handle both plain addresses and URIs with parameters
  if (!uri.startsWith('synor:')) {
    return null;
  }

  const [addressPart, queryPart] = uri.split('?');
  const address = addressPart;

  if (!queryPart) {
    return { address };
  }

  const params = new URLSearchParams(queryPart);
  return {
    address,
    amount: params.get('amount') || undefined,
    label: params.get('label') || undefined,
    message: params.get('message') || undefined,
  };
}
