import React, { useState, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { availableLanguages, changeLanguage, getCurrentLanguage } from '../i18n';

/**
 * Componente seletor de idioma
 * Exibe dropdown com bandeiras e nomes dos idiomas
 */
const LanguageSelector = ({ variant = 'dropdown', className = '' }) => {
  const { i18n } = useTranslation();
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef(null);

  const currentLang = availableLanguages.find(l => l.code === i18n.language) 
    || availableLanguages[0];

  // Fecha dropdown ao clicar fora
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSelect = (langCode) => {
    changeLanguage(langCode);
    setIsOpen(false);
  };

  // Variante dropdown (padrão)
  if (variant === 'dropdown') {
    return (
      <div className={`dropdown ${className}`} ref={dropdownRef}>
        <button
          className="btn btn-outline-secondary dropdown-toggle d-flex align-items-center gap-2"
          type="button"
          onClick={() => setIsOpen(!isOpen)}
          aria-expanded={isOpen}
        >
          <span style={{ fontSize: '1.2em' }}>{currentLang.flag}</span>
          <span className="d-none d-md-inline">{currentLang.name}</span>
        </button>
        
        <ul className={`dropdown-menu dropdown-menu-end ${isOpen ? 'show' : ''}`}>
          {availableLanguages.map((lang) => (
            <li key={lang.code}>
              <button
                className={`dropdown-item d-flex align-items-center gap-2 ${
                  lang.code === i18n.language ? 'active' : ''
                }`}
                onClick={() => handleSelect(lang.code)}
              >
                <span style={{ fontSize: '1.2em' }}>{lang.flag}</span>
                <span>{lang.name}</span>
              </button>
            </li>
          ))}
        </ul>
      </div>
    );
  }

  // Variante botões (para mobile ou settings)
  if (variant === 'buttons') {
    return (
      <div className={`btn-group ${className}`} role="group">
        {availableLanguages.map((lang) => (
          <button
            key={lang.code}
            type="button"
            className={`btn ${
              lang.code === i18n.language 
                ? 'btn-primary' 
                : 'btn-outline-secondary'
            }`}
            onClick={() => handleSelect(lang.code)}
            title={lang.name}
          >
            <span style={{ fontSize: '1.2em' }}>{lang.flag}</span>
            <span className="d-none d-sm-inline ms-1">{lang.code.toUpperCase()}</span>
          </button>
        ))}
      </div>
    );
  }

  // Variante select (para formulários)
  if (variant === 'select') {
    return (
      <select
        className={`form-select ${className}`}
        value={i18n.language}
        onChange={(e) => handleSelect(e.target.value)}
      >
        {availableLanguages.map((lang) => (
          <option key={lang.code} value={lang.code}>
            {lang.flag} {lang.name}
          </option>
        ))}
      </select>
    );
  }

  return null;
};

export default LanguageSelector;
