import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Html5Qrcode } from 'html5-qrcode';
import { useStore } from '../context/StoreContext';
import { X, Camera, Barcode, Search, AlertTriangle, CheckCircle, Plus, ShoppingCart, Tag, ShieldAlert, SwitchCamera, RefreshCw, ChevronRight } from 'lucide-react';

interface Props {
  isOpen: boolean;
  onClose: () => void;
  onSelectVariantForPos?: (variantId: string, productId: string) => void;
}

export const BarcodeScannerModal: React.FC<Props> = ({ isOpen, onClose, onSelectVariantForPos }) => {
  const { db, findVariantByBarcode, priceCheckBarcode, setPriceCheckBarcode, setActiveTab } = useStore();
  const [manualInput, setManualInput] = useState('');
  const [isCameraActive, setIsCameraActive] = useState(false);
  const [cameraError, setCameraError] = useState<string | null>(null);
  const [scannedBarcode, setScannedBarcode] = useState<string | null>(null);
  const [facingMode, setFacingMode] = useState<'environment' | 'user'>('environment');
  const [isSuggestOpen, setIsSuggestOpen] = useState(false);

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

  // Sound effect
  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); // A5 note
      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 fallback silent
    }
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (inputContainerRef.current && !inputContainerRef.current.contains(event.target as Node)) {
        setIsSuggestOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  useEffect(() => {
    if (isOpen) {
      if (priceCheckBarcode) {
        setManualInput(priceCheckBarcode);
        setScannedBarcode(priceCheckBarcode);
        setPriceCheckBarcode(null);
      }
    } else {
      stopCamera();
      setScannedBarcode(null);
      setManualInput('');
      setCameraError(null);
      setIsSuggestOpen(false);
    }
  }, [isOpen, priceCheckBarcode]);

  // Compute live search suggestions
  const suggestions = useMemo(() => {
    const query = manualInput.trim().toLowerCase();
    if (!query) return [];

    const list: Array<{
      productId: string;
      productName: string;
      variantId: string;
      variantName: string;
      barcode: string;
      category: string;
      sellPrice: number;
      stock: number;
      unit: string;
    }> = [];

    for (const p of db.products) {
      for (const v of p.variants) {
        if (
          p.name.toLowerCase().includes(query) ||
          v.variantName.toLowerCase().includes(query) ||
          v.barcode.toLowerCase().includes(query) ||
          p.category.toLowerCase().includes(query)
        ) {
          list.push({
            productId: p.id,
            productName: p.name,
            variantId: v.id,
            variantName: v.variantName,
            barcode: v.barcode,
            category: p.category,
            sellPrice: v.sellPrice,
            stock: v.stock,
            unit: v.unit
          });
        }
      }
    }
    return list.slice(0, 6);
  }, [db.products, manualInput]);

  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 DOM clear errors
      }
    }
    setIsCameraActive(false);
  };

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

    setCameraError(null);
    setIsCameraActive(true);
    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://");
      setIsCameraActive(false);
      isTransitioningRef.current = false;
      return;
    }

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

    timeoutRef.current = setTimeout(async () => {
      try {
        const readerEl = document.getElementById("reader");
        if (!readerEl) {
          setIsCameraActive(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();
          setScannedBarcode(decodedText);
          setManualInput(decodedText);

          // Auto-add to cart directly if callback provided and item found
          const matched = findVariantByBarcode(decodedText);
          if (matched && onSelectVariantForPos) {
            onSelectVariantForPos(matched.variant.id, matched.product.id);
            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("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 beri izin akses kamera di browser / tablet Anda.");
        }
      } catch (err: any) {
        console.error("Camera error:", err);
        setCameraError(err?.message || "Kamera tidak dapat diakses. Mohon beri izin akses kamera di browser / tablet Anda.");
        setIsCameraActive(false);
      } finally {
        isTransitioningRef.current = false;
      }
    }, 150);
  };

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

  if (!isOpen) return null;

  const currentBarcode = manualInput.trim() || scannedBarcode || '';
  const result = currentBarcode ? findVariantByBarcode(currentBarcode) : null;

  const handleManualSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setIsSuggestOpen(false);
    if (manualInput.trim()) {
      setScannedBarcode(manualInput.trim());
      const matched = findVariantByBarcode(manualInput.trim());
      if (matched && onSelectVariantForPos) {
        onSelectVariantForPos(matched.variant.id, matched.product.id);
        stopCamera();
        onClose();
      }
    }
  };

  const handleSelectSuggestion = (item: { barcode: string; productName: string; variantName: string; productId: string; variantId: string }) => {
    const searchVal = item.barcode || item.productName;
    setManualInput(searchVal);
    setScannedBarcode(searchVal);
    setIsSuggestOpen(false);
    playBeep();

    if (onSelectVariantForPos) {
      onSelectVariantForPos(item.variantId, item.productId);
      stopCamera();
      onClose();
    }
  };

  const handleQuickTestSample = (code: string) => {
    setManualInput(code);
    setScannedBarcode(code);
    playBeep();
  };

  const marginAmount = result ? result.variant.sellPrice - result.variant.buyPrice : 0;
  const marginPercentage = result && result.variant.buyPrice > 0 
    ? Math.round((marginAmount / result.variant.buyPrice) * 100)
    : 0;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-sm p-2 sm:p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl lg:max-w-4xl border border-slate-100 overflow-hidden my-auto max-h-[95vh] flex flex-col">
        
        {/* 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-1.5 sm:p-2 bg-white/20 rounded-lg">
              <Barcode className="w-5 h-5 sm:w-6 sm:h-6 text-white" />
            </div>
            <div>
              <h3 className="font-bold text-base sm:text-lg leading-tight">Pengecekan Harga Barcode</h3>
              <p className="text-emerald-100 text-[11px] sm:text-xs">
                Pindai kamera (Depan / Belakang) atau ketik kode barcode barang Toko Makmur
              </p>
            </div>
          </div>
          <button 
            onClick={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 sm:space-y-6 overflow-y-auto flex-1">
          
          {/* Manual Barcode Input & Camera Toggle */}
          <div className="space-y-3">
            <form onSubmit={handleManualSearch} className="flex gap-2">
              <div ref={inputContainerRef} className="relative flex-1">
                <Barcode className="w-5 h-5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                <input
                  type="text"
                  value={manualInput}
                  onFocus={() => setIsSuggestOpen(true)}
                  onChange={(e) => {
                    setManualInput(e.target.value);
                    setIsSuggestOpen(true);
                  }}
                  placeholder="Ketik atau tempel kode barcode / nama barang..."
                  className="w-full pl-10 pr-8 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white transition"
                />
                {manualInput && (
                  <button
                    type="button"
                    onClick={() => {
                      setManualInput('');
                      setIsSuggestOpen(false);
                    }}
                    className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5 rounded-full"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}

                {/* Live Auto-Suggest Menu */}
                {isSuggestOpen && manualInput.trim().length > 0 && (
                  <div className="absolute top-full left-0 right-0 mt-1.5 bg-white rounded-2xl shadow-2xl border border-slate-200 z-50 overflow-hidden text-xs py-1 animate-in fade-in zoom-in-95 duration-100">
                    <div className="px-3.5 py-2 bg-slate-50 border-b border-slate-100 text-[10px] font-bold text-slate-500 uppercase tracking-wider flex justify-between items-center">
                      <span>Rekomendasi Pencarian ({suggestions.length})</span>
                      <span className="text-[10px] font-normal text-slate-400">Klik untuk Pilih</span>
                    </div>

                    {suggestions.length === 0 ? (
                      <div className="p-4 text-center text-slate-400 italic text-xs">
                        Tidak ada barang yang cocok dengan "{manualInput}"
                      </div>
                    ) : (
                      <div className="max-h-60 overflow-y-auto divide-y divide-slate-100">
                        {suggestions.map((item) => (
                          <button
                            key={`${item.productId}-${item.variantId}`}
                            type="button"
                            onClick={() => handleSelectSuggestion(item)}
                            className="w-full text-left px-3.5 py-2.5 hover:bg-emerald-50 transition flex items-center justify-between gap-2 group"
                          >
                            <div className="min-w-0 flex-1">
                              <div className="font-bold text-slate-800 group-hover:text-emerald-800 text-xs truncate">
                                {item.productName} - {item.variantName}
                              </div>
                              <div className="flex items-center gap-2 mt-0.5 text-[10px] text-slate-400">
                                <span className="font-mono text-slate-500 font-semibold">
                                  {item.barcode ? `Barcode: ${item.barcode}` : 'Tanpa Barcode'}
                                </span>
                                <span>•</span>
                                <span>{item.category}</span>
                              </div>
                            </div>
                            <div className="text-right shrink-0">
                              <div className="font-extrabold text-emerald-700 text-xs">
                                Rp {item.sellPrice.toLocaleString('id-ID')}
                              </div>
                              <div className="text-[10px] text-slate-400">
                                Stok: <span className={item.stock > 0 ? "font-bold text-slate-700" : "font-bold text-rose-600"}>{item.stock} {item.unit}</span>
                              </div>
                            </div>
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                )}
              </div>
              <button
                type="submit"
                className="px-4 py-2.5 bg-slate-800 text-white text-sm font-medium rounded-xl hover:bg-slate-900 flex items-center gap-1.5 transition shrink-0"
              >
                <Search className="w-4 h-4" /> Cari
              </button>
            </form>

            <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-slate-500">
              <div className="flex items-center gap-1.5 flex-wrap">
                <span>Coba Barcode Contoh:</span>
                <button
                  type="button"
                  onClick={() => handleQuickTestSample('8996001600124')}
                  className="px-2 py-0.5 bg-emerald-50 text-emerald-700 rounded font-mono hover:bg-emerald-100 transition"
                >
                  Le Minerale 500ml
                </button>
                <button
                  type="button"
                  onClick={() => handleQuickTestSample('8996001600123')}
                  className="px-2 py-0.5 bg-emerald-50 text-emerald-700 rounded font-mono hover:bg-emerald-100 transition"
                >
                  Le Minerale 300ml
                </button>
              </div>

              {!isCameraActive ? (
                <button
                  onClick={() => startCamera()}
                  className="px-3.5 py-2 bg-emerald-600 text-white rounded-xl hover:bg-emerald-700 flex items-center gap-1.5 font-bold transition shadow-xs"
                >
                  <Camera className="w-4 h-4" /> Buka Kamera Scanner
                </button>
              ) : (
                <div className="flex items-center gap-2">
                  <button
                    onClick={handleToggleCameraMode}
                    className="px-3 py-1.5 bg-emerald-100 text-emerald-800 rounded-xl hover:bg-emerald-200 border border-emerald-300/80 flex items-center gap-1.5 font-bold transition"
                    title="Ganti Kamera Depan / Belakang"
                  >
                    <SwitchCamera className="w-3.5 h-3.5 text-emerald-700" />
                    <span>{facingMode === 'environment' ? 'Ke Kamera Depan' : 'Ke Kamera Belakang'}</span>
                  </button>

                  <button
                    onClick={stopCamera}
                    className="px-3 py-1.5 bg-rose-600 text-white rounded-xl hover:bg-rose-700 flex items-center gap-1 font-bold transition"
                  >
                    <X className="w-3.5 h-3.5" /> Tutup Kamera
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* Camera View Area */}
          <div className={isCameraActive ? "border-2 border-dashed border-emerald-400 bg-slate-900 rounded-2xl p-4 text-center space-y-3" : "hidden"}>
            <div className="flex items-center justify-between px-2 text-xs text-emerald-300">
              <span className="flex items-center gap-1.5 font-medium">
                <span className="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-ping"></span>
                Kamera Aktif ({facingMode === 'environment' ? 'Belakang / Rear' : 'Depan / Front'})
              </span>
            </div>

            {/* Large responsive camera feed for tablet landscape */}
            <div id="reader" className="w-full max-w-2xl mx-auto overflow-hidden rounded-xl bg-black min-h-[220px]"></div>
          </div>

          {cameraError && (
            <div className="p-3 bg-amber-50 border border-amber-200 rounded-xl flex items-start gap-2 text-amber-800 text-xs">
              <AlertTriangle className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
              <span>{cameraError}</span>
            </div>
          )}

          {/* SCAN RESULT PANEL */}
          {currentBarcode ? (
            result ? (
              <div className="bg-emerald-50/70 border border-emerald-200 rounded-2xl p-5 space-y-4">
                <div className="flex items-start justify-between">
                  <div>
                    <span className="inline-block px-2.5 py-0.5 bg-emerald-100 text-emerald-800 rounded-full text-xs font-semibold mb-1">
                      {result.product.category}
                    </span>
                    <h4 className="text-xl font-bold text-slate-900">{result.product.name}</h4>
                    <p className="text-sm font-medium text-emerald-700">
                      Varian: <span className="font-bold">{result.variant.variantName}</span> ({result.variant.size} {result.variant.unit})
                    </p>
                    <p className="text-xs text-slate-500 font-mono mt-0.5">Barcode: {result.variant.barcode}</p>
                  </div>

                  <div className="text-right">
                    <span className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold ${
                      result.variant.stock <= 0 
                        ? 'bg-rose-100 text-rose-700' 
                        : result.variant.stock <= result.variant.minStock
                        ? 'bg-amber-100 text-amber-800'
                        : 'bg-emerald-100 text-emerald-800'
                    }`}>
                      {result.variant.stock <= result.variant.minStock && <AlertTriangle className="w-3 h-3" />}
                      Stok: {result.variant.stock} {result.variant.unit}
                    </span>
                  </div>
                </div>

                {/* Price Cards Grid */}
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5 sm:gap-3 pt-2">
                  <div className="p-3 bg-white border border-slate-200 rounded-xl">
                    <span className="text-xs text-slate-500 block font-medium">Harga Beli (Modal)</span>
                    <span className="text-base font-bold text-slate-800">
                      Rp {result.variant.buyPrice.toLocaleString('id-ID')}
                    </span>
                  </div>

                  <div className="p-3 bg-emerald-600 text-white rounded-xl shadow-sm">
                    <span className="text-xs text-emerald-100 block font-medium">Harga Jual</span>
                    <span className="text-lg font-black">
                      Rp {result.variant.sellPrice.toLocaleString('id-ID')}
                    </span>
                  </div>

                  <div className="p-3 bg-white border border-slate-200 rounded-xl">
                    <span className="text-xs text-slate-500 block font-medium">Margin Keuntungan</span>
                    <span className="text-base font-bold text-teal-600 block">
                      +Rp {marginAmount.toLocaleString('id-ID')}
                    </span>
                    <span className="text-[10px] text-slate-400 font-semibold">({marginPercentage}% untung)</span>
                  </div>
                </div>

                {/* Action buttons */}
                <div className="flex gap-2 pt-2">
                  {onSelectVariantForPos && (
                    <button
                      onClick={() => {
                        onSelectVariantForPos(result.variant.id, result.product.id);
                        onClose();
                      }}
                      className="flex-1 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-sm rounded-xl flex items-center justify-center gap-2 shadow-sm transition"
                    >
                      <ShoppingCart className="w-4 h-4" /> Masukkan ke Kasir
                    </button>
                  )}
                  <button
                    onClick={() => {
                      onClose();
                      setActiveTab('products');
                    }}
                    className="px-4 py-2.5 bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 font-semibold text-sm rounded-xl transition"
                  >
                    Buka Katalog Produk
                  </button>
                </div>
              </div>
            ) : (
              <div className="bg-rose-50 border border-rose-200 rounded-2xl p-5 text-center space-y-3">
                <div className="w-10 h-10 bg-rose-100 rounded-full flex items-center justify-center mx-auto text-rose-600">
                  <ShieldAlert className="w-5 h-5" />
                </div>
                <div>
                  <h4 className="font-bold text-slate-900">Barang Tidak Ditemukan</h4>
                  <p className="text-xs text-slate-600 mt-1">
                    Kode barcode <span className="font-mono font-bold">{currentBarcode}</span> belum terdaftar di sistem Toko Makmur.
                  </p>
                </div>
                <button
                  onClick={() => {
                    onClose();
                    setActiveTab('products');
                  }}
                  className="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white font-medium text-xs rounded-xl inline-flex items-center gap-1.5 transition"
                >
                  <Plus className="w-4 h-4" /> Tambah Barang Baru
                </button>
              </div>
            )
          ) : (
            <div className="border border-slate-100 bg-slate-50/50 rounded-2xl p-6 text-center space-y-2">
              <div className="w-12 h-12 bg-emerald-100 text-emerald-700 rounded-full flex items-center justify-center mx-auto">
                <Tag className="w-6 h-6" />
              </div>
              <h4 className="font-semibold text-slate-800 text-sm">Siap Memindai Barcode</h4>
              <p className="text-xs text-slate-500 max-w-sm mx-auto">
                Gunakan kamera ponsel/tablet atau ketik kode barcode di atas untuk melihat rincian harga beli, harga jual, dan stok barang.
              </p>
            </div>
          )}

        </div>

        {/* Footer */}
        <div className="px-6 py-3 bg-slate-50 border-t border-slate-100 flex justify-end">
          <button
            onClick={onClose}
            className="px-4 py-2 bg-slate-200 hover:bg-slate-300 text-slate-800 text-xs font-semibold rounded-xl transition"
          >
            Tutup Modal
          </button>
        </div>

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

