"use client";

import { useCallback, useEffect, useState } from "react";

export type SavedFilter = {
  id: string;
  name: string;
  values: Record<string, string>;
  createdAt: string;
};

/** Persist named filter presets in localStorage per page key. */
export function useSavedFilters(storageKey: string) {
  const fullKey = `torbatyar:saved-filters:${storageKey}`;

  const [saved, setSaved] = useState<SavedFilter[]>([]);

  useEffect(() => {
    try {
      const raw = localStorage.getItem(fullKey);
      if (raw) setSaved(JSON.parse(raw) as SavedFilter[]);
    } catch {
      setSaved([]);
    }
  }, [fullKey]);

  const persist = useCallback(
    (next: SavedFilter[]) => {
      setSaved(next);
      localStorage.setItem(fullKey, JSON.stringify(next));
    },
    [fullKey]
  );

  const saveFilter = useCallback(
    (name: string, values: Record<string, string>) => {
      const entry: SavedFilter = {
        id: crypto.randomUUID(),
        name,
        values,
        createdAt: new Date().toISOString(),
      };
      persist([entry, ...saved].slice(0, 12));
      return entry;
    },
    [persist, saved]
  );

  const removeFilter = useCallback(
    (id: string) => persist(saved.filter((f) => f.id !== id)),
    [persist, saved]
  );

  return { saved, saveFilter, removeFilter };
}
