import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { costCenterService } from '../services/api';
import { useToast } from '../components/Toast';
import { ConfirmModal } from '../components/Modal';
import IconSelector from '../components/IconSelector';

const CostCenters = () => {
  const { t } = useTranslation();
  const toast = useToast();
  const [costCenters, setCostCenters] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);
  const [saving, setSaving] = useState(false);
  const [newKeyword, setNewKeyword] = useState('');
  const [openDropdownId, setOpenDropdownId] = useState(null);
  const dropdownRef = useRef(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setOpenDropdownId(null);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const [formData, setFormData] = useState({
    name: '',
    code: '',
    description: '',
    color: '#10B981',
    icon: 'bi-building',
    is_active: true,
    keywords: [],
  });

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

  const loadCostCenters = async () => {
    try {
      setLoading(true);
      const response = await costCenterService.getAll();
      if (response.success) {
        setCostCenters(response.data);
      }
    } catch (error) {
      toast.error(t('costCenters.loadError'));
    } finally {
      setLoading(false);
    }
  };

  const handleOpenModal = (item = null) => {
    if (item) {
      setSelectedItem(item);
      setFormData({
        name: item.name || '',
        code: item.code || '',
        description: item.description || '',
        color: item.color || '#10B981',
        icon: item.icon || 'bi-building',
        is_active: item.is_active ?? true,
        keywords: item.keywords?.map(k => k.keyword) || [],
      });
    } else {
      setSelectedItem(null);
      setFormData({
        name: '',
        code: '',
        description: '',
        color: '#10B981',
        icon: 'bi-building',
        is_active: true,
        keywords: [],
      });
    }
    setNewKeyword('');
    setShowModal(true);
  };

  const handleCloseModal = () => {
    setShowModal(false);
    setSelectedItem(null);
    setNewKeyword('');
  };

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }));
  };

  const handleAddKeyword = () => {
    const keyword = newKeyword.trim();
    if (keyword && !formData.keywords.includes(keyword)) {
      setFormData(prev => ({
        ...prev,
        keywords: [...prev.keywords, keyword],
      }));
      setNewKeyword('');
    }
  };

  const handleRemoveKeyword = (keyword) => {
    setFormData(prev => ({
      ...prev,
      keywords: prev.keywords.filter(k => k !== keyword),
    }));
  };

  const handleKeywordKeyPress = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAddKeyword();
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!formData.name.trim()) {
      toast.error(t('validation.required'));
      return;
    }

    setSaving(true);
    try {
      let response;
      if (selectedItem) {
        response = await costCenterService.update(selectedItem.id, formData);
      } else {
        response = await costCenterService.create(formData);
      }

      if (response.success) {
        toast.success(selectedItem ? t('costCenters.updateSuccess') : t('costCenters.createSuccess'));
        handleCloseModal();
        loadCostCenters();
      }
    } catch (error) {
      toast.error(error.response?.data?.message || t('costCenters.createError'));
    } finally {
      setSaving(false);
    }
  };

  const handleDeleteClick = (item) => {
    setSelectedItem(item);
    setShowDeleteModal(true);
  };

  const handleDeleteConfirm = async () => {
    if (!selectedItem) return;

    setSaving(true);
    try {
      const response = await costCenterService.delete(selectedItem.id);
      if (response.success) {
        toast.success(t('costCenters.deleteSuccess'));
        setShowDeleteModal(false);
        setSelectedItem(null);
        loadCostCenters();
      }
    } catch (error) {
      toast.error(error.response?.data?.message || t('costCenters.deleteError'));
    } finally {
      setSaving(false);
    }
  };

  return (
    <div>
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h2 className="text-white mb-1">
            <i className="bi bi-building me-2 text-success"></i>
            {t('nav.costCenters')}
          </h2>
          <p className="text-slate-400 mb-0">
            {t('costCenters.title')}
          </p>
        </div>
        <button className="btn btn-success" onClick={() => handleOpenModal()}>
          <i className="bi bi-plus-lg me-2"></i>
          {t('costCenters.newCostCenter')}
        </button>
      </div>

      {/* Info Card */}
      <div className="card border-0 mb-4" style={{ background: '#1e293b' }}>
        <div className="card-body">
          <div className="d-flex align-items-start">
            <div className="rounded-circle bg-info bg-opacity-25 p-2 me-3">
              <i className="bi bi-info-circle text-info"></i>
            </div>
            <div>
              <h6 className="text-white mb-1">{t('costCenters.keywordHelp')}</h6>
              <p className="text-slate-400 mb-0 small">
                {t('common.info')}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Cost Centers Grid */}
      {loading ? (
        <div className="text-center py-5">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">{t('common.loading')}</span>
          </div>
        </div>
      ) : costCenters.length === 0 ? (
        <div className="card border-0" style={{ background: '#1e293b' }}>
          <div className="card-body text-center py-5">
            <i className="bi bi-building display-1 text-slate-600"></i>
            <p className="text-slate-400 mt-3">{t('costCenters.noCostCenters')}</p>
            <button className="btn btn-success" onClick={() => handleOpenModal()}>
              <i className="bi bi-plus-lg me-2"></i>
              {t('costCenters.newCostCenter')}
            </button>
          </div>
        </div>
      ) : (
        <div className="row g-4">
          {costCenters.map((item) => (
            <div key={item.id} className="col-md-6 col-lg-4">
              <div 
                className="card border-0 h-100" 
                style={{ 
                  background: '#1e293b',
                  borderLeft: `4px solid ${item.color}`,
                }}
              >
                <div className="card-body">
                  <div className="d-flex justify-content-between align-items-start mb-3">
                    <div className="d-flex align-items-center">
                      <div 
                        className="rounded-circle d-flex align-items-center justify-content-center me-3"
                        style={{ 
                          width: '45px', 
                          height: '45px', 
                          backgroundColor: item.color + '25',
                        }}
                      >
                        <i className={`bi ${item.icon} fs-5`} style={{ color: item.color }}></i>
                      </div>
                      <div>
                        <h5 className="text-white mb-0">
                          {item.name}
                          {item.is_system && (
                            <i className="bi bi-lock-fill ms-2 text-warning" title={t('costCenters.systemCostCenter')}></i>
                          )}
                        </h5>
                        {item.code && (
                          <small className="text-slate-400">{t('costCenters.code')}: {item.code}</small>
                        )}
                      </div>
                    </div>
                    {!item.is_system && (
                    <div className="dropdown" ref={openDropdownId === item.id ? dropdownRef : null} style={{ position: 'relative' }}>
                      <button 
                        className="btn btn-link text-slate-400 p-0" 
                        type="button"
                        onClick={() => setOpenDropdownId(openDropdownId === item.id ? null : item.id)}
                      >
                        <i className="bi bi-three-dots-vertical"></i>
                      </button>
                      <ul 
                        className={`dropdown-menu dropdown-menu-end ${openDropdownId === item.id ? 'show' : ''}`} 
                        style={{ 
                          background: '#334155',
                          position: 'absolute',
                          right: 0,
                          top: '100%',
                          zIndex: 1000
                        }}
                      >
                        <li>
                          <button 
                            className="dropdown-item text-white" 
                            onClick={() => { handleOpenModal(item); setOpenDropdownId(null); }}
                          >
                            <i className="bi bi-pencil me-2"></i>{t('common.edit')}
                          </button>
                        </li>
                        <li>
                          <button 
                            className="dropdown-item text-danger"
                            onClick={() => { handleDeleteClick(item); setOpenDropdownId(null); }}
                          >
                            <i className="bi bi-trash me-2"></i>{t('common.delete')}
                          </button>
                        </li>
                      </ul>
                    </div>
                    )}
                  </div>

                  {item.description && (
                    <p className="text-slate-400 small mb-3">{item.description}</p>
                  )}

                  {/* Keywords */}
                  <div className="mb-3">
                    <small className="text-slate-500 d-block mb-2">
                      <i className="bi bi-key me-1"></i>
                      {t('costCenters.keywords')} ({item.keywords?.length || 0})
                    </small>
                    <div className="d-flex flex-wrap gap-1">
                      {item.keywords?.slice(0, 5).map((kw) => (
                        <span 
                          key={kw.id} 
                          className="badge rounded-pill"
                          style={{ 
                            backgroundColor: item.color + '25',
                            color: item.color,
                            fontSize: '11px',
                          }}
                        >
                          {kw.keyword}
                        </span>
                      ))}
                      {item.keywords?.length > 5 && (
                        <span className="badge bg-secondary rounded-pill" style={{ fontSize: '11px' }}>
                          +{item.keywords.length - 5}
                        </span>
                      )}
                      {(!item.keywords || item.keywords.length === 0) && (
                        <span className="text-slate-500 small">{t('common.noData')}</span>
                      )}
                    </div>
                  </div>

                  {/* Status */}
                  <div className="d-flex justify-content-between align-items-center">
                    {item.is_active ? (
                      <span className="badge bg-success bg-opacity-25 text-success">{t('common.active')}</span>
                    ) : (
                      <span className="badge bg-secondary bg-opacity-25 text-secondary">{t('common.inactive')}</span>
                    )}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal de Criar/Editar */}
      {showModal && (
        <div className="modal show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.7)' }}>
          <div className="modal-dialog modal-lg modal-dialog-centered">
            <div className="modal-content" style={{ background: '#1e293b' }}>
              <div className="modal-header border-bottom" style={{ borderColor: '#334155 !important' }}>
                <h5 className="modal-title text-white">
                  <i className={`bi ${selectedItem ? 'bi-pencil' : 'bi-plus-circle'} me-2`}></i>
                  {selectedItem ? t('costCenters.editCostCenter') : t('costCenters.newCostCenter')}
                </h5>
                <button type="button" className="btn-close btn-close-white" onClick={handleCloseModal}></button>
              </div>
              <form onSubmit={handleSubmit}>
                <div className="modal-body">
                  <div className="row g-3">
                    {/* Nome */}
                    <div className="col-md-8">
                      <label className="form-label text-slate-300">{t('common.name')} *</label>
                      <input
                        type="text"
                        className="form-control bg-dark text-white border-secondary"
                        name="name"
                        value={formData.name}
                        onChange={handleChange}
                        placeholder="Ex: Projeto Alpha, Departamento RH..."
                        required
                      />
                    </div>

                    {/* Código */}
                    <div className="col-md-4">
                      <label className="form-label text-slate-300">{t('costCenters.code')}</label>
                      <input
                        type="text"
                        className="form-control bg-dark text-white border-secondary"
                        name="code"
                        value={formData.code}
                        onChange={handleChange}
                        placeholder="Ex: CC001"
                        maxLength="20"
                      />
                    </div>

                    {/* Cor */}
                    <div className="col-md-3">
                      <label className="form-label text-slate-300">{t('common.color')}</label>
                      <input
                        type="color"
                        className="form-control form-control-color bg-dark border-secondary w-100"
                        name="color"
                        value={formData.color}
                        onChange={handleChange}
                      />
                    </div>

                    {/* Ícone */}
                    <div className="col-md-5">
                      <label className="form-label text-slate-300">{t('common.icon')}</label>
                      <IconSelector
                        value={formData.icon}
                        onChange={(icon) => setFormData(prev => ({ ...prev, icon }))}
                        type="costCenter"
                      />
                    </div>

                    {/* Status */}
                    <div className="col-md-4">
                      <label className="form-label text-slate-300">&nbsp;</label>
                      <div className="form-check mt-2">
                        <input
                          type="checkbox"
                          className="form-check-input"
                          id="is_active"
                          name="is_active"
                          checked={formData.is_active}
                          onChange={handleChange}
                        />
                        <label className="form-check-label text-slate-300" htmlFor="is_active">
                          {t('common.active')}
                        </label>
                      </div>
                    </div>

                    {/* Descrição */}
                    <div className="col-12">
                      <label className="form-label text-slate-300">{t('common.description')}</label>
                      <textarea
                        className="form-control bg-dark text-white border-secondary"
                        name="description"
                        value={formData.description}
                        onChange={handleChange}
                        rows="2"
                        placeholder="Descreva o propósito deste centro de custo..."
                      ></textarea>
                    </div>

                    {/* Palavras-chave */}
                    <div className="col-12">
                      <label className="form-label text-slate-300">
                        <i className="bi bi-key me-1"></i>
                        {t('costCenters.keywordHelp')}
                      </label>
                      <div className="input-group mb-2">
                        <input
                          type="text"
                          className="form-control bg-dark text-white border-secondary"
                          value={newKeyword}
                          onChange={(e) => setNewKeyword(e.target.value)}
                          onKeyPress={handleKeywordKeyPress}
                          placeholder="Digite uma palavra-chave e pressione Enter..."
                        />
                        <button 
                          type="button" 
                          className="btn btn-outline-success"
                          onClick={handleAddKeyword}
                        >
                          <i className="bi bi-plus"></i>
                        </button>
                      </div>
                      <div className="d-flex flex-wrap gap-2">
                        {formData.keywords.map((keyword, index) => (
                          <span 
                            key={index}
                            className="badge d-flex align-items-center"
                            style={{ 
                              backgroundColor: formData.color + '25',
                              color: formData.color,
                            }}
                          >
                            {keyword}
                            <button
                              type="button"
                              className="btn-close btn-close-white ms-2"
                              style={{ fontSize: '8px' }}
                              onClick={() => handleRemoveKeyword(keyword)}
                            ></button>
                          </span>
                        ))}
                        {formData.keywords.length === 0 && (
                          <small className="text-slate-500">
                            {t('common.noData')}
                          </small>
                        )}
                      </div>
                      <small className="text-slate-500 mt-2 d-block">
                        Ex: "UBER", "iFood", "Supermercado XYZ" - Quando estas palavras aparecerem na 
                        descrição de uma transação, este centro de custo será sugerido automaticamente.
                      </small>
                    </div>
                  </div>
                </div>
                <div className="modal-footer border-top" style={{ borderColor: '#334155 !important' }}>
                  <button type="button" className="btn btn-outline-light" onClick={handleCloseModal}>
                    {t('common.cancel')}
                  </button>
                  <button type="submit" className="btn btn-success" disabled={saving}>
                    {saving ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2"></span>
                        {t('common.loading')}
                      </>
                    ) : (
                      <>
                        <i className="bi bi-check-lg me-2"></i>
                        {selectedItem ? t('common.save') : t('common.create')}
                      </>
                    )}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* Modal de Confirmação de Exclusão */}
      <ConfirmModal
        show={showDeleteModal}
        onHide={() => setShowDeleteModal(false)}
        onConfirm={handleDeleteConfirm}
        title={t('costCenters.deleteCostCenter')}
        message={t('costCenters.deleteConfirm')}
        confirmText={t('common.delete')}
        loading={saving}
      />
    </div>
  );
};

export default CostCenters;
