import { useState, useEffect, useCallback } from 'react';
import { AgencyApi } from '@/services/api/agencyApi';
import { clearWorkingBaseUrlCache } from '@/services/api/client';
import { Agency } from '@/types/agency';

/**
 * Hook to fetch single agency details by ID.
 * No hardcoded fallback data.
 */
export function useAgency(id?: string) {
  const [agency, setAgency] = useState<Agency | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [isNotFound, setIsNotFound] = useState<boolean>(false);
  const [isNetworkError, setIsNetworkError] = useState<boolean>(false);

  const fetchAgency = useCallback(async (isRetry = false) => {
    if (!id) return;
    setLoading(true);
    setError(null);
    setIsNotFound(false);
    setIsNetworkError(false);

    if (isRetry) {
      clearWorkingBaseUrlCache();
    }

    try {
      const data = await AgencyApi.getAgencyById(id);
      setAgency(data);
      if (!data) {
        setIsNotFound(true);
        setError('AGENCY_NOT_FOUND');
      } else {
        setError(null);
      }
    } catch (err: any) {
      setAgency(null);
      const msg = err?.message || 'Failed to fetch agency details from server';
      const isNet =
        err?.isNetworkError ||
        msg.toLowerCase().includes('connect') ||
        msg.toLowerCase().includes('network') ||
        msg.toLowerCase().includes('failed to fetch');
      setIsNetworkError(isNet);
      setIsNotFound(err?.isNotFound || err?.status === 404);
      setError(msg);
    } finally {
      setLoading(false);
    }
  }, [id]);

  useEffect(() => {
    fetchAgency();
  }, [fetchAgency]);

  return {
    agency,
    loading,
    error,
    isNotFound,
    isNetworkError,
    refetch: () => fetchAgency(true),
  };
}
