import React from 'react';
import { useTranslation } from 'react-i18next';
import { currencies, getSortedCurrencies, getCurrencyByCode } from '../config/currencies';

/**
 * Componente seletor de moeda
 * Exibe dropdown com moedas ordenadas (comuns primeiro)
 */
const CurrencySelector = ({ 
  value = 'BRL', 
  onChange, 
  className = '',
  showSymbol = true,
  disabled = false,
  name = 'currency',
  id = 'currency',
}) => {
  const { t } = useTranslation();
  const sortedCurrencies = getSortedCurrencies();
  const currentCurrency = getCurrencyByCode(value);

  const handleChange = (e) => {
    if (onChange) {
      onChange(e.target.value);
    }
  };

  return (
    <select
      id={id}
      name={name}
      className={`form-select ${className}`}
      value={value}
      onChange={handleChange}
      disabled={disabled}
    >
      {sortedCurrencies.map((currency) => (
        <option key={currency.code} value={currency.code}>
          {showSymbol && `${currency.symbol} `}
          {currency.code} - {t(currency.name)}
        </option>
      ))}
    </select>
  );
};

/**
 * Componente que exibe o valor formatado com a moeda
 */
export const CurrencyDisplay = ({ value, currency = 'BRL', className = '' }) => {
  const currencyInfo = getCurrencyByCode(currency);
  const numValue = parseFloat(value) || 0;
  
  const formatted = new Intl.NumberFormat(currencyInfo.locale, {
    style: 'currency',
    currency: currencyInfo.code,
    minimumFractionDigits: currencyInfo.decimals,
    maximumFractionDigits: currencyInfo.decimals,
  }).format(numValue);

  const isNegative = numValue < 0;
  
  return (
    <span className={`${className} ${isNegative ? 'text-danger' : ''}`}>
      {formatted}
    </span>
  );
};

/**
 * Input para valores monetários com máscara
 */
export const CurrencyInput = ({
  value,
  onChange,
  currency = 'BRL',
  className = '',
  placeholder,
  disabled = false,
  name,
  id,
  ...props
}) => {
  const { t } = useTranslation();
  const currencyInfo = getCurrencyByCode(currency);

  const handleChange = (e) => {
    let rawValue = e.target.value;
    
    // Remove tudo exceto números e separadores
    rawValue = rawValue.replace(/[^\d.,\-]/g, '');
    
    // Converte para formato numérico
    // Trata caso brasileiro (vírgula decimal) vs americano (ponto decimal)
    if (currencyInfo.locale.includes('BR') || currencyInfo.locale.includes('ES')) {
      // Formato brasileiro/espanhol: 1.234,56
      rawValue = rawValue.replace(/\.(?=.*,)/g, ''); // Remove pontos de milhar
      rawValue = rawValue.replace(',', '.'); // Vírgula para ponto
    } else {
      // Formato americano: 1,234.56
      rawValue = rawValue.replace(/,(?=.*\.)/g, ''); // Remove vírgulas de milhar
    }
    
    if (onChange) {
      onChange(rawValue);
    }
  };

  return (
    <div className="input-group">
      <span className="input-group-text">{currencyInfo.symbol}</span>
      <input
        type="text"
        id={id}
        name={name}
        className={`form-control ${className}`}
        value={value}
        onChange={handleChange}
        placeholder={placeholder || '0.00'}
        disabled={disabled}
        inputMode="decimal"
        {...props}
      />
    </div>
  );
};

export default CurrencySelector;
