import React, { useState, useEffect, useRef } from 'react';
import { Html5Qrcode } from 'html5-qrcode';
import { X, Camera, Barcode, AlertTriangle, Check, RefreshCw, SwitchCamera } from 'lucide-react';

interface Props {
  isOpen: boolean;
  onClose: () => void;
  onScanSuccess: (scannedBarcode: string) => void;
  title?: string;
}

export const CameraBarcodeScannerModal: React.FC<Props> = ({
  isOpen,
  onClose,
  onScanSuccess,
  title = 'Scan Barcode / SKU dengan Kamera'
}) => {
  const [cameraError, setCameraError] = useState<string | null>(null);
  const [isScanning, setIsScanning] = useState(false);
  const [lastScanned, setLastScanned] = useState<string | null>(null);
  const [facingMode, setFacingMode] = useState<'environment' | 'user'>('environment');

  const isScanningRef = useRef(false);
  const isTransitioningRef = useRef(false);
  const timeoutRef = useRef<any>(null);
  const html5QrcodeRef = useRef<Html5Qrcode | null>(null);

  const playBeep = () => {
    try {
      const audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      osc.type = 'sine';
      osc.frequency.setValueAtTime(880, audioCtx.currentTime);
      gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
      osc.connect(gain);
      gain.connect(audioCtx.destination);
      osc.start();
      osc.stop(audioCtx.currentTime + 0.15);
    } catch (e) {
      // Audio context fallback
    }
  };

  const stopCamera = async () => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    const scanner = html5QrcodeRef.current;
    html5QrcodeRef.current = null;

    if (scanner) {
      try {
        if (scanner.isScanning) {
          await scanner.stop();
        }
      } catch (err) {
        console.warn("Failed to stop camera:", err);
      }
      try {
        scanner.clear();
      } catch (e) {
        // Ignore clear errors
      }
    }
    setIsScanning(false);
  };

  useEffect(() => {
    if (isOpen) {
      setCameraError(null);
      setLastScanned(null);
      startCamera('environment');
    } else {
      stopCamera();
    }
    return () => {
      stopCamera();
    };
  }, [isOpen]);

  const startCamera = async (mode: 'environment' | 'user' = facingMode) => {
    if (isTransitioningRef.current) return;
    isTransitioningRef.current = true;

    setIsScanning(true);
    setCameraError(null);

    await stopCamera();

    // Check secure context and mediaDevices API availability
    if (typeof window !== 'undefined' && !window.isSecureContext && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
      setCameraError("Kamera memerlukan koneksi HTTPS aman. Mohon buka aplikasi menggunakan URL https://");
      setIsScanning(false);
      isTransitioningRef.current = false;
      return;
    }

    if (!navigator?.mediaDevices?.getUserMedia) {
      setCameraError("Browser Anda tidak mendukung akses kamera. Mohon gunakan browser Chrome / Safari versi terbaru.");
      setIsScanning(false);
      isTransitioningRef.current = false;
      return;
    }

    timeoutRef.current = setTimeout(async () => {
      try {
        const readerEl = document.getElementById("product-form-reader");
        if (!readerEl) {
          setIsScanning(false);
          isTransitioningRef.current = false;
          return;
        }

        const scanConfig = {
          fps: 10,
          qrbox: (viewfinderWidth: number, viewfinderHeight: number) => {
            const width = Math.min(viewfinderWidth * 0.85, 360);
            const height = Math.min(viewfinderHeight * 0.65, 220);
            return { width: Math.max(width, 220), height: Math.max(height, 140) };
          },
          aspectRatio: 1.333333,
          experimentalFeatures: {
            useBarCodeDetectorIfSupported: true
          }
        };

        const onSuccess = (decodedText: string) => {
          playBeep();
          setLastScanned(decodedText);
          onScanSuccess(decodedText);
          stopCamera();
          onClose();
        };

        const constraintsList = [
          {
            facingMode: mode,
            width: { ideal: 640, max: 1280 },
            height: { ideal: 480, max: 720 },
            frameRate: { ideal: 15, max: 20 }
          },
          { facingMode: mode },
          { facingMode: { exact: mode } }
        ];

        let startedSuccessfully = false;

        for (const constraint of constraintsList) {
          try {
            readerEl.innerHTML = "";
            const instance = new Html5Qrcode("product-form-reader");
            await instance.start(constraint, scanConfig, onSuccess, () => {});
            html5QrcodeRef.current = instance;
            startedSuccessfully = true;
            break;
          } catch (e: any) {
            console.warn("Constraint attempt failed, trying fallback...", e);
            readerEl.innerHTML = "";
          }
        }

        if (!startedSuccessfully) {
          throw new Error("Kamera tidak dapat diakses. Mohon izinkan akses kamera pada browser / tablet Anda.");
        }
      } catch (err: any) {
        console.error("Camera scanner error:", err);
        setCameraError(
          err?.message || "Kamera tidak dapat diakses. Mohon izinkan akses kamera pada browser / tablet Anda."
        );
        setIsScanning(false);
      } finally {
        isTransitioningRef.current = false;
      }
    }, 150);
  };

  const handleToggleCameraMode = () => {
    const nextMode = facingMode === 'environment' ? 'user' : 'environment';
    setFacingMode(nextMode);
    startCamera(nextMode);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[70] flex items-center justify-center bg-slate-900/75 backdrop-blur-sm p-2 sm:p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl md:max-w-3xl border border-slate-100 overflow-hidden my-auto max-h-[95vh] flex flex-col animate-in fade-in zoom-in-95 duration-150">
        
        {/* Header */}
        <div className="bg-gradient-to-r from-emerald-600 to-teal-700 text-white px-4 sm:px-6 py-3.5 flex items-center justify-between shrink-0">
          <div className="flex items-center gap-2.5">
            <div className="p-2 bg-white/20 rounded-xl">
              <Camera className="w-5 h-5 text-white" />
            </div>
            <div>
              <h4 className="font-bold text-sm sm:text-base leading-tight">{title}</h4>
              <p className="text-emerald-100 text-[11px] sm:text-xs">
                Mendukung Kamera Depan & Belakang — Pemindaian Barcode Cepat & Responsif
              </p>
            </div>
          </div>
          <button
            onClick={() => {
              stopCamera();
              onClose();
            }}
            className="p-1.5 rounded-lg hover:bg-white/20 text-white transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-4 sm:p-6 space-y-4 text-center overflow-y-auto flex-1">
          {/* Controls Bar for Camera Switch */}
          <div className="flex items-center justify-between bg-slate-50 p-2.5 rounded-xl border border-slate-200 text-xs">
            <div className="flex items-center gap-2 font-semibold text-slate-700">
              <span>Posisi Kamera:</span>
              <button
                type="button"
                onClick={handleToggleCameraMode}
                className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg flex items-center gap-1.5 transition shadow-xs"
                title="Ganti Kamera Depan / Belakang"
              >
                <SwitchCamera className="w-4 h-4" />
                <span>{facingMode === 'environment' ? 'Kamera Belakang (Rear)' : 'Kamera Depan (Front / Selfie)'}</span>
              </button>
            </div>
            <button
              type="button"
              onClick={() => startCamera(facingMode)}
              className="px-3 py-1.5 bg-slate-200 hover:bg-slate-300 text-slate-700 font-bold rounded-lg flex items-center gap-1 transition"
            >
              <RefreshCw className="w-3.5 h-3.5" /> Muat Ulang
            </button>
          </div>

          {cameraError && (
            <div className="p-4 bg-amber-50 border border-amber-200 rounded-xl space-y-2 text-amber-800 text-xs text-left">
              <div className="flex items-center gap-1.5 font-bold text-amber-900">
                <AlertTriangle className="w-4 h-4 text-amber-600" />
                <span>Akses Kamera Diblokir / Gagal</span>
              </div>
              <p>{cameraError}</p>
              <button
                type="button"
                onClick={() => startCamera(facingMode)}
                className="mt-2 px-3 py-1.5 bg-amber-600 text-white font-semibold rounded-lg text-xs hover:bg-amber-700 transition"
              >
                Coba Buka Kamera Lagi
              </button>
            </div>
          )}

          <div className="space-y-3">
            <div className="border-2 border-dashed border-emerald-400 bg-slate-900 rounded-2xl p-3 text-center">
              <p className="text-emerald-300 text-xs font-semibold flex items-center justify-center gap-1.5 mb-3">
                <span className="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-ping"></span>
                Arahkan barcode ke kotak pemindai kamera...
              </p>
              {/* Responsive Viewport for Tablet Landscape */}
              <div id="product-form-reader" className="w-full max-w-xl mx-auto overflow-hidden rounded-xl bg-black min-h-[220px]"></div>
            </div>

            {lastScanned && (
              <div className="p-3 bg-emerald-50 border border-emerald-200 rounded-xl text-xs sm:text-sm font-bold text-emerald-900 flex items-center justify-center gap-2">
                <Check className="w-5 h-5 text-emerald-600" />
                <span>Terdeteksi: <span className="font-mono text-emerald-800">{lastScanned}</span></span>
              </div>
            )}
          </div>

          <div className="flex justify-end pt-2">
            <button
              type="button"
              onClick={() => {
                stopCamera();
                onClose();
              }}
              className="px-5 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold text-xs sm:text-sm rounded-xl transition"
            >
              Batal
            </button>
          </div>
        </div>

      </div>
    </div>
  );
};
