import React, { useState, useMemo, useRef, useEffect } from 'react';
import { useStore } from '../context/StoreContext';
import { BarcodeScannerModal } from '../components/BarcodeScannerModal';
import { Barcode, Camera, ShoppingCart, Package, X } from 'lucide-react';

export const PriceLookupPage: React.FC = () => {
  const { db, findVariantByBarcode, setActiveTab } = useStore();
  const [barcodeInput, setBarcodeInput] = useState('');
  const [activeBarcode, setActiveBarcode] = useState('');
  const [isCameraModalOpen, setIsCameraModalOpen] = useState(false);
  const [isSuggestOpen, setIsSuggestOpen] = useState(false);

  const dropdownRef = useRef<HTMLDivElement>(null);

  // Flatten all product variants for quick search & suggestions
  const allVariants = useMemo(() => {
    const list: Array<{
      productId: string;
      productName: string;
      category: string;
      variantName: string;
      barcode: string;
      sellPrice: number;
      buyPrice: number;
      stock: number;
      minStock: number;
      unit: string;
      size: string;
      variantId: string;
    }> = [];

    (db.products || []).forEach(p => {
      (p.variants || []).forEach(v => {
        list.push({
          productId: p.id,
          productName: p.name,
          category: p.category,
          variantName: v.variantName,
          barcode: v.barcode,
          sellPrice: v.sellPrice,
          buyPrice: v.buyPrice,
          stock: v.stock,
          minStock: v.minStock,
          unit: v.unit,
          size: v.size,
          variantId: v.id,
        });
      });
    });

    return list;
  }, [db.products]);

  // Real-time suggestions based on user input
  const suggestions = useMemo(() => {
    const q = barcodeInput.trim().toLowerCase();
    if (!q) return [];

    return allVariants.filter(item =>
      item.productName.toLowerCase().includes(q) ||
      item.variantName.toLowerCase().includes(q) ||
      item.barcode.toLowerCase().includes(q) ||
      item.category.toLowerCase().includes(q)
    ).slice(0, 8);
  }, [allVariants, barcodeInput]);

  // Handle live typing
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    setBarcodeInput(val);
    setIsSuggestOpen(true);

    const exactMatch = allVariants.find(item => item.barcode.toLowerCase() === val.trim().toLowerCase());
    if (exactMatch) {
      setActiveBarcode(exactMatch.barcode);
    } else {
      setActiveBarcode(val.trim());
    }
  };

  // Handle selecting a suggestion
  const handleSelectSuggestion = (item: typeof allVariants[0]) => {
    setBarcodeInput(item.productName + ' - ' + item.variantName);
    setActiveBarcode(item.barcode);
    setIsSuggestOpen(false);
  };

  const handleSelectSample = (code: string, label: string) => {
    setBarcodeInput(label);
    setActiveBarcode(code);
    setIsSuggestOpen(false);
  };

  // Close dropdown on click outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setIsSuggestOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const matched = activeBarcode ? findVariantByBarcode(activeBarcode) : null;

  return (
    <div className="space-y-6 max-w-4xl mx-auto">
      
      {/* Title */}
      <div className="bg-gradient-to-r from-emerald-600 via-teal-600 to-emerald-700 text-white rounded-3xl p-6 sm:p-8 shadow-lg text-center space-y-3">
        <div className="w-12 h-12 bg-white/20 backdrop-blur-xs rounded-2xl flex items-center justify-center mx-auto text-white">
          <Barcode className="w-7 h-7" />
        </div>
        <h2 className="text-2xl sm:text-3xl font-black tracking-tight">Pengecekan Harga Barcode Barang</h2>
        <p className="text-emerald-100 text-xs sm:text-sm max-w-lg mx-auto">
          Cukup ketik nama barang atau scan kode barcode. Rekomendasi barang akan otomatis muncul secara langsung tanpa perlu menekan tombol cari.
        </p>

        <div className="pt-2">
          <button
            onClick={() => setIsCameraModalOpen(true)}
            className="px-6 py-3 bg-white text-emerald-800 hover:bg-emerald-50 font-black text-xs sm:text-sm rounded-xl shadow-md inline-flex items-center gap-2 transition active:scale-95"
          >
            <Camera className="w-4 h-4 text-emerald-600" /> Buka Scanner Kamera Barcode
          </button>
        </div>
      </div>

      {/* Auto-suggest Search Box (Without 'Cari Harga' button) */}
      <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-2xs space-y-4 relative" ref={dropdownRef}>
        <div className="relative">
          <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 flex items-center gap-2 pointer-events-none">
            <Barcode className="w-5 h-5" />
          </div>

          <input
            type="text"
            value={barcodeInput}
            onChange={handleInputChange}
            onFocus={() => setIsSuggestOpen(true)}
            placeholder="Ketik nama barang, varian, atau barcode (cth: Le Minerale / 8996001600124)..."
            className="w-full pl-12 pr-10 py-3.5 bg-slate-50 border border-slate-200 rounded-xl text-sm font-semibold text-slate-900 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white transition"
          />

          {barcodeInput && (
            <button
              onClick={() => {
                setBarcodeInput('');
                setActiveBarcode('');
                setIsSuggestOpen(false);
              }}
              className="absolute right-3.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-1"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>

        {/* Real-time Suggestion Dropdown */}
        {isSuggestOpen && barcodeInput.trim().length > 0 && (
          <div className="absolute left-6 right-6 top-[72px] bg-white border border-slate-200 rounded-2xl shadow-xl z-30 max-h-80 overflow-y-auto divide-y divide-slate-100">
            {suggestions.length > 0 ? (
              suggestions.map((item) => (
                <div
                  key={`${item.productId}-${item.variantId}`}
                  onClick={() => handleSelectSuggestion(item)}
                  className="p-3.5 hover:bg-emerald-50/70 cursor-pointer transition flex items-center justify-between gap-3 group"
                >
                  <div className="flex items-center gap-3 min-w-0">
                    <div className="p-2 bg-slate-100 group-hover:bg-emerald-100 rounded-xl text-slate-500 group-hover:text-emerald-700 transition shrink-0">
                      <Package className="w-4 h-4" />
                    </div>
                    <div className="min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="font-bold text-slate-900 text-xs truncate">{item.productName}</span>
                        <span className="text-[10px] font-semibold text-emerald-800 bg-emerald-100 px-2 py-0.5 rounded-full shrink-0">
                          {item.variantName}
                        </span>
                      </div>
                      <div className="text-[11px] text-slate-400 font-mono mt-0.5 truncate">
                        Barcode: <span className="text-slate-600 font-semibold">{item.barcode}</span> &bull; {item.category}
                      </div>
                    </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 font-medium">
                      Stok: {item.stock} {item.unit}
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="p-4 text-center text-xs text-slate-500">
                Tidak ada barang yang cocok dengan kata kunci &quot;{barcodeInput}&quot;.
              </div>
            )}
          </div>
        )}

        {/* Quick Test Samples */}
        <div className="pt-2 border-t border-slate-100 flex flex-wrap items-center gap-2 text-xs">
          <span className="font-semibold text-slate-500">Contoh Pilihan Cepat:</span>
          <button
            onClick={() => handleSelectSample('8996001600124', 'Le Minerale Besar')}
            className="px-2.5 py-1 bg-emerald-50 text-emerald-800 hover:bg-emerald-100 rounded-lg font-mono font-bold transition"
          >
            Le Minerale Besar
          </button>
          <button
            onClick={() => handleSelectSample('8996001600123', 'Le Minerale Sedang')}
            className="px-2.5 py-1 bg-emerald-50 text-emerald-800 hover:bg-emerald-100 rounded-lg font-mono font-bold transition"
          >
            Le Minerale Sedang
          </button>
          <button
            onClick={() => handleSelectSample('899200110002', 'Beras Sania 5KG')}
            className="px-2.5 py-1 bg-emerald-50 text-emerald-800 hover:bg-emerald-100 rounded-lg font-mono font-bold transition"
          >
            Beras Sania 5KG
          </button>
        </div>
      </div>

      {/* RESULT DISPLAY CARD */}
      {activeBarcode && (
        matched ? (
          <div className="bg-white border-2 border-emerald-500 rounded-3xl p-6 shadow-xl space-y-6 animate-in fade-in zoom-in-95 duration-150">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-100 pb-4">
              <div>
                <span className="px-3 py-1 bg-emerald-100 text-emerald-800 text-xs font-bold rounded-full">
                  {matched.product.category}
                </span>
                <h3 className="text-2xl font-black text-slate-900 mt-2">{matched.product.name}</h3>
                <p className="text-sm font-bold text-emerald-700">
                  Varian Ukuran: <span className="underline">{matched.variant.variantName}</span> ({matched.variant.size} {matched.variant.unit})
                </p>
                <p className="text-xs text-slate-400 font-mono mt-1">Kode Barcode: {matched.variant.barcode}</p>
              </div>

              <div className="text-left sm:text-right">
                <span className={`inline-block px-3 py-1.5 rounded-xl text-xs font-extrabold ${
                  matched.variant.stock <= 0
                    ? 'bg-rose-100 text-rose-800'
                    : matched.variant.stock <= matched.variant.minStock
                    ? 'bg-amber-100 text-amber-900'
                    : 'bg-emerald-100 text-emerald-800'
                }`}>
                  Stok Tersedia: {matched.variant.stock} {matched.variant.unit}
                </span>
              </div>
            </div>

            {/* Prices Big Cards */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              <div className="p-4 bg-slate-50 border border-slate-200 rounded-2xl">
                <span className="text-xs text-slate-500 font-semibold block">Harga Beli (Modal)</span>
                <span className="text-xl font-bold text-slate-800">
                  Rp {matched.variant.buyPrice.toLocaleString('id-ID')}
                </span>
              </div>

              <div className="p-4 bg-gradient-to-br from-emerald-600 to-teal-700 text-white rounded-2xl shadow-md">
                <span className="text-xs text-emerald-100 font-semibold block">Harga Jual Toko Makmur</span>
                <span className="text-2xl font-black">
                  Rp {matched.variant.sellPrice.toLocaleString('id-ID')}
                </span>
              </div>

              <div className="p-4 bg-slate-50 border border-slate-200 rounded-2xl">
                <span className="text-xs text-slate-500 font-semibold block">Keuntungan (Margin)</span>
                <span className="text-xl font-bold text-teal-600 block">
                  +Rp {(matched.variant.sellPrice - matched.variant.buyPrice).toLocaleString('id-ID')}
                </span>
              </div>
            </div>

            <div className="flex gap-3 pt-2">
              <button
                onClick={() => setActiveTab('pos')}
                className="flex-1 py-3 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl flex items-center justify-center gap-2 shadow-md transition"
              >
                <ShoppingCart className="w-4 h-4" /> Buka Kasir & Transaksi
              </button>
            </div>
          </div>
        ) : (
          <div className="bg-rose-50 border border-rose-200 rounded-3xl p-8 text-center space-y-3">
            <h3 className="font-bold text-rose-900 text-base">Barcode Tidak Ditemukan</h3>
            <p className="text-xs text-rose-700 max-w-md mx-auto">
              Kode barcode <span className="font-mono font-bold">{activeBarcode}</span> belum terdaftar di sistem Toko Makmur. Silahkan daftarkan barang baru di katalog produk.
            </p>
            <button
              onClick={() => setActiveTab('products')}
              className="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl transition"
            >
              + Buat Barang Baru
            </button>
          </div>
        )
      )}

      {/* Scanner Modal */}
      <BarcodeScannerModal
        isOpen={isCameraModalOpen}
        onClose={() => setIsCameraModalOpen(false)}
        onSelectVariantForPos={() => {
          setActiveTab('pos');
        }}
      />

    </div>
  );
};

