/**
 * React hook for looking up a single IP address.
 */

import { useCallback, useEffect, useRef, useState } from "react";
import { handleFetchError } from "../utils/fetchError";
import { lookupIp } from "../api/jails";
import type { IpLookupResponse } from "../types/jail";

export interface UseIpLookupResult {
  result: IpLookupResponse | null;
  loading: boolean;
  error: string | null;
  lookup: (ip: string) => void;
  clear: () => void;
}

/**
 * Manage IP lookup state and expose a lookup trigger.
 */
export function useIpLookup(): UseIpLookupResult {
  const [result, setResult] = useState<IpLookupResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const abortRef = useRef<AbortController | null>(null);

  const lookup = useCallback((ip: string): void => {
    (async (): Promise<void> => {
      // Abort any previous lookup
      abortRef.current?.abort();
      const ctrl = new AbortController();
      abortRef.current = ctrl;

      setLoading(true);
      setError(null);
      setResult(null);

      try {
        const res = await lookupIp(ip, ctrl.signal);
        if (ctrl.signal.aborted) return;
        setResult(res);
      } catch (err: unknown) {
        if (ctrl.signal.aborted) return;
        handleFetchError(err, setError, "Failed to lookup IP");
      } finally {
        if (!ctrl.signal.aborted) {
          setLoading(false);
        }
      }
    })().catch(() => {
      // Silently ignore abort errors
    });
  }, []);

  const clear = useCallback(() => {
    setResult(null);
    setError(null);
  }, []);

  // Cleanup: abort any pending lookup on unmount
  useEffect(() => {
    return (): void => {
      abortRef.current?.abort();
    };
  }, []);

  return { result, loading, error, lookup, clear };
}
