import { useState, useMemo, useCallback } from 'react';
import { FilterOptions, ListItem } from '../types';

export interface UseDataFilterOptions {
  searchFields?: string[];
  defaultFilters?: FilterOptions;
  debounceMs?: number;
}

export interface UseDataFilterReturn {
  filteredData: ListItem[];
  filters: FilterOptions;
  setFilter: (key: string, value: any) => void;
  clearFilters: () => void;
  resetFilters: () => void;
  searchTerm: string;
  setSearchTerm: (term: string) => void;
}

export const useDataFilter = (
  data: ListItem[],
  options: UseDataFilterOptions = {}
): UseDataFilterReturn => {
  const {
    searchFields = ['name', 'title', 'email', 'description'],
    defaultFilters = {},
  } = options;

  const [filters, setFilters] = useState<FilterOptions>(defaultFilters);
  const [searchTerm, setSearchTerm] = useState('');

  const setFilter = useCallback((key: string, value: any) => {
    if (key === 'search') {
      setSearchTerm(value);
      setFilters(prev => ({ ...prev, search: value }));
    } else {
      setFilters(prev => ({ ...prev, [key]: value }));
    }
  }, []);

  const clearFilters = useCallback(() => {
    setFilters({});
    setSearchTerm('');
  }, []);

  const resetFilters = useCallback(() => {
    setFilters(defaultFilters);
    setSearchTerm('');
  }, [defaultFilters]);

  const filteredData = useMemo(() => {
    let result = [...data];

    // Apply search filter
    if (searchTerm.trim()) {
      const term = searchTerm.toLowerCase().trim();
      result = result.filter(item => {
        return searchFields.some(field => {
          const value = item[field];
          if (!value) return false;
          return value.toString().toLowerCase().includes(term);
        });
      });
    }

    // Apply other filters
    Object.entries(filters).forEach(([key, value]) => {
      if (key === 'search') return; // Already handled above
      
      if (value !== undefined && value !== null && value !== '') {
        if (Array.isArray(value) && value.length > 0) {
          // Array filter (e.g., multiple status selection)
          result = result.filter(item => value.includes(item[key]));
        } else {
          // Single value filter
          result = result.filter(item => {
            const itemValue = item[key];
            if (itemValue == null) return false;
            
            // Exact match for most cases
            if (itemValue.toString().toLowerCase() === value.toString().toLowerCase()) {
              return true;
            }
            
            // Partial match for string fields
            if (typeof itemValue === 'string' && typeof value === 'string') {
              return itemValue.toLowerCase().includes(value.toLowerCase());
            }
            
            return false;
          });
        }
      }
    });

    return result;
  }, [data, searchTerm, filters, searchFields]);

  return {
    filteredData,
    filters,
    setFilter,
    clearFilters,
    resetFilters,
    searchTerm,
    setSearchTerm,
  };
};