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);

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.VND);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  const supportedCurrencies = [
    CURRENCY.VND,
    CURRENCY.USD,
    CURRENCY.EUR,
    '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.VND);
        localStorage.setItem('currency', CURRENCY.VND);
      }
    } catch (error) {
      console.error('Error loading platform currency:', error);
      
      setCurrencyState(CURRENCY.VND);
      localStorage.setItem('currency', CURRENCY.VND);
    } finally {
      setIsLoading(false);
    }
  };

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

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

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

