import { useEffect, useState, type ReactNode } from "react";
import { FilterContext } from "./FilterContext";
import type { SearchFilters } from "../types/search";

const STORE_KEY = "potion_app_search_filters";

const DEFAULT_FILTERS: SearchFilters = {
  Search: "",
  MealType: 0,
  Time: 0,
  Difficulty: 0,
  ServingSize: 0,
  Favorites: false,
};

export function FilterProvider({ children }: { children: ReactNode }) {
  const [filters, setFilters] = useState<SearchFilters>(() => {
    // Window would not be found, something is wrong with the browser
    if (typeof window === "undefined") return DEFAULT_FILTERS;

    try {
      const stored = window.localStorage.getItem(STORE_KEY);
      return stored ? (JSON.parse(stored) as SearchFilters) : DEFAULT_FILTERS;
    } catch {
      return DEFAULT_FILTERS;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(STORE_KEY, JSON.stringify(filters));
    } catch {
      // TODO: Error here?
      // ignore quota / access errors
    }
  }, [filters]);

  return (
    <FilterContext value={{ filters, setFilters }}>
      {children}
    </FilterContext>
  )
}
