import React, { useMemo } from 'react';
import '@/src/styles/select.css';
import { trackEvent } from './MatomoAnalytics';
import { getFinishesForMaterial, getAllFinishes, getMaterialOptions } from '@/src/data/bambuLabCatalog';
import { Filament } from '@/src/types/filament';

interface EnhancedFiltersProps {
  filters: {
    material: string;
    finish: string;
    color: string;
  };
  onFilterChange: (filters: { material: string; finish: string; color: string }) => void;
  uniqueValues: {
    materials: string[];
    finishes: string[];
    colors: string[];
  };
  inventoryFilaments?: Filament[];
}

export const EnhancedFilters: React.FC<EnhancedFiltersProps> = ({
  filters,
  onFilterChange,
  uniqueValues,
  inventoryFilaments = []
}) => {
  const hasActiveFilters = filters.material || filters.finish || filters.color;

  // Catalog-aware material list (static from catalog)
  const materialOptions = useMemo(() => getMaterialOptions(), []);

  // Finish options: conditional on selected material
  const finishOptions = useMemo(() => {
    const inStock = inventoryFilaments.filter(f => f.kolicina > 0);
    if (filters.material) {
      // Show finishes from catalog for this material, but only if they exist in inventory
      const catalogFinishes = getFinishesForMaterial(filters.material);
      const inventoryFinishes = new Set(
        inStock.filter(f => f.tip === filters.material).map(f => f.finish)
      );
      return catalogFinishes.filter(f => inventoryFinishes.has(f));
    }
    // No material selected: show all finishes from inventory
    if (inStock.length > 0) {
      return [...new Set(inStock.map(f => f.finish))].sort();
    }
    return getAllFinishes();
  }, [filters.material, inventoryFilaments]);

  // Color options: conditional on selected material + finish
  const colorOptions = useMemo(() => {
    const inStock = inventoryFilaments.filter(f => f.kolicina > 0);
    let filtered = inStock;
    if (filters.material) {
      filtered = filtered.filter(f => f.tip === filters.material);
    }
    if (filters.finish) {
      filtered = filtered.filter(f => f.finish === filters.finish);
    }
    return [...new Set(filtered.map(f => f.boja))].sort();
  }, [filters.material, filters.finish, inventoryFilaments]);

  const handleMaterialChange = (value: string) => {
    // Reset finish and color when material changes
    onFilterChange({ material: value, finish: '', color: '' });
    trackEvent('Filter', 'Material', value || 'All');
  };

  const handleFinishChange = (value: string) => {
    // Reset color when finish changes
    onFilterChange({ ...filters, finish: value, color: '' });
    trackEvent('Filter', 'Finish', value || 'All');
  };

  const handleColorChange = (value: string) => {
    onFilterChange({ ...filters, color: value });
    trackEvent('Filter', 'Color', value || 'All');
  };

  return (
    <div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
      {/* Filters Grid */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 max-w-4xl mx-auto">
        {/* Material Filter */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Materijal
          </label>
          <select
            value={filters.material}
            onChange={(e) => handleMaterialChange(e.target.value)}
            className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600
                     bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100
                     rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">Svi materijali</option>
            {materialOptions.map(mat => (
              <option key={mat} value={mat}>{mat}</option>
            ))}
          </select>
        </div>

        {/* Finish Filter */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Finish
          </label>
          <select
            value={filters.finish}
            onChange={(e) => handleFinishChange(e.target.value)}
            className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600
                     bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100
                     rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">Svi finish tipovi</option>
            {finishOptions.map(finish => (
              <option key={finish} value={finish}>{finish}</option>
            ))}
          </select>
        </div>

        {/* Color Filter */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Boja
          </label>
          <select
            value={filters.color}
            onChange={(e) => handleColorChange(e.target.value)}
            className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600
                     bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100
                     rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">Sve boje</option>
            {colorOptions.map(color => (
              <option key={color} value={color}>{color}</option>
            ))}
          </select>
        </div>

      </div>

      {/* Reset button - only show when filters are active */}
      {hasActiveFilters && (
        <div className="mt-4 text-center">
          <button
            onClick={() => {
              onFilterChange({
                material: '',
                finish: '',
                color: ''
              });
              trackEvent('Filter', 'Reset', 'All Filters');
            }}
            className="px-4 py-2 text-sm font-medium text-white bg-red-500 dark:bg-red-600 hover:bg-red-600 dark:hover:bg-red-700 rounded-md transition-colors"
          >
            Reset filtere
          </button>
        </div>
      )}
    </div>
  );
};
