/**
 * useAlertFilters Hook
 * Manages alert filtering state and logic
 */

import { useState, useCallback, useMemo } from 'react';
import type { AlertFilters, AlertSeverity, AlertCategory, TimeGroup } from '../utils/alertHelpers';

export interface UseAlertFiltersReturn {
  filters: AlertFilters;
  setFilters: React.Dispatch<React.SetStateAction<AlertFilters>>;
  toggleSeverity: (severity: AlertSeverity) => void;
  toggleCategory: (category: AlertCategory) => void;
  setTimeRange: (range: TimeGroup | 'all') => void;
  setSearch: (search: string) => void;
  toggleShowSnoozed: () => void;
  clearFilters: () => void;
  hasActiveFilters: boolean;
  activeFilterCount: number;
}

const DEFAULT_FILTERS: AlertFilters = {
  severities: [],
  categories: [],
  timeRange: 'all',
  search: '',
  showSnoozed: false,
};

/**
 * Hook to manage alert filters
 */
export function useAlertFilters(initialFilters: Partial<AlertFilters> = {}): UseAlertFiltersReturn {
  const [filters, setFilters] = useState<AlertFilters>({
    ...DEFAULT_FILTERS,
    ...initialFilters,
  });

  const toggleSeverity = useCallback((severity: AlertSeverity) => {
    setFilters(prev => ({
      ...prev,
      severities: prev.severities.includes(severity)
        ? prev.severities.filter(s => s !== severity)
        : [...prev.severities, severity],
    }));
  }, []);

  const toggleCategory = useCallback((category: AlertCategory) => {
    setFilters(prev => ({
      ...prev,
      categories: prev.categories.includes(category)
        ? prev.categories.filter(c => c !== category)
        : [...prev.categories, category],
    }));
  }, []);

  const setTimeRange = useCallback((range: TimeGroup | 'all') => {
    setFilters(prev => ({
      ...prev,
      timeRange: range,
    }));
  }, []);

  const setSearch = useCallback((search: string) => {
    setFilters(prev => ({
      ...prev,
      search,
    }));
  }, []);

  const toggleShowSnoozed = useCallback(() => {
    setFilters(prev => ({
      ...prev,
      showSnoozed: !prev.showSnoozed,
    }));
  }, []);

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

  const hasActiveFilters = useMemo(() => {
    return (
      filters.severities.length > 0 ||
      filters.categories.length > 0 ||
      filters.timeRange !== 'all' ||
      filters.search.trim() !== ''
    );
  }, [filters]);

  const activeFilterCount = useMemo(() => {
    let count = 0;
    if (filters.severities.length > 0) count += filters.severities.length;
    if (filters.categories.length > 0) count += filters.categories.length;
    if (filters.timeRange !== 'all') count += 1;
    if (filters.search.trim() !== '') count += 1;
    return count;
  }, [filters]);

  return {
    filters,
    setFilters,
    toggleSeverity,
    toggleCategory,
    setTimeRange,
    setSearch,
    toggleShowSnoozed,
    clearFilters,
    hasActiveFilters,
    activeFilterCount,
  };
}
