import { useCallback, useEffect, useState } from 'react';
import { exchangeApi } from '../services/exchangeApi';
import type {
  CreateExchangeRequest,
  CreateProviderMappingRequest,
  Exchange,
  ExchangeDetails,
  ExchangeStats,
  ProviderExchange,
  ProviderMapping,
  UpdateExchangeRequest,
  UpdateProviderMappingRequest,
} from '../types/index';

export function useExchanges() {
  const [exchanges, setExchanges] = useState<Exchange[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchExchanges = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await exchangeApi.getExchanges();
      setExchanges(data);
    } catch (err) {
      // Error fetching exchanges - error state will show in UI
      setError(err instanceof Error ? err.message : 'Failed to fetch exchanges');
      setExchanges([]);
    } finally {
      setLoading(false);
    }
  }, []);

  const updateExchange = useCallback(
    async (id: string, updates: UpdateExchangeRequest): Promise<boolean> => {
      try {
        await exchangeApi.updateExchange(id, updates);
        await fetchExchanges(); // Refresh the list
        return true;
      } catch (err) {
        // Error updating exchange - error state will show in UI
        setError(err instanceof Error ? err.message : 'Failed to update exchange');
        return false;
      }
    },
    [fetchExchanges]
  );

  const createExchange = useCallback(
    async (request: CreateExchangeRequest): Promise<Exchange> => {
      try {
        const exchange = await exchangeApi.createExchange(request);
        await fetchExchanges(); // Refresh the list
        return exchange;
      } catch (err) {
        // Error creating exchange - error state will show in UI
        setError(err instanceof Error ? err.message : 'Failed to create exchange');
        throw err;
      }
    },
    [fetchExchanges]
  );

  const fetchExchangeDetails = useCallback(async (id: string): Promise<ExchangeDetails | null> => {
    try {
      return await exchangeApi.getExchangeById(id);
    } catch (err) {
      // Error fetching exchange details - error state will show in UI
      setError(err instanceof Error ? err.message : 'Failed to fetch exchange details');
      return null;
    }
  }, []);

  const fetchStats = useCallback(async (): Promise<ExchangeStats | null> => {
    try {
      return await exchangeApi.getExchangeStats();
    } catch (err) {
      // Error fetching stats - error state will show in UI
      setError(err instanceof Error ? err.message : 'Failed to fetch stats');
      return null;
    }
  }, []);

  const fetchProviderMappings = useCallback(
    async (provider?: string): Promise<ProviderMapping[]> => {
      try {
        return await exchangeApi.getProviderMappings(provider);
      } catch (err) {
        // Error fetching provider mappings - error state will show in UI
        setError(err instanceof Error ? err.message : 'Failed to fetch provider mappings');
        return [];
      }
    },
    []
  );

  const updateProviderMapping = useCallback(
    async (id: string, updates: UpdateProviderMappingRequest): Promise<boolean> => {
      try {
        await exchangeApi.updateProviderMapping(id, updates);
        return true;
      } catch (err) {
        // Error updating provider mapping - error state will show in UI
        setError(err instanceof Error ? err.message : 'Failed to update provider mapping');
        return false;
      }
    },
    []
  );

  const createProviderMapping = useCallback(
    async (request: CreateProviderMappingRequest): Promise<ProviderMapping | null> => {
      try {
        return await exchangeApi.createProviderMapping(request);
      } catch (err) {
        // Error creating provider mapping - error state will show in UI
        setError(err instanceof Error ? err.message : 'Failed to create provider mapping');
        return null;
      }
    },
    []
  );

  const fetchProviders = useCallback(async (): Promise<string[]> => {
    try {
      return await exchangeApi.getProviders();
    } catch (err) {
      // Error fetching providers - error state will show in UI
      setError(err instanceof Error ? err.message : 'Failed to fetch providers');
      return [];
    }
  }, []);

  const fetchUnmappedProviderExchanges = useCallback(
    async (provider: string): Promise<ProviderExchange[]> => {
      try {
        return await exchangeApi.getUnmappedProviderExchanges(provider);
      } catch (err) {
        // Error fetching unmapped exchanges - error state will show in UI
        setError(err instanceof Error ? err.message : 'Failed to fetch unmapped exchanges');
        return [];
      }
    },
    []
  );

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

  return {
    exchanges,
    loading,
    error,
    refetch: fetchExchanges,
    updateExchange,
    createExchange,
    fetchExchangeDetails,
    fetchStats,
    fetchProviderMappings,
    updateProviderMapping,
    createProviderMapping,
    fetchProviders,
    fetchUnmappedProviderExchanges,
  };
}
