'use client';

import { useEffect, useRef, useState } from 'react';
import { Html5Qrcode, Html5QrcodeSupportedFormats } from 'html5-qrcode';
import { Camera, X, Loader2, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useTranslation } from '@/hooks/useTranslation';

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

export function QRScanner({ onScan, onClose }: QRScannerProps) {
  const { t, locale } = useTranslation();
  const scannerRef = useRef<Html5Qrcode | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [cameras, setCameras] = useState<{ id: string; label: string }[]>([]);
  const [selectedCameraId, setSelectedCameraId] = useState<string>('');
  const [isScanning, setIsScanning] = useState(false);

  useEffect(() => {
    const initScanner = async () => {
      try {
        // 创建扫描器实例
        const scanner = new Html5Qrcode('qr-reader', {
          formatsToSupport: [Html5QrcodeSupportedFormats.QR_CODE],
          verbose: false,
        });
        scannerRef.current = scanner;

        // 获取摄像头列表
        const devices = await Html5Qrcode.getCameras();
        
        if (devices && devices.length > 0) {
          const cameraList = devices.map(device => ({
            id: device.id,
            label: device.label || `Camera ${devices.indexOf(device) + 1}`,
          }));
          setCameras(cameraList);

          // 优先选择后置摄像头（移动端）
          const backCamera = devices.find(device =>
            device.label?.toLowerCase().includes('back') ||
            device.label?.toLowerCase().includes('rear') ||
            device.label?.toLowerCase().includes('后')
          );
          const defaultCameraId = backCamera?.id || devices[0].id;
          setSelectedCameraId(defaultCameraId);

          // 开始扫描
          await startScanning(scanner, defaultCameraId);
        } else {
          setError(locale === 'zh' ? '此设备未找到摄像头' : 'No camera found on this device');
          setIsLoading(false);
        }
      } catch (err: any) {
        console.error('Scanner init error:', err);
        let errorMsg = err.message || (locale === 'zh' ? '无法初始化摄像头' : 'Failed to initialize camera');
        
        // 特殊处理安全上下文错误
        if (err.message && err.message.includes('secure context')) {
          errorMsg = locale === 'zh' 
            ? '摄像头访问需要 HTTPS 或 localhost 环境。请使用文件上传功能作为替代。'
            : 'Camera access requires HTTPS or localhost. Please use file upload as an alternative.';
        }
        
        setError(errorMsg);
        setIsLoading(false);
      }
    };

    initScanner();

    // 清理函数
    return () => {
      if (scannerRef.current && isScanning) {
        scannerRef.current.stop().catch(console.error);
      }
    };
  }, []);

  const startScanning = async (scanner: Html5Qrcode, cameraId: string) => {
    setIsLoading(true);
    setError(null);

    try {
      // 检测是否为移动设备
      const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
      
      await scanner.start(
        cameraId,
        {
          fps: isMobile ? 5 : 10, // 移动端降低帧率以提高性能
          qrbox: isMobile 
            ? { width: Math.min(250, window.innerWidth - 40), height: Math.min(250, window.innerWidth - 40) }
            : { width: 250, height: 250 },
          aspectRatio: 1.0,
        },
        (decodedText) => {
          // 扫描成功
          console.log('QR Code detected:', decodedText);
          onScan(decodedText);
          // 停止扫描
          if (scannerRef.current) {
            scannerRef.current.stop().catch(console.error);
          }
        },
        (errorMessage) => {
          // 扫描失败（正常情况，没找到二维码）
          // 不需要处理，继续扫描
        }
      );
      setIsScanning(true);
      setIsLoading(false);
    } catch (err: any) {
      console.error('Start scanning error:', err);
      let errorMsg = locale === 'zh' ? '无法启动摄像头' : 'Failed to start camera';
      
      if (err.name === 'NotAllowedError') {
        errorMsg = locale === 'zh' 
          ? '摄像头权限被拒绝，请允许访问摄像头' 
          : 'Camera permission denied. Please allow camera access.';
      } else if (err.name === 'NotFoundError') {
        errorMsg = locale === 'zh' ? '此设备未找到摄像头' : 'No camera found on this device';
      } else if (err.name === 'NotReadableError') {
        errorMsg = locale === 'zh' 
          ? '摄像头正在被其他应用使用' 
          : 'Camera is already in use by another application';
      } else if (err.message) {
        errorMsg = err.message;
      }
      
      setError(errorMsg);
      setIsLoading(false);
    }
  };

  const handleCameraChange = async (cameraId: string) => {
    if (!scannerRef.current) return;

    setSelectedCameraId(cameraId);
    
    try {
      if (isScanning) {
        await scannerRef.current.stop();
        setIsScanning(false);
      }
      await startScanning(scannerRef.current, cameraId);
    } catch (err) {
      console.error('Camera change error:', err);
    }
  };

  const handleClose = async () => {
    if (scannerRef.current && isScanning) {
      try {
        await scannerRef.current.stop();
      } catch (err) {
        console.error('Stop scanner error:', err);
      }
    }
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/95 backdrop-blur-sm flex items-center justify-center p-4">
      <div className="relative w-full max-w-2xl bg-white rounded-lg overflow-hidden shadow-2xl">
        {/* 头部 */}
        <div className="flex items-center justify-between p-4 border-b bg-gradient-to-r from-blue-600 to-blue-700">
          <div className="flex items-center gap-2 text-white">
            <Camera className="w-5 h-5" />
            <h2 className="text-lg font-semibold">{locale === 'zh' ? '扫描二维码' : 'Scan QR Code'}</h2>
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={handleClose}
            className="text-white hover:bg-white/20"
          >
            <X className="w-5 h-5" />
          </Button>
        </div>

        {/* 扫描区域 */}
        <div className="relative bg-black">
          {/* html5-qrcode 渲染容器 */}
          <div id="qr-reader" className="w-full"></div>

          {/* 加载状态 */}
          {isLoading && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/50">
              <div className="text-center text-white">
                <Loader2 className="w-12 h-12 mx-auto mb-3 animate-spin" />
                <p className="text-base">{locale === 'zh' ? '启动摄像头...' : 'Starting camera...'}</p>
              </div>
            </div>
          )}

          {/* 错误状态 */}
          {error && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/90 p-6">
              <div className="text-center text-white max-w-md">
                <AlertCircle className="w-16 h-16 mx-auto mb-4 text-red-400" />
                <p className="text-lg font-semibold mb-3">{locale === 'zh' ? '摄像头错误' : 'Camera Error'}</p>
                <p className="text-sm text-gray-300 mb-6 leading-relaxed">{error}</p>
                <div className="space-y-3">
                  <Button
                    onClick={handleClose}
                    variant="outline"
                    className="w-full text-white border-white hover:bg-white/20"
                  >
                    {locale === 'zh' ? '关闭' : 'Close'}
                  </Button>
                  {(error?.includes('permission') || error?.includes('权限')) && (
                    <p className="text-xs text-gray-400">
                      {locale === 'zh' 
                        ? '请检查浏览器设置并允许访问摄像头' 
                        : 'Please check your browser settings and allow camera access'}
                    </p>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 底部控制栏 */}
        <div className="p-4 bg-gray-50 border-t space-y-3">
          {/* 摄像头选择 */}
          {cameras.length > 1 && !error && (
            <div className="flex items-center gap-3">
              <label className="text-sm font-medium text-gray-700 whitespace-nowrap">
                {locale === 'zh' ? '摄像头:' : 'Camera:'}
              </label>
              <select
                value={selectedCameraId}
                onChange={(e) => handleCameraChange(e.target.value)}
                className="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
                disabled={isLoading}
              >
                {cameras.map((camera) => (
                  <option key={camera.id} value={camera.id}>
                    {camera.label}
                  </option>
                ))}
              </select>
            </div>
          )}
          
          {/* 提示文本 */}
          <p className="text-xs text-center text-gray-500">
            {isLoading
              ? (locale === 'zh' ? '正在初始化摄像头...' : 'Initializing camera...')
              : error
              ? (locale === 'zh' ? '摄像头不可用' : 'Camera unavailable')
              : (locale === 'zh' ? '将二维码放入框内进行扫描' : 'Position the QR code within the frame to scan')}
          </p>
        </div>
      </div>
    </div>
  );
}
