/**
 * React hook for listing and mutating blocklist sources.
 */

import { useCallback, useEffect, useRef, useState } from "react";
import {
  createBlocklist,
  deleteBlocklist,
  fetchBlocklists,
  previewBlocklist,
  updateBlocklist,
} from "../api/blocklist";
import { handleFetchError } from "../utils/fetchError";
import type {
  BlocklistSource,
  BlocklistSourceCreate,
  BlocklistSourceUpdate,
  PreviewResponse,
} from "../types/blocklist";

export interface UseBlocklistsReturn {
  sources: BlocklistSource[];
  loading: boolean;
  error: string | null;
  refresh: () => void;
  createSource: (payload: BlocklistSourceCreate) => Promise<BlocklistSource>;
  updateSource: (id: number, payload: BlocklistSourceUpdate) => Promise<BlocklistSource>;
  removeSource: (id: number) => Promise<void>;
  previewSource: (id: number) => Promise<PreviewResponse>;
}

/**
 * Load all blocklist sources and expose CRUD operations.
 */
export function useBlocklists(): UseBlocklistsReturn {
  const [sources, setSources] = useState<BlocklistSource[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const abortRef = useRef<AbortController | null>(null);

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

    setLoading(true);
    setError(null);

    fetchBlocklists()
      .then((data) => {
        if (!ctrl.signal.aborted) {
          setSources(data.sources);
          setLoading(false);
        }
      })
      .catch((err: unknown) => {
        if (!ctrl.signal.aborted) {
          handleFetchError(err, setError, "Failed to load blocklists");
          setLoading(false);
        }
      });
  }, []);

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

  const createSource = useCallback(
    async (payload: BlocklistSourceCreate): Promise<BlocklistSource> => {
      const created = await createBlocklist(payload);
      setSources((prev) => [...prev, created]);
      return created;
    },
    [],
  );

  const updateSource = useCallback(
    async (id: number, payload: BlocklistSourceUpdate): Promise<BlocklistSource> => {
      const updated = await updateBlocklist(id, payload);
      setSources((prev) => prev.map((s) => (s.id === id ? updated : s)));
      return updated;
    },
    [],
  );

  const removeSource = useCallback(async (id: number): Promise<void> => {
    await deleteBlocklist(id);
    setSources((prev) => prev.filter((s) => s.id !== id));
  }, []);

  const previewSource = useCallback(async (id: number): Promise<PreviewResponse> => {
    return previewBlocklist(id);
  }, []);

  return {
    sources,
    loading,
    error,
    refresh: load,
    createSource,
    updateSource,
    removeSource,
    previewSource,
  };
}
