"use client";

import { useCallback, useMemo } from "react";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import type { FieldType } from "@capakraken/shared";

// Typed-routes are enabled in next.config.ts; bypass for dynamic URLs.
type PlainRouter = { replace: (url: string, opts?: { scroll?: boolean }) => void };

export interface CustomFieldFilter {
  key: string;
  value: string;
  type: FieldType;
}

/**
 * URL-persisted filter state for list views.
 * Built-in filters (search, chapter) use simple query params.
 * Custom field filters encode as: cf_<fieldKey>=<value> + cft_<fieldKey>=<FieldType>
 */
export function useFilters() {
  const router = useRouter() as unknown as PlainRouter;
  const searchParams = useSearchParams();
  const pathname = usePathname();

  const search = searchParams.get("search") ?? "";
  const chapter = searchParams.get("chapter") ?? "";
  const status = searchParams.get("status") ?? "";

  const customFieldFilters: CustomFieldFilter[] = useMemo(() => {
    const filters: CustomFieldFilter[] = [];
    for (const [param, value] of searchParams.entries()) {
      if (param.startsWith("cf_") && !param.startsWith("cft_")) {
        const fieldKey = param.slice(3);
        const type = (searchParams.get(`cft_${fieldKey}`) ?? "TEXT") as FieldType;
        if (value) filters.push({ key: fieldKey, value, type });
      }
    }
    return filters;
  }, [searchParams]);

  const setFilter = useCallback(
    (key: string, value: string) => {
      const params = new URLSearchParams(searchParams.toString());
      if (value) {
        params.set(key, value);
      } else {
        params.delete(key);
      }
      router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    },
    [router, searchParams, pathname],
  );

  const setCustomFieldFilter = useCallback(
    (fieldKey: string, value: string, type: FieldType) => {
      const params = new URLSearchParams(searchParams.toString());
      if (value) {
        params.set(`cf_${fieldKey}`, value);
        params.set(`cft_${fieldKey}`, type);
      } else {
        params.delete(`cf_${fieldKey}`);
        params.delete(`cft_${fieldKey}`);
      }
      router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    },
    [router, searchParams, pathname],
  );

  const clearFilters = useCallback(() => {
    router.replace(pathname, { scroll: false });
  }, [router, pathname]);

  const hasActiveFilters =
    search !== "" || chapter !== "" || status !== "" || customFieldFilters.length > 0;

  return {
    search,
    chapter,
    status,
    customFieldFilters,
    setFilter,
    setCustomFieldFilter,
    clearFilters,
    hasActiveFilters,
  };
}
