import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  ReactNode,
} from 'react';
import { CURRENCY } from '../utils/constants';
import systemSettingsService from '../services/api/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',
  ];

  // Load platform currency from system settings
  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);
        // Store in localStorage so formatCurrency can access it
        localStorage.setItem('currency', platformCurrency);
      } else {
        // Fallback to default
        setCurrencyState(CURRENCY.VND);
        localStorage.setItem('currency', CURRENCY.VND);
      }
    } catch (error) {
      console.error('Error loading platform currency:', error);
      // Fallback to default
      setCurrencyState(CURRENCY.VND);
      localStorage.setItem('currency', CURRENCY.VND);
    } finally {
      setIsLoading(false);
    }
  };

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

  const refreshCurrency = async () => {
    await loadCurrency();
    // Dispatch a custom event to notify all components of currency change
    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>
  );
};

