import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  ReactNode,
} from 'react';
import { CURRENCY } from '../../../shared/utils/constants';
import systemSettingsService from '../../../features/system/services/systemSettingsService';

type CurrencyContextValue = {
  currency: string;
  isLoading: boolean;
  supportedCurrencies: string[];
  refreshCurrency: () => Promise<void>;
};

const CurrencyContext = createContext<CurrencyContextValue | undefined>(undefined);

// eslint-disable-next-line react-refresh/only-export-components
export const useCurrency = () => {
  const context = useContext(CurrencyContext);
  if (!context) {
    throw new Error('useCurrency must be used within CurrencyProvider');
  }
  return context;
};

interface CurrencyProviderProps {
  children: ReactNode;
}

export const CurrencyProvider: React.FC<CurrencyProviderProps> = ({ children }) => {
  const [currency, setCurrencyState] = useState<string>(CURRENCY.USD);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  const supportedCurrencies = [
    CURRENCY.USD,
    CURRENCY.EUR,
    CURRENCY.GBP,
    'JPY',
    'CNY',
    'KRW',
    'SGD',
    'THB',
    'AUD',
    'CAD',
  ];

  
  const loadCurrency = async () => {
    try {
      setIsLoading(true);
      const response = await systemSettingsService.getPlatformCurrency();
      if (response.data?.currency && supportedCurrencies.includes(response.data.currency)) {
        const platformCurrency = response.data.currency;
        setCurrencyState(platformCurrency);
        
        localStorage.setItem('currency', platformCurrency);
      } else {
        
        setCurrencyState(CURRENCY.USD);
        localStorage.setItem('currency', CURRENCY.USD);
      }
    } catch (error) {
      console.error('Error loading platform currency:', error);
      
      setCurrencyState(CURRENCY.USD);
      localStorage.setItem('currency', CURRENCY.USD);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadCurrency();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const refreshCurrency = async () => {
    await loadCurrency();
    
    if (typeof window !== 'undefined') {
      window.dispatchEvent(new CustomEvent('currencyChanged', {
        detail: { currency: localStorage.getItem('currency') || CURRENCY.USD }
      }));
    }
  };

  return (
    <CurrencyContext.Provider
      value={{
        currency,
        isLoading,
        supportedCurrencies,
        refreshCurrency,
      }}
    >
      {children}
    </CurrencyContext.Provider>
  );
};

