import React, { createContext, useContext, useState, useCallback } from 'react';

interface FilterContextType {
  states: Record<string, any>;
  setState: (key: string, value: any) => void;
}

const FilterContext = createContext<FilterContextType | undefined>(undefined);

export function FilterProvider({ children }: { children: React.ReactNode }) {
  const [states, setStates] = useState<Record<string, any>>({});

  const setState = useCallback((key: string, value: any) => {
    setStates(prev => ({
      ...prev,
      [key]: typeof value === 'function' ? value(prev[key]) : value
    }));
  }, []);

  return (
    <FilterContext.Provider value={{ states, setState }}>
      {children}
    </FilterContext.Provider>
  );
}

export function usePersistentState<T>(key: string, defaultValue: T): [T, (value: T | ((prev: T) => T)) => void] {
  const context = useContext(FilterContext);
  if (!context) {
    throw new Error('usePersistentState must be used within a FilterProvider');
  }

  const state = context.states[key] !== undefined ? context.states[key] : defaultValue;
  
  const setState = useCallback((value: T | ((prev: T) => T)) => {
    context.setState(key, (current: any) => {
      const actualCurrent = current !== undefined ? current : defaultValue;
      return typeof value === 'function' ? (value as any)(actualCurrent) : value;
    });
  }, [context, key, defaultValue]);

  return [state, setState];
}
