import { useState, useEffect, useCallback } from 'react';
import { TownApi } from '@/services/api/townApi';
import { clearWorkingBaseUrlCache } from '@/services/api/client';
import { TownItem } from '@/types';

/**
 * Hook to fetch dynamic departure and destination towns.
 * No hardcoded fallback data.
 */
export function useTowns() {
  const [towns, setTowns] = useState<TownItem[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const fetchTowns = useCallback(async (isRetry = false) => {
    setLoading(true);
    if (isRetry) {
      clearWorkingBaseUrlCache();
    }
    try {
      const data = await TownApi.getTowns();
      setTowns(data);
      if (!data || data.length === 0) {
        setError('No towns found');
      } else {
        setError(null);
      }
    } catch (err: any) {
      setTowns([]);
      setError(err?.message || 'Failed to fetch towns from server');
    } finally {
      setLoading(false);
    }
  }, []);

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

  return { towns, loading, error, refetch: () => fetchTowns(true) };
}
