import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { businessSettingService } from '../../services/api';
import useFormatters from '../../hooks/useFormatters';
import BusinessSettingModal from './BusinessSettingModal';
import ConfirmModal from '../ConfirmModal';

const BusinessSettingsTab = ({ settings, onCreated, onUpdated, onDeleted }) => {
  const { t } = useTranslation();
  const { currency, percent } = useFormatters();
  
  const [showModal, setShowModal] = useState(false);
  const [editingSetting, setEditingSetting] = useState(null);
  const [deleting, setDeleting] = useState(null);
  const [confirmModal, setConfirmModal] = useState({ show: false, setting: null });

  const handleCreate = () => {
    setEditingSetting(null);
    setShowModal(true);
  };

  const handleEdit = (setting) => {
    setEditingSetting(setting);
    setShowModal(true);
  };

  const handleDelete = async (setting) => {
    setConfirmModal({ show: true, setting });
  };

  const executeDelete = async () => {
    const setting = confirmModal.setting;
    setConfirmModal({ show: false, setting: null });
    
    setDeleting(setting.id);
    try {
      await businessSettingService.delete(setting.id);
      onDeleted(setting.id);
    } catch (err) {
      alert(err.response?.data?.message || t('common.error'));
    } finally {
      setDeleting(null);
    }
  };

  const handleSave = (savedSetting) => {
    if (editingSetting) {
      onUpdated(savedSetting);
    } else {
      onCreated(savedSetting);
    }
    setShowModal(false);
  };

  return (
    <>
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h5 className="text-white mb-1">{t('business.settings.title')}</h5>
          <p className="text-slate-400 small mb-0">{t('business.settings.description')}</p>
        </div>
        <button className="btn btn-primary" onClick={handleCreate}>
          <i className="bi bi-plus-lg me-2"></i>
          {t('business.settings.add')}
        </button>
      </div>

      {/* Empty State */}
      {settings.length === 0 ? (
        <div className="card border-0" style={{ background: '#1e293b' }}>
          <div className="card-body text-center py-5">
            <i className="bi bi-gear fs-1 text-slate-500 mb-3 d-block"></i>
            <h5 className="text-white mb-2">{t('business.settings.empty')}</h5>
            <p className="text-slate-400 mb-4">{t('business.settings.emptyDescription')}</p>
            <button className="btn btn-primary" onClick={handleCreate}>
              <i className="bi bi-plus-lg me-2"></i>
              {t('business.settings.createFirst')}
            </button>
          </div>
        </div>
      ) : (
        /* Settings Cards */
        <div className="row g-4">
          {settings.map(setting => (
            <div key={setting.id} className="col-12 col-lg-6">
              <div 
                className="card border-0 h-100" 
                style={{ 
                  background: setting.is_active ? '#1e293b' : '#0f172a',
                  opacity: setting.is_active ? 1 : 0.7,
                }}
              >
                <div className="card-header border-0 d-flex justify-content-between align-items-center py-3" style={{ background: 'transparent' }}>
                  <div>
                    <h6 className="text-white mb-0">
                      {setting.name}
                      {!setting.is_active && (
                        <span className="badge bg-secondary ms-2">{t('common.inactive')}</span>
                      )}
                    </h6>
                    <small className="text-slate-500">{setting.currency}</small>
                  </div>
                  <div className="dropdown">
                    <button className="btn btn-sm btn-outline-secondary border-0" data-bs-toggle="dropdown">
                      <i className="bi bi-three-dots-vertical"></i>
                    </button>
                    <ul className="dropdown-menu dropdown-menu-end" style={{ background: '#1e293b' }}>
                      <li>
                        <button className="dropdown-item text-white" onClick={() => handleEdit(setting)}>
                          <i className="bi bi-pencil me-2"></i>
                          {t('common.edit')}
                        </button>
                      </li>
                      <li><hr className="dropdown-divider" style={{ borderColor: 'rgba(255,255,255,0.1)' }} /></li>
                      <li>
                        <button 
                          className="dropdown-item text-danger" 
                          onClick={() => handleDelete(setting)}
                          disabled={deleting === setting.id}
                        >
                          <i className="bi bi-trash me-2"></i>
                          {t('common.delete')}
                        </button>
                      </li>
                    </ul>
                  </div>
                </div>
                
                <div className="card-body py-3">
                  {/* Markup Factor - Destaque */}
                  <div className="text-center mb-4 p-3 rounded" style={{ background: 'rgba(59, 130, 246, 0.1)' }}>
                    <small className="text-slate-400 d-block mb-1">{t('business.settings.markupFactor')}</small>
                    <h2 className="text-primary mb-0">{parseFloat(setting.markup_factor || 0).toFixed(2)}</h2>
                  </div>
                  
                  {/* Breakdown */}
                  <div className="row g-3 small">
                    <div className="col-6">
                      <div className="p-2 rounded" style={{ background: 'rgba(255,255,255,0.05)' }}>
                        <small className="text-slate-500 d-block">{t('business.settings.monthlyRevenue')}</small>
                        <span className="text-white">{currency(setting.monthly_revenue, setting.currency)}</span>
                      </div>
                    </div>
                    <div className="col-6">
                      <div className="p-2 rounded" style={{ background: 'rgba(255,255,255,0.05)' }}>
                        <small className="text-slate-500 d-block">{t('business.settings.fixedExpenses')}</small>
                        <span className="text-white">{currency(setting.fixed_expenses, setting.currency)}</span>
                      </div>
                    </div>
                    <div className="col-6">
                      <div className="p-2 rounded" style={{ background: 'rgba(255,255,255,0.05)' }}>
                        <small className="text-slate-500 d-block">{t('business.settings.fixedExpensesRate')}</small>
                        <span className="text-warning">{parseFloat(setting.fixed_expenses_rate || 0).toFixed(2)}%</span>
                      </div>
                    </div>
                    <div className="col-6">
                      <div className="p-2 rounded" style={{ background: 'rgba(255,255,255,0.05)' }}>
                        <small className="text-slate-500 d-block">{t('business.settings.totalVariableCosts')}</small>
                        <span className="text-warning">{parseFloat(setting.total_variable_costs || 0).toFixed(2)}%</span>
                      </div>
                    </div>
                  </div>
                  
                  {/* Variable Costs Detail */}
                  <div className="mt-3 pt-3" style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }}>
                    <small className="text-slate-500 d-block mb-2">{t('business.settings.variableCostsBreakdown')}</small>
                    <div className="d-flex flex-wrap gap-2">
                      <span className="badge bg-secondary">
                        {t('business.settings.taxRate')}: {setting.tax_rate}%
                      </span>
                      <span className="badge bg-secondary">
                        {t('business.settings.salesCommission')}: {setting.sales_commission}%
                      </span>
                      <span className="badge bg-secondary">
                        {t('business.settings.cardFee')}: {setting.card_fee}%
                      </span>
                      {setting.other_variable_costs > 0 && (
                        <span className="badge bg-secondary">
                          {t('business.settings.otherVariableCosts')}: {setting.other_variable_costs}%
                        </span>
                      )}
                    </div>
                  </div>
                  
                  {/* Investment & Profit */}
                  <div className="mt-3 pt-3" style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }}>
                    <div className="d-flex justify-content-between">
                      <div>
                        <small className="text-slate-500 d-block">{t('business.settings.investmentRate')}</small>
                        <span className="text-info">{setting.investment_rate}%</span>
                      </div>
                      <div className="text-end">
                        <small className="text-slate-500 d-block">{t('business.settings.profitMargin')}</small>
                        <span className="text-success">{setting.profit_margin}%</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal */}
      {showModal && (
        <BusinessSettingModal
          setting={editingSetting}
          onSave={handleSave}
          onClose={() => setShowModal(false)}
        />
      )}

      {/* Confirm Modal */}
      <ConfirmModal
        show={confirmModal.show}
        message={t('business.settings.confirmDelete')}
        variant="danger"
        onConfirm={executeDelete}
        onCancel={() => setConfirmModal({ show: false, setting: null })}
      />
    </>
  );
};

export default BusinessSettingsTab;
