/**
 * FilterBar Component
 * 
 * Compact 1-row filter bar above AG Grid table
 */

import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useDebounce } from '../../hooks/useDebounce';
import LoadingSpinner from '../ui/LoadingSpinner';
import CacheStatus from '../ui/CacheStatus';

interface FilterBarProps {
  onFilterChange: (filters: FilterState) => void;
  isLoading?: boolean;
}

export interface FilterState {
  search: string;
  attributes: string;
  priceMin: number | null;
  priceMax: number | null;
  filterSalePrice: boolean;
  saleDateFrom: string | null;
  saleDateTo: string | null;
  onlyActiveSales: boolean;
  checkedSearch: boolean;
}

interface AutocompleteItem {
  label: string;
  sublabel?: string;
  value: string;
}

export default function FilterBar({ 
  onFilterChange, 
  isLoading = false,
}: FilterBarProps) {
  const { t } = useTranslation();
  
  // Filter state
  const [search, setSearch] = useState('');
  const [attributes, setAttributes] = useState('');
  const [priceMin, setPriceMin] = useState<string>('');
  const [priceMax, setPriceMax] = useState<string>('');
  const [filterSalePrice, setFilterSalePrice] = useState(false);
  const [saleDateFrom, setSaleDateFrom] = useState<string>('');
  const [saleDateTo, setSaleDateTo] = useState<string>('');
  const [onlyActiveSales, setOnlyActiveSales] = useState(false);
  // 🔥 checkedSearch is NOT managed by FilterBar (it's a Toolbar feature)
  
  // Autocomplete state
  const [showProductSuggestions, setShowProductSuggestions] = useState(false);
  const [showAttributeSuggestions, setShowAttributeSuggestions] = useState(false);
  const [productSuggestions, setProductSuggestions] = useState<AutocompleteItem[]>([]);
  const [attributeSuggestions, setAttributeSuggestions] = useState<AutocompleteItem[]>([]);
  
  // Input field states (separate from filter state for autocomplete)
  const [productInputValue, setProductInputValue] = useState('');
  const [attributeInputValue, setAttributeInputValue] = useState('');
  
  // Suppress dropdown flags (prevent re-opening after selection)
  const suppressProductDropdown = useRef(false);
  const suppressAttributeDropdown = useRef(false);
  
  const productInputRef = useRef<HTMLInputElement>(null);
  const attributeInputRef = useRef<HTMLInputElement>(null);
  
  // Debounce ALL filter changes (500ms) - user can finish typing
  const debouncedSearch = useDebounce(search, 500);
  const debouncedAttributes = useDebounce(attributes, 500);
  const debouncedPriceMin = useDebounce(priceMin, 500);
  const debouncedPriceMax = useDebounce(priceMax, 500);
  
  // Debounce autocomplete separately (500ms, 2 char minimum)
  const debouncedAttributeInput = useDebounce(attributeInputValue, 500);
  
  // Auto-enable filterSalePrice when onlyActiveSales is checked
  useEffect(() => {
    if (onlyActiveSales && !filterSalePrice) {
      setFilterSalePrice(true);
    }
  }, [onlyActiveSales, filterSalePrice]);
  
  // Trigger filter change - USE DEBOUNCED VALUES!
  // 🔥 NOTE: checkedSearch is NOT sent (managed by Toolbar, not FilterBar)
  useEffect(() => {
    onFilterChange({
      search: debouncedSearch.trim(),
      attributes: debouncedAttributes.trim(),
      priceMin: debouncedPriceMin ? parseFloat(debouncedPriceMin) : null,
      priceMax: debouncedPriceMax ? parseFloat(debouncedPriceMax) : null,
      filterSalePrice,
      saleDateFrom: saleDateFrom || null,
      saleDateTo: saleDateTo || null,
      onlyActiveSales,
      checkedSearch: false, // Always false - VariationsTable will preserve its own value
    });
  }, [debouncedSearch, debouncedAttributes, debouncedPriceMin, debouncedPriceMax, filterSalePrice, saleDateFrom, saleDateTo, onlyActiveSales, onFilterChange]);
  
  // Fetch product suggestions (3+ characters from input field)
  useEffect(() => {
    if (productInputValue.length >= 3 && !suppressProductDropdown.current) {
      fetchProductSuggestions(productInputValue);
    } else {
      setShowProductSuggestions(false);
      setProductSuggestions([]);
    }
  }, [productInputValue]);
  
  // Fetch attribute suggestions (2+ characters, 300ms debounce from input field)
  useEffect(() => {
    if (debouncedAttributeInput.length >= 2 && !suppressAttributeDropdown.current) {
      fetchAttributeSuggestions(debouncedAttributeInput);
    } else {
      setShowAttributeSuggestions(false);
      setAttributeSuggestions([]);
    }
  }, [debouncedAttributeInput]);
  
  const fetchProductSuggestions = async (query: string) => {
    try {
      const response = await fetch(
        `${window.varihuConfig.restUrl}/variations/autocomplete/products?q=${encodeURIComponent(query)}`,
        {
          headers: {
            'X-WP-Nonce': window.varihuConfig.nonce,
          },
        }
      );
      const data = await response.json();
      
      if (data.success) {
        setProductSuggestions(data.data);
        setShowProductSuggestions(true);
      }
    } catch (error) {
      console.error('[FilterBar] Product autocomplete error:', error);
    }
  };
  
  const fetchAttributeSuggestions = async (query: string) => {
    try {
      const response = await fetch(
        `${window.varihuConfig.restUrl}/variations/autocomplete/attributes?q=${encodeURIComponent(query)}`,
        {
          headers: {
            'X-WP-Nonce': window.varihuConfig.nonce,
          },
        }
      );
      const data = await response.json();
      
      if (data.success) {
        setAttributeSuggestions(data.data);
        setShowAttributeSuggestions(true);
      }
    } catch (error) {
      console.error('[FilterBar] Attribute autocomplete error:', error);
    }
  };
  
  const handleProductSelect = (item: AutocompleteItem) => {
    // Beállítjuk MINDKÉT state-et: a filter state-et ÉS az input value-t
    const selectedValue = item.value;
    setSearch(selectedValue);
    setProductInputValue(selectedValue);
    setShowProductSuggestions(false);
    setProductSuggestions([]); // Töröljük a listát is!
    suppressProductDropdown.current = true; // 🔥 Suppress dropdown re-open
  };
  
  const handleAttributeSelect = (item: AutocompleteItem) => {
    // Beállítjuk MINDKÉT state-et: a filter state-et ÉS az input value-t
    const selectedValue = item.value;
    setAttributes(selectedValue);
    setAttributeInputValue(selectedValue);
    setShowAttributeSuggestions(false);
    setAttributeSuggestions([]); // Töröljük a listát is!
    suppressAttributeDropdown.current = true; // 🔥 Suppress dropdown re-open
  };
  
  const handleClearFilters = () => {
    setSearch('');
    setProductInputValue('');
    setAttributes('');
    setAttributeInputValue('');
    setPriceMin('');
    setPriceMax('');
    setFilterSalePrice(false);
    setSaleDateFrom('');
    setSaleDateTo('');
    setOnlyActiveSales(false);
    // 🔥 checkedSearch is NOT cleared here (managed by Toolbar)
  };
  
  const hasActiveFilters = search || attributes || priceMin || priceMax || filterSalePrice || saleDateFrom || saleDateTo || onlyActiveSales;
  
  return (
    <div className="bg-gradient-to-r from-gray-50 to-white border-b-2 border-gray-200 px-3 py-2 relative">
      {/* Top Right Indicators - z-50 hogy overlay felett legyen! */}
      <div className="absolute top-2 right-3 z-50 flex items-center gap-2">
        {/* Loading Spinner */}
        {isLoading && <LoadingSpinner size="sm" />}
        
        {/* Cache Status */}
        <CacheStatus />
      </div>
      
      <div className="flex items-center gap-2">
        {/* Product/SKU Search - 30% kisebb */}
        <div className="relative flex-1 max-w-[200px]">
          <input
            ref={productInputRef}
            type="text"
            value={productInputValue}
            onChange={(e) => {
              setProductInputValue(e.target.value);
              setSearch(e.target.value); // Sync azonnal - NORMÁL szűrő (debounced)
              suppressProductDropdown.current = false; // Re-enable dropdown
            }}
            placeholder={t('filter.product_sku_search')}
            className="w-full px-2 py-1.5 text-xs border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
          />
          
          {/* Product Autocomplete Dropdown */}
          {showProductSuggestions && productSuggestions.length > 0 && (
            <div className="absolute z-50 w-full mt-1 bg-white border-2 border-indigo-500 rounded-lg shadow-xl max-h-64 overflow-y-auto">
              {productSuggestions.map((item, index) => (
                <button
                  key={index}
                  onClick={() => handleProductSelect(item)}
                  className="w-full px-4 py-2 text-left hover:bg-indigo-50 transition flex flex-col"
                >
                  <span className="text-sm font-semibold text-gray-900">{item.label}</span>
                  {item.sublabel && (
                    <span className="text-xs text-gray-500 font-mono">{item.sublabel}</span>
                  )}
                </button>
              ))}
            </div>
          )}
        </div>
        
        {/* Attribute Search - 30% kisebb */}
        <div className="relative flex-1 max-w-[200px]">
          <input
            ref={attributeInputRef}
            type="text"
            value={attributeInputValue}
            onChange={(e) => {
              setAttributeInputValue(e.target.value);
              // NE sync-eljük a filter state-et gépelés közben! Csak autocomplete input
              suppressAttributeDropdown.current = false; // Re-enable dropdown
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                // Enter esetén triggereljük a szűrést
                setAttributes(attributeInputValue);
                setShowAttributeSuggestions(false);
                suppressAttributeDropdown.current = true;
              }
            }}
            placeholder={t('filter.attribute_search')}
            className="w-full px-2 py-1.5 text-xs border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
          />
          
          {/* Attribute Autocomplete Dropdown */}
          {showAttributeSuggestions && attributeSuggestions.length > 0 && (
            <div className="absolute z-50 w-full mt-1 bg-white border-2 border-indigo-500 rounded-lg shadow-xl max-h-64 overflow-y-auto">
              {attributeSuggestions.map((item, index) => (
                <button
                  key={index}
                  onClick={() => handleAttributeSelect(item)}
                  className="w-full px-4 py-2 text-left hover:bg-indigo-50 transition"
                >
                  <span className="text-sm text-gray-900">{item.label}</span>
                  {item.sublabel && (
                    <span className="text-xs text-gray-500 ml-2">{item.sublabel}</span>
                  )}
                </button>
              ))}
            </div>
          )}
        </div>
        
        {/* Price Range - Kisebb, inline */}
        <div className="flex items-center gap-1">
          <input
            type="number"
            value={priceMin}
            onChange={(e) => setPriceMin(e.target.value)}
            placeholder={t('filter.price_min')}
            className="w-20 px-2 py-1.5 text-xs border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
          />
          <span className="text-gray-400 text-xs">-</span>
          <input
            type="number"
            value={priceMax}
            onChange={(e) => setPriceMax(e.target.value)}
            placeholder={t('filter.price_max')}
            className="w-20 px-2 py-1.5 text-xs border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
          />
        </div>
        
        {/* Akciós ár checkbox - INLINE! */}
        <label className="flex items-center gap-1.5 cursor-pointer whitespace-nowrap">
          <input
            type="checkbox"
            checked={filterSalePrice}
            onChange={(e) => setFilterSalePrice(e.target.checked)}
            className="w-3.5 h-3.5 text-orange-600 rounded focus:ring-2 focus:ring-orange-200"
          />
          <span className="text-xs font-medium text-orange-700">{t('filter.filter_sale_price')}</span>
        </label>
        
        {/* Sale Date Range - Csak akkor enabled, ha filterSalePrice=true */}
        <div className="flex items-center gap-1">
          <input
            type="date"
            value={saleDateFrom}
            onChange={(e) => setSaleDateFrom(e.target.value)}
            disabled={!filterSalePrice}
            className={`w-32 px-2 py-1.5 text-xs border-2 rounded-lg transition ${
              filterSalePrice
                ? 'border-gray-300 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200'
                : 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed'
            }`}
          />
          <span className="text-gray-400 text-xs">→</span>
          <input
            type="date"
            value={saleDateTo}
            onChange={(e) => setSaleDateTo(e.target.value)}
            disabled={!filterSalePrice}
            className={`w-32 px-2 py-1.5 text-xs border-2 rounded-lg transition ${
              filterSalePrice
                ? 'border-gray-300 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200'
                : 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed'
            }`}
          />
        </div>
        
        {/* Active Sales Checkbox - Csak akkor enabled, ha filterSalePrice=true */}
        <label className={`flex items-center gap-1.5 whitespace-nowrap ${
          filterSalePrice ? 'cursor-pointer' : 'cursor-not-allowed opacity-50'
        }`}>
          <input
            type="checkbox"
            checked={onlyActiveSales}
            onChange={(e) => setOnlyActiveSales(e.target.checked)}
            disabled={!filterSalePrice}
            className="w-3.5 h-3.5 text-indigo-600 rounded focus:ring-2 focus:ring-indigo-200 disabled:cursor-not-allowed"
          />
          <span className="text-xs font-medium text-gray-700">{t('filter.only_active_sales')}</span>
        </label>
        
        {/* Clear Filters - Kisebb */}
        {hasActiveFilters && (
          <button
            onClick={handleClearFilters}
            className="px-2 py-1.5 text-xs font-semibold text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition"
          >
            ✕ {t('filter.clear')}
          </button>
        )}
      </div>
    </div>
  );
}
