/**
 * Moderation Queue Filters Hook
 * 
 * Manages filter state for the moderation queue, including:
 * - Entity type filtering (all, reviews, submissions, photos)
 * - Status filtering (pending, approved, rejected, etc.)
 * - Tab management (main queue vs archive)
 * - Filter persistence and clearing
 */

import { useState, useCallback, useEffect } from 'react';
import { useDebounce } from '@/hooks/useDebounce';
import { logger } from '@/lib/logger';
import { MODERATION_CONSTANTS } from '@/lib/moderation/constants';
import type { EntityFilter, StatusFilter, QueueTab, SortConfig, SortField } from '@/types/moderation';
import * as storage from '@/lib/localStorage';

export interface ModerationFiltersConfig {
  /** Initial entity filter */
  initialEntityFilter?: EntityFilter;
  
  /** Initial status filter */
  initialStatusFilter?: StatusFilter;
  
  /** Initial active tab */
  initialTab?: QueueTab;
  
  /** Debounce delay for filter changes (ms) */
  debounceDelay?: number;
  
  /** Whether to persist filters to localStorage */
  persist?: boolean;
  
  /** localStorage key prefix for persistence */
  storageKey?: string;
  
  /** Initial sort configuration */
  initialSortConfig?: SortConfig;
}

export interface ModerationFilters {
  /** Current entity type filter */
  entityFilter: EntityFilter;
  
  /** Current status filter */
  statusFilter: StatusFilter;
  
  /** Current active tab */
  activeTab: QueueTab;
  
  /** Debounced entity filter (for API calls) */
  debouncedEntityFilter: EntityFilter;
  
  /** Debounced status filter (for API calls) */
  debouncedStatusFilter: StatusFilter;
  
  /** Set entity filter */
  setEntityFilter: (filter: EntityFilter) => void;
  
  /** Set status filter */
  setStatusFilter: (filter: StatusFilter) => void;
  
  /** Set active tab */
  setActiveTab: (tab: QueueTab) => void;
  
  /** Reset all filters to defaults */
  clearFilters: () => void;
  
  /** Check if any non-default filters are active */
  hasActiveFilters: boolean;
  
  /** Current sort configuration (immediate) */
  sortConfig: SortConfig;
  
  /** Debounced sort configuration (use this for queries) */
  debouncedSortConfig: SortConfig;
  
  /** Update the sort configuration */
  setSortConfig: (config: SortConfig) => void;
  
  /** Sort by a specific field, toggling direction if already sorting by that field */
  sortBy: (field: SortField) => void;
  
  /** Toggle the sort direction */
  toggleSortDirection: () => void;
  
  /** Reset sort to default */
  resetSort: () => void;
  
  /** Reset pagination to page 1 (callback) */
  onFilterChange?: () => void;
}

/**
 * Hook for managing moderation queue filters
 * 
 * @param config - Configuration options
 * @returns Filter state and actions
 * 
 * @example
 * ```tsx
 * const filters = useModerationFilters({
 *   persist: true,
 *   debounceDelay: 300
 * });
 * 
 * // Use in component
 * <Select value={filters.entityFilter} onValueChange={filters.setEntityFilter}>
 *   ...
 * </Select>
 * ```
 */
export function useModerationFilters(
  config: ModerationFiltersConfig & { onFilterChange?: () => void } = {}
): ModerationFilters {
  const {
    initialEntityFilter = 'all',
    initialStatusFilter = 'pending',
    initialTab = 'mainQueue',
    debounceDelay = MODERATION_CONSTANTS.FILTER_DEBOUNCE_MS,
    persist = true,
    storageKey = 'moderationQueue_filters',
    initialSortConfig = { field: 'created_at', direction: 'asc' },
    onFilterChange,
  } = config;

  // Load persisted filters on mount
  const loadPersistedFilters = useCallback(() => {
    if (!persist) return null;
    
    try {
      const saved = localStorage.getItem(storageKey);
      if (saved) {
        return JSON.parse(saved);
      }
    } catch (error: unknown) {
      console.error('Failed to load persisted filters:', error);
    }
    
    return null;
  }, [persist, storageKey]);

  // Load persisted sort
  const loadPersistedSort = useCallback((): SortConfig => {
    if (!persist) return initialSortConfig;
    
    try {
      const saved = localStorage.getItem(`${storageKey}_sort`);
      if (saved) {
        const parsed = JSON.parse(saved);
        if (parsed.field && parsed.direction) {
          return parsed;
        }
      }
    } catch (error: unknown) {
      console.error('Failed to load persisted sort:', error);
    }
    
    return initialSortConfig;
  }, [persist, storageKey, initialSortConfig]);

  const persisted = loadPersistedFilters();

  // Filter state
  const [entityFilter, setEntityFilterState] = useState<EntityFilter>(
    persisted?.entityFilter || initialEntityFilter
  );
  const [statusFilter, setStatusFilterState] = useState<StatusFilter>(
    persisted?.statusFilter || initialStatusFilter
  );
  const [activeTab, setActiveTabState] = useState<QueueTab>(
    persisted?.activeTab || initialTab
  );

  // Sort state
  const [sortConfig, setSortConfigState] = useState<SortConfig>(loadPersistedSort);

  // Debounced filters for API calls
  const debouncedEntityFilter = useDebounce(entityFilter, debounceDelay);
  const debouncedStatusFilter = useDebounce(statusFilter, debounceDelay);
  
  // Debounced sort (0ms for immediate feedback)
  const debouncedSortConfig = useDebounce(sortConfig, 0);

  // Persist filters to localStorage
  useEffect(() => {
    if (persist) {
      storage.setJSON(storageKey, {
        entityFilter,
        statusFilter,
        activeTab,
      });
    }
  }, [entityFilter, statusFilter, activeTab, persist, storageKey]);

  // Persist sort to localStorage
  useEffect(() => {
    if (persist) {
      storage.setJSON(`${storageKey}_sort`, sortConfig);
    }
  }, [sortConfig, persist, storageKey]);

  // Set entity filter with logging and pagination reset
  const setEntityFilter = useCallback((filter: EntityFilter) => {
    logger.log('🔍 Entity filter changed:', filter);
    setEntityFilterState(filter);
    onFilterChange?.();
  }, [onFilterChange]);

  // Set status filter with logging and pagination reset
  const setStatusFilter = useCallback((filter: StatusFilter) => {
    logger.log('🔍 Status filter changed:', filter);
    setStatusFilterState(filter);
    onFilterChange?.();
  }, [onFilterChange]);

  // Set active tab with logging and pagination reset
  const setActiveTab = useCallback((tab: QueueTab) => {
    logger.log('🔍 Tab changed:', tab);
    setActiveTabState(tab);
    onFilterChange?.();
  }, [onFilterChange]);

  // Sort callbacks
  const setSortConfig = useCallback((config: SortConfig) => {
    logger.log('📝 [SORT] Sort config changed:', config);
    setSortConfigState(config);
  }, []);

  const sortBy = useCallback((field: SortField) => {
    setSortConfigState(prev => ({
      field,
      direction: prev.field === field 
        ? (prev.direction === 'asc' ? 'desc' : 'asc')
        : 'asc'
    }));
  }, []);

  const toggleSortDirection = useCallback(() => {
    setSortConfigState(prev => ({
      ...prev,
      direction: prev.direction === 'asc' ? 'desc' : 'asc'
    }));
  }, []);

  const resetSort = useCallback(() => {
    setSortConfigState(initialSortConfig);
  }, [initialSortConfig]);

  // Clear all filters
  const clearFilters = useCallback(() => {
    logger.log('🔍 Filters cleared');
    setEntityFilterState(initialEntityFilter);
    setStatusFilterState(initialStatusFilter);
    setActiveTabState(initialTab);
    setSortConfigState(initialSortConfig);
  }, [initialEntityFilter, initialStatusFilter, initialTab, initialSortConfig]);

  // Check if non-default filters are active
  const hasActiveFilters =
    entityFilter !== initialEntityFilter ||
    statusFilter !== initialStatusFilter ||
    activeTab !== initialTab ||
    sortConfig.field !== initialSortConfig.field ||
    sortConfig.direction !== initialSortConfig.direction;

  // Return without useMemo wrapper (OPTIMIZED)
  return {
    entityFilter,
    statusFilter,
    activeTab,
    debouncedEntityFilter,
    debouncedStatusFilter,
    setEntityFilter,
    setStatusFilter,
    setActiveTab,
    clearFilters,
    hasActiveFilters,
    sortConfig,
    debouncedSortConfig,
    setSortConfig,
    sortBy,
    toggleSortDirection,
    resetSort,
    onFilterChange,
  };
}
