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

import { useCallback, 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 lookup = useCallback((ip: string) => {
    setLoading(true);
    setError(null);
    setResult(null);

    lookupIp(ip)
      .then((res) => {
        setResult(res);
      })
      .catch((err: unknown) => {
        handleFetchError(err, setError, "Failed to lookup IP");
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

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

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