import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { categoryIcons, accountIcons, costCenterIcons } from '../config/icons';

/**
 * Seletor de ícones com modal visual
 * Props:
 * - value: ícone selecionado (string)
 * - onChange: callback quando seleciona um ícone
 * - type: 'category' | 'account' | 'costCenter' (determina quais ícones mostrar)
 */
const IconSelector = ({ 
  value = 'bi-tag', 
  onChange, 
  type = 'category',
  className = '' 
}) => {
  const { t } = useTranslation();
  const [isOpen, setIsOpen] = useState(false);
  const [search, setSearch] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');

  // Seleciona lista de ícones baseado no tipo
  const iconList = useMemo(() => {
    switch (type) {
      case 'account':
        return accountIcons;
      case 'costCenter':
        return costCenterIcons;
      default:
        return categoryIcons;
    }
  }, [type]);

  // Filtra ícones por busca e categoria
  const filteredIcons = useMemo(() => {
    let icons = iconList;
    
    // Filtra por categoria
    if (selectedCategory !== 'all') {
      icons = icons.filter(icon => icon.category === selectedCategory);
    }
    
    // Filtra por busca
    if (search) {
      const searchLower = search.toLowerCase();
      icons = icons.filter(icon => 
        icon.value.toLowerCase().includes(searchLower) ||
        icon.label.toLowerCase().includes(searchLower)
      );
    }
    
    return icons;
  }, [iconList, selectedCategory, search]);

  const handleSelect = (iconValue) => {
    if (onChange) {
      onChange(iconValue);
    }
    setIsOpen(false);
    setSearch('');
    setSelectedCategory('all');
  };

  const handleClose = () => {
    setIsOpen(false);
    setSearch('');
    setSelectedCategory('all');
  };

  // Categorias únicas disponíveis nos ícones
  const availableCategories = useMemo(() => {
    const cats = new Set(iconList.map(icon => icon.category));
    return ['all', ...Array.from(cats)];
  }, [iconList]);

  return (
    <>
      {/* Botão para abrir o modal */}
      <button
        type="button"
        className={`btn w-100 d-flex align-items-center justify-content-between ${className}`}
        onClick={() => setIsOpen(true)}
        style={{ 
          background: '#0f172a',
          border: '1px solid #334155',
          color: '#f1f5f9',
          padding: '0.5rem 0.75rem',
        }}
      >
        <span className="d-flex align-items-center gap-2">
          <i className={`bi ${value} fs-4`}></i>
          <span className="text-slate-400 small">
            {t('common.selectIcon') || 'Selecionar ícone'}
          </span>
        </span>
        <i className="bi bi-chevron-right text-slate-400"></i>
      </button>

      {/* Modal de seleção de ícones */}
      {isOpen && (
        <div 
          className="modal show d-block" 
          style={{ backgroundColor: 'rgba(0,0,0,0.8)' }}
          onClick={(e) => e.target === e.currentTarget && handleClose()}
        >
          <div className="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
            <div className="modal-content" style={{ background: '#1e293b', maxHeight: '80vh' }}>
              {/* Header */}
              <div className="modal-header border-bottom" style={{ borderColor: '#334155 !important' }}>
                <h5 className="modal-title text-white d-flex align-items-center gap-2">
                  <i className="bi bi-grid-3x3-gap text-primary"></i>
                  {t('common.selectIcon') || 'Selecionar Ícone'}
                </h5>
                <button 
                  type="button" 
                  className="btn-close btn-close-white" 
                  onClick={handleClose}
                ></button>
              </div>

              {/* Barra de busca e filtros */}
              <div className="p-3 border-bottom" style={{ borderColor: '#334155' }}>
                {/* Busca */}
                <div className="mb-3">
                  <div className="input-group">
                    <span className="input-group-text" style={{ background: '#0f172a', border: '1px solid #334155', color: '#94a3b8' }}>
                      <i className="bi bi-search"></i>
                    </span>
                    <input
                      type="text"
                      className="form-control"
                      placeholder={t('common.searchIcon') || 'Buscar ícone...'}
                      value={search}
                      onChange={(e) => setSearch(e.target.value)}
                      autoFocus
                      style={{
                        background: '#0f172a',
                        border: '1px solid #334155',
                        borderLeft: 'none',
                        color: '#f1f5f9',
                      }}
                    />
                  </div>
                </div>

                {/* Filtro por categoria */}
                <div className="d-flex flex-wrap gap-2">
                  {availableCategories.map(cat => (
                    <button
                      key={cat}
                      type="button"
                      className={`btn btn-sm ${selectedCategory === cat ? 'btn-primary' : ''}`}
                      onClick={() => setSelectedCategory(cat)}
                      style={selectedCategory !== cat ? { 
                        background: '#334155', 
                        border: 'none', 
                        color: '#94a3b8' 
                      } : {}}
                    >
                      {cat === 'all' ? (t('common.all') || 'Todos') : cat}
                    </button>
                  ))}
                </div>
              </div>

              {/* Grid de ícones */}
              <div className="modal-body p-3" style={{ overflowY: 'auto' }}>
                {filteredIcons.length > 0 ? (
                  <div className="row g-2">
                    {filteredIcons.map((icon) => (
                      <div key={icon.value} className="col-2 col-md-1">
                        <button
                          type="button"
                          className={`btn w-100 d-flex align-items-center justify-content-center p-2 ${
                            value === icon.value ? 'btn-primary' : ''
                          }`}
                          style={value !== icon.value ? { 
                            background: '#0f172a', 
                            border: '1px solid #334155',
                            color: '#94a3b8',
                          } : {
                            boxShadow: '0 0 0 2px #3b82f6',
                          }}
                          onClick={() => handleSelect(icon.value)}
                          title={icon.value.replace('bi-', '')}
                        >
                          <i className={`bi ${icon.value} fs-4`}></i>
                        </button>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-5">
                    <i className="bi bi-search display-4 text-slate-600"></i>
                    <p className="text-slate-400 mt-3 mb-0">
                      {t('common.noIconsFound') || 'Nenhum ícone encontrado'}
                    </p>
                  </div>
                )}
              </div>

              {/* Footer com contagem */}
              <div className="modal-footer border-top d-flex justify-content-between" style={{ borderColor: '#334155 !important' }}>
                <span className="text-slate-400 small">
                  {filteredIcons.length} {t('common.icons') || 'ícones'}
                </span>
                <button type="button" className="btn btn-secondary" onClick={handleClose}>
                  {t('common.cancel') || 'Cancelar'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default IconSelector;
