import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useStore } from '../context/StoreContext';
import { Search, Menu, PanelLeftClose, PanelLeftOpen, X, ChevronRight } from 'lucide-react';

export const Header: React.FC = () => {
  const { db, setScannerModalOpen, setPriceCheckBarcode, setActiveTab, setMobileMenuOpen, isSidebarCollapsed, toggleSidebar } = useStore();
  const [globalSearch, setGlobalSearch] = useState('');
  const [isSuggestOpen, setIsSuggestOpen] = useState(false);
  const [currentTime, setCurrentTime] = useState<string>('');
  const searchContainerRef = useRef<HTMLDivElement>(null);

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

  useEffect(() => {
    const updateClock = () => {
      const now = new Date();
      const options: Intl.DateTimeFormatOptions = {
        weekday: 'short',
        day: 'numeric',
        month: 'short',
        hour: '2-digit',
        minute: '2-digit'
      };
      setCurrentTime(now.toLocaleDateString('id-ID', options));
    };
    updateClock();
    const interval = setInterval(updateClock, 30000);
    return () => clearInterval(interval);
  }, []);

  // Compute live suggestions based on globalSearch
  const suggestions = useMemo(() => {
    const query = globalSearch.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, 7);
  }, [db.products, globalSearch]);

  const handleSearchKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && globalSearch.trim()) {
      setIsSuggestOpen(false);
      setActiveTab('products');
    }
  };

  return (
    <header className="h-16 bg-white border-b border-slate-200 flex items-center justify-between px-3 sm:px-6 shrink-0 sticky top-0 z-30 shadow-2xs gap-2">
      
      {/* Left Area: Mobile & Desktop Sidebar Toggle & Search Bar */}
      <div className="flex items-center gap-2 flex-1 max-w-lg">
        <button
          onClick={() => {
            if (window.innerWidth < 768) {
              setMobileMenuOpen(true);
            } else {
              toggleSidebar();
            }
          }}
          className="p-2 rounded-xl text-slate-600 hover:bg-slate-100 hover:text-emerald-700 transition shrink-0"
          title={isSidebarCollapsed ? "Buka Sidebar Navigation" : "Tutup/Sembunyikan Sidebar"}
        >
          {isSidebarCollapsed ? (
            <PanelLeftOpen className="w-5 h-5 text-emerald-700" />
          ) : (
            <Menu className="w-5 h-5" />
          )}
        </button>

        {/* Global Search Input Bar with Auto-Suggestions */}
        <div ref={searchContainerRef} className="relative w-full">
          <div className="flex items-center bg-slate-100 rounded-full px-3 sm:px-4 py-1.5 w-full border border-slate-200 text-xs focus-within:bg-white focus-within:ring-2 focus-within:ring-emerald-500 focus-within:border-emerald-500 transition">
            <Search className="w-4 h-4 text-slate-400 mr-2 shrink-0" />
            <input
              type="text"
              value={globalSearch}
              onFocus={() => setIsSuggestOpen(true)}
              onChange={(e) => {
                setGlobalSearch(e.target.value);
                setIsSuggestOpen(true);
              }}
              onKeyDown={handleSearchKeyDown}
              placeholder="Ketik nama barang / barcode / SKU..."
              className="bg-transparent text-xs text-slate-800 placeholder-slate-400 outline-none w-full font-medium"
            />
            {globalSearch && (
              <button
                type="button"
                onClick={() => {
                  setGlobalSearch('');
                  setIsSuggestOpen(false);
                }}
                className="text-slate-400 hover:text-slate-600 p-0.5 rounded-full"
              >
                <X className="w-3.5 h-3.5" />
              </button>
            )}
          </div>

          {/* Floating Auto-Suggest Dropdown */}
          {isSuggestOpen && globalSearch.trim().length > 0 && (
            <div className="absolute top-full left-0 right-0 mt-2 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 Barang ({suggestions.length})</span>
                <span className="text-[10px] font-normal text-slate-400">Pencarian Cepat</span>
              </div>

              {suggestions.length === 0 ? (
                <div className="p-4 text-center text-slate-400 italic text-xs">
                  Tidak ditemukan barang yang cocok dengan "<span className="font-semibold text-slate-600">{globalSearch}</span>"
                </div>
              ) : (
                <div className="max-h-72 overflow-y-auto divide-y divide-slate-100">
                  {suggestions.map((item) => (
                    <button
                      key={`${item.productId}-${item.variantId}`}
                      type="button"
                      onClick={() => {
                        setGlobalSearch(`${item.productName} (${item.variantName})`);
                        setIsSuggestOpen(false);
                        setPriceCheckBarcode(item.barcode || item.productName);
                        setScannerModalOpen(true);
                      }}
                      className="w-full text-left px-3.5 py-2.5 hover:bg-emerald-50/80 transition flex items-center justify-between gap-2 group"
                    >
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-1.5 flex-wrap">
                          <span className="font-bold text-slate-800 group-hover:text-emerald-800 text-xs truncate">
                            {item.productName}
                          </span>
                          <span className="px-1.5 py-0.2 bg-slate-100 text-slate-600 group-hover:bg-emerald-100 group-hover:text-emerald-800 rounded text-[10px] font-semibold shrink-0">
                            {item.variantName}
                          </span>
                        </div>
                        <div className="flex items-center gap-2 mt-0.5 text-[11px] text-slate-400">
                          <span className="font-mono text-slate-500 font-semibold">
                            {item.barcode ? `Barcode: ${item.barcode}` : 'Tanpa Barcode'}
                          </span>
                          <span>•</span>
                          <span className="text-slate-400">{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 className="p-2 bg-slate-50 border-t border-slate-100">
                <button
                  type="button"
                  onClick={() => {
                    setIsSuggestOpen(false);
                    setActiveTab('products');
                  }}
                  className="w-full py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl text-center text-xs transition flex items-center justify-center gap-1"
                >
                  <span>Lihat Semua Produk di Kelola Stok</span>
                  <ChevronRight className="w-3.5 h-3.5" />
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Header Actions & Profile */}
      <div className="flex items-center gap-2 sm:gap-3">
        {/* User Profile Info */}
        <div className="flex items-center gap-2 sm:gap-3">
          <div className="text-right hidden sm:block">
            <p className="text-[10px] text-slate-400 leading-tight">Selamat Datang,</p>
            <p className="text-xs font-bold text-slate-900 leading-tight">Pengelola Toko</p>
          </div>
          <div className="w-9 h-9 rounded-full bg-slate-200 border-2 border-emerald-500 flex items-center justify-center text-xs font-black text-emerald-800 shrink-0">
            TM
          </div>
        </div>
      </div>
    </header>
  );
};

