import { useState, useEffect, Dispatch, SetStateAction } from 'react';

/**
 * Custom hook for persisting library filter state in sessionStorage.
 * Filters are preserved during the browser session but cleared when the tab is closed.
 *
 * @param key - Unique identifier for the filter value in sessionStorage
 * @param defaultValue - Default value if no stored value exists
 * @returns Tuple of [value, setValue] similar to useState
 */
export function useLibraryFilters<T>(
  key: string,
  defaultValue: T
): [T, Dispatch<SetStateAction<T>>] {
  // Initialize state from sessionStorage or use default value
  const [value, setValue] = useState<T>(() => {
    // SSR safety: sessionStorage only available in browser
    if (typeof window === 'undefined') {
      return defaultValue;
    }

    try {
      const stored = sessionStorage.getItem(`library_filter_${key}`);
      if (stored === null) {
        return defaultValue;
      }
      return JSON.parse(stored) as T;
    } catch (error) {
      console.warn(`Failed to parse sessionStorage value for library_filter_${key}:`, error);
      return defaultValue;
    }
  });

  // Persist to sessionStorage whenever value changes
  useEffect(() => {
    if (typeof window === 'undefined') return;

    try {
      sessionStorage.setItem(`library_filter_${key}`, JSON.stringify(value));
    } catch (error) {
      console.warn(`Failed to save to sessionStorage for library_filter_${key}:`, error);
    }
  }, [key, value]);

  return [value, setValue];
}

/**
 * Clear all library filters from sessionStorage.
 * Useful for "Clear Filters" button or when switching libraries.
 */
export function clearLibraryFilters(): void {
  if (typeof window === 'undefined') return;

  try {
    // Get all sessionStorage keys
    const keys = Object.keys(sessionStorage);

    // Remove only library filter keys
    keys.forEach(key => {
      if (key.startsWith('library_filter_')) {
        sessionStorage.removeItem(key);
      }
    });
  } catch (error) {
    console.warn('Failed to clear library filters from sessionStorage:', error);
  }
}
