import { useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';

import { type SearchFilter } from 'src/pages/dashboard/search/types';

const VALID_CATEGORIES: SearchFilter[] = ['all', 'person', 'post', 'group'];

const isValidCategory = (value: string | null): value is SearchFilter =>
  value !== null && VALID_CATEGORIES.includes(value as SearchFilter);

export const useSearchUrlState = () => {
  const [searchParams, setSearchParams] = useSearchParams();

  const query = searchParams.get('q') ?? '';
  const rawCategory = searchParams.get('category');
  const category: SearchFilter = isValidCategory(rawCategory)
    ? rawCategory
    : 'all';

  const setCategory = useCallback(
    (next: SearchFilter) => {
      setSearchParams(
        prev => {
          const params = new URLSearchParams(prev);
          params.set('category', next);
          return params;
        },
        { replace: false },
      );
    },
    [setSearchParams],
  );

  return { query, category, setCategory };
};
