/**
 * React hook for loading filter config metadata used by the filter tab.
 */
import { useCallback, useEffect, useRef, useState } from "react";
import { fetchFilters, createFilter, assignFilterToJail } from "../api/config";
import { handleFetchError } from "../utils/fetchError";
import type { FilterConfig, FilterCreateRequest } from "../types/config";

export interface UseFilterListResult {
  filters: FilterConfig[];
  loading: boolean;
  error: string | null;
  refresh: () => void;
  createFilter: (payload: FilterCreateRequest) => Promise<FilterConfig>;
  assignFilterToJail: (jailName: string, payload: { filter_name: string }, reload: boolean) => Promise<void>;
}

/**
 * Load the filter inventory and expose refresh semantics.
 */
export function useFilterList(): UseFilterListResult {
  const [filters, setFilters] = useState<FilterConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const abortRef = useRef<AbortController | null>(null);

  const refresh = useCallback((): void => {
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;

    setLoading(true);
    setError(null);

    fetchFilters()
      .then((resp) => {
        if (!controller.signal.aborted) {
          setFilters(resp.filters);
        }
      })
      .catch((err: unknown) => {
        if (!controller.signal.aborted) {
          handleFetchError(err, setError, "Failed to load filters");
        }
      })
      .finally(() => {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      });
  }, []);

  useEffect(() => {
    refresh();
    return (): void => {
      abortRef.current?.abort();
    };
  }, [refresh]);

  const handleCreateFilter = useCallback(
    async (payload: FilterCreateRequest): Promise<FilterConfig> => {
      return await createFilter(payload);
    },
    [],
  );

  const handleAssignFilterToJail = useCallback(
    async (jailName: string, payload: { filter_name: string }, reload: boolean): Promise<void> => {
      await assignFilterToJail(jailName, payload, reload);
    },
    [],
  );

  return {
    filters,
    loading,
    error,
    refresh,
    createFilter: handleCreateFilter,
    assignFilterToJail: handleAssignFilterToJail,
  };
}
