import { useEffect, useRef, useState } from 'react';
import { Html5Qrcode } from 'html5-qrcode';

interface QRScannerProps {
  onScan: (result: string) => void;
  onError?: (error: string) => void;
  onClose: () => void;
}

/**
 * QR Scanner component using device camera.
 *
 * Supports both rear and front cameras. On desktop, will use webcam.
 * On mobile, defaults to rear camera for easier scanning.
 */
export function QRScanner({ onScan, onError, onClose }: QRScannerProps) {
  const scannerRef = useRef<Html5Qrcode | null>(null);
  const [isStarting, setIsStarting] = useState(true);
  const [permissionDenied, setPermissionDenied] = useState(false);

  useEffect(() => {
    const scannerId = 'qr-reader';
    let mounted = true;

    const startScanner = async () => {
      try {
        const scanner = new Html5Qrcode(scannerId);
        scannerRef.current = scanner;

        await scanner.start(
          { facingMode: 'environment' },
          {
            fps: 10,
            qrbox: { width: 250, height: 250 },
            aspectRatio: 1,
          },
          (decodedText) => {
            // Successfully scanned
            scanner.stop().catch(() => {});
            onScan(decodedText);
          },
          () => {
            // Scan error (ignore - just means no QR found in frame)
          }
        );

        if (mounted) {
          setIsStarting(false);
        }
      } catch (err) {
        if (mounted) {
          setIsStarting(false);
          if (err instanceof Error && err.message.includes('Permission')) {
            setPermissionDenied(true);
          }
          onError?.(err instanceof Error ? err.message : 'Camera error');
        }
      }
    };

    startScanner();

    return () => {
      mounted = false;
      if (scannerRef.current) {
        scannerRef.current.stop().catch(() => {});
      }
    };
  }, [onScan, onError]);

  return (
    <div className="fixed inset-0 z-50 bg-black/90 flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between p-4 bg-black/50">
        <h2 className="text-lg font-semibold">Scan QR Code</h2>
        <button
          onClick={onClose}
          className="p-2 hover:bg-slate-800 rounded-lg transition-colors"
          aria-label="Close scanner"
        >
          <svg
            className="w-6 h-6"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>
      </div>

      {/* Scanner area */}
      <div className="flex-1 flex items-center justify-center p-4">
        <div className="relative w-full max-w-sm">
          {isStarting && !permissionDenied && (
            <div className="absolute inset-0 flex items-center justify-center bg-slate-900 rounded-lg">
              <div className="text-center">
                <div className="animate-spin w-8 h-8 border-2 border-synor-400 border-t-transparent rounded-full mx-auto mb-2" />
                <p className="text-slate-400">Starting camera...</p>
              </div>
            </div>
          )}

          {permissionDenied && (
            <div className="absolute inset-0 flex items-center justify-center bg-slate-900 rounded-lg p-6">
              <div className="text-center">
                <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-red-900/50 flex items-center justify-center">
                  <svg
                    className="w-8 h-8 text-red-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"
                    />
                  </svg>
                </div>
                <h3 className="text-lg font-semibold mb-2">Camera Access Denied</h3>
                <p className="text-slate-400 text-sm mb-4">
                  Please allow camera access in your browser settings to scan QR codes.
                </p>
                <button onClick={onClose} className="btn btn-secondary">
                  Close
                </button>
              </div>
            </div>
          )}

          <div
            id="qr-reader"
            className="w-full aspect-square rounded-lg overflow-hidden"
          />

          {/* Scan guide overlay */}
          {!isStarting && !permissionDenied && (
            <div className="absolute inset-0 pointer-events-none">
              <div className="absolute inset-0 border-2 border-synor-400/30 rounded-lg" />
              <div className="absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-synor-400 rounded-tl-lg" />
              <div className="absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-synor-400 rounded-tr-lg" />
              <div className="absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-synor-400 rounded-bl-lg" />
              <div className="absolute bottom-0 right-0 w-8 h-8 border-b-4 border-r-4 border-synor-400 rounded-br-lg" />
            </div>
          )}
        </div>
      </div>

      {/* Instructions */}
      <div className="p-4 text-center bg-black/50">
        <p className="text-slate-400 text-sm">
          Point your camera at a Synor address QR code
        </p>
      </div>
    </div>
  );
}
