import React, { useState } from 'react';
import { useCurrency } from '../../features/payments/contexts/CurrencyContext';
import { Globe } from 'lucide-react';
import { toast } from 'react-toastify';
import systemSettingsService from '../../features/system/services/systemSettingsService';
import useAuthStore from '../../store/useAuthStore';
import { getCurrencySymbol } from '../utils/format';

interface CurrencySelectorProps {
  className?: string;
  showLabel?: boolean;
  variant?: 'dropdown' | 'select';
  adminMode?: boolean; 
}

const CurrencySelector: React.FC<CurrencySelectorProps> = ({
  className = '',
  showLabel = true,
  variant = 'select',
  adminMode = false,
}) => {
  const { currency, supportedCurrencies, isLoading, refreshCurrency } = useCurrency();
  const { userInfo } = useAuthStore();
  const [, setSaving] = useState(false);
  const isAdmin = userInfo?.role === 'admin';

  const currencyNames: Record<string, string> = {
    USD: 'US Dollar',
    EUR: 'Euro',
    GBP: 'British Pound',
    JPY: 'Japanese Yen',
    CNY: 'Chinese Yuan',
    KRW: 'South Korean Won',
    SGD: 'Singapore Dollar',
    THB: 'Thai Baht',
    AUD: 'Australian Dollar',
    CAD: 'Canadian Dollar',
  };

  const getCurrencyDisplayName = (code: string): string => {
    const name = currencyNames[code] || code;
    const symbol = getCurrencySymbol(code);
    return `${name} (${symbol})`;
  };

  const handleChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newCurrency = e.target.value;
    
    
    if (adminMode && isAdmin) {
      try {
        setSaving(true);
        await systemSettingsService.updatePlatformCurrency(newCurrency);
        await refreshCurrency();
        toast.success('Platform currency updated successfully');
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to update platform currency';
        toast.error(message);
      } finally {
        setSaving(false);
      }
    }
  };

  if (isLoading) {
    return (
      <div className={`flex items-center gap-2 ${className}`}>
        {showLabel && <span className="text-sm text-gray-600">Currency:</span>}
        <div className="h-8 w-24 bg-gray-200 animate-pulse rounded"></div>
      </div>
    );
  }

  if (variant === 'dropdown') {
    return (
      <div className={`relative ${className}`}>
        {showLabel && (
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Currency
          </label>
        )}
        <div className="relative">
          <select
            value={currency}
            onChange={handleChange}
            className="appearance-none bg-white border border-gray-300 rounded-lg px-4 py-2 pr-8 text-sm font-medium text-gray-900 focus:outline-none focus:ring-2 focus:ring-[var(--luxury-gold)] focus:border-[var(--luxury-gold)] transition-colors cursor-pointer"
          >
            {supportedCurrencies.map((curr) => (
              <option key={curr} value={curr}>
                {curr} - {getCurrencyDisplayName(curr)}
              </option>
            ))}
          </select>
          <div className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none">
            <Globe className="w-4 h-4 text-gray-400" />
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`flex items-center gap-2 ${className}`}>
      {showLabel && (
        <span className="text-sm font-medium text-gray-700 flex items-center gap-1">
          <Globe className="w-4 h-4" />
          Currency:
        </span>
      )}
      <select
        value={currency}
        onChange={handleChange}
        className="px-3 py-1.5 border border-gray-300 rounded-md text-sm font-medium text-gray-900 bg-white focus:outline-none focus:ring-2 focus:ring-[var(--luxury-gold)] focus:border-[var(--luxury-gold)] transition-colors cursor-pointer"
      >
        {supportedCurrencies.map((curr) => (
          <option key={curr} value={curr}>
            {curr}
          </option>
        ))}
      </select>
    </div>
  );
};

export default CurrencySelector;

