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

const PriceCalculatorTab = ({ settings, sheets }) => {
  const { t } = useTranslation();
  const { currency } = useFormatters();
  
  const [selectedSetting, setSelectedSetting] = useState(null);
  const [cmvInput, setCmvInput] = useState('');
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  // Selecionar primeira configuração ativa por padrão
  useEffect(() => {
    const activeSetting = settings.find(s => s.is_active);
    if (activeSetting) {
      setSelectedSetting(activeSetting);
    }
  }, [settings]);

  const handleCalculate = async () => {
    if (!selectedSetting || !cmvInput) return;
    
    setLoading(true);
    try {
      const result = await businessSettingService.simulatePrice(selectedSetting.id, parseFloat(cmvInput));
      setResult(result);
    } catch (err) {
      alert(err.response?.data?.message || t('common.error'));
    } finally {
      setLoading(false);
    }
  };

  const handleSettingChange = (e) => {
    const setting = settings.find(s => s.id === parseInt(e.target.value));
    setSelectedSetting(setting);
    setResult(null);
  };

  // Cálculo local em tempo real
  const localCalculation = () => {
    if (!selectedSetting || !cmvInput) return null;
    
    const cmv = parseFloat(cmvInput) || 0;
    const markup = selectedSetting.markup_factor || 0;
    const salePrice = cmv * markup;
    const contributionMargin = salePrice - cmv;
    const contributionMarginPercent = salePrice > 0 ? (contributionMargin / salePrice) * 100 : 0;
    
    return {
      cmv,
      markup,
      salePrice,
      contributionMargin,
      contributionMarginPercent,
    };
  };

  const localResult = localCalculation();

  return (
    <>
      {/* Header */}
      <div className="mb-4">
        <h5 className="text-white mb-1">{t('business.calculator.title')}</h5>
        <p className="text-slate-400 small mb-0">{t('business.calculator.description')}</p>
      </div>

      {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.calculator.noSettings')}</h5>
            <p className="text-slate-400">{t('business.calculator.createSettingFirst')}</p>
          </div>
        </div>
      ) : (
        <div className="row g-4">
          {/* Calculadora */}
          <div className="col-lg-6">
            <div className="card border-0 h-100" style={{ background: '#1e293b' }}>
              <div className="card-header border-0" style={{ background: 'transparent' }}>
                <h6 className="text-white mb-0">
                  <i className="bi bi-calculator me-2"></i>
                  {t('business.calculator.simulate')}
                </h6>
              </div>
              <div className="card-body">
                {/* Seleção de Configuração */}
                <div className="mb-4">
                  <label className="form-label text-slate-400">{t('business.calculator.selectSetting')}</label>
                  <select
                    className="form-select bg-dark text-white border-secondary"
                    value={selectedSetting?.id || ''}
                    onChange={handleSettingChange}
                  >
                    {settings.map(s => (
                      <option key={s.id} value={s.id}>
                      {s.name} ({s.currency}) - {t('business.common.markupLabel')}: {parseFloat(s.markup_factor || 0).toFixed(2)}
                      </option>
                    ))}
                  </select>
                </div>

                {/* Input CMV */}
                <div className="mb-4">
                  <label className="form-label text-slate-400">{t('business.calculator.enterCmv')}</label>
                  <div className="input-group">
                    <span className="input-group-text bg-dark text-slate-400 border-secondary">
                      {selectedSetting?.currency || 'EUR'}
                    </span>
                    <input
                      type="number"
                      step="0.01"
                      className="form-control bg-dark text-white border-secondary"
                      value={cmvInput}
                      onChange={(e) => {
                        setCmvInput(e.target.value);
                        setResult(null);
                      }}
                      placeholder="0.00"
                    />
                  </div>
                  <small className="text-slate-500">{t('business.calculator.cmvHelp')}</small>
                </div>

                {/* Resultado em Tempo Real */}
                {localResult && localResult.cmv > 0 && (
                  <div className="p-3 rounded mb-4" style={{ background: 'rgba(59, 130, 246, 0.1)' }}>
                    <div className="row g-3 text-center">
                      <div className="col-6">
                        <small className="text-slate-500 d-block">CMV</small>
                        <span className="text-danger fw-bold">
                          {currency(localResult.cmv, selectedSetting?.currency)}
                        </span>
                      </div>
                      <div className="col-6">
                        <small className="text-slate-500 d-block">{t('business.common.timesMarkup')}</small>
                        <span className="text-primary fw-bold">{localResult.markup.toFixed(2)}</span>
                      </div>
                      <div className="col-12">
                        <hr className="border-secondary my-2" />
                      </div>
                      <div className="col-12">
                        <small className="text-slate-500 d-block">{t('business.calculator.salePrice')}</small>
                        <h3 className="text-success mb-0">
                          {currency(localResult.salePrice, selectedSetting?.currency)}
                        </h3>
                      </div>
                      <div className="col-6">
                        <small className="text-slate-500 d-block">{t('business.calculator.contributionMargin')}</small>
                        <span className="text-info">
                          {currency(localResult.contributionMargin, selectedSetting?.currency)}
                        </span>
                      </div>
                      <div className="col-6">
                        <small className="text-slate-500 d-block">{t('business.calculator.marginPercent')}</small>
                        <span className="text-info">
                          {localResult.contributionMarginPercent.toFixed(2)}%
                        </span>
                      </div>
                    </div>
                  </div>
                )}

                {/* Fórmula */}
                <div className="p-3 rounded" style={{ background: 'rgba(255,255,255,0.05)' }}>
                  <small className="text-slate-500 d-block mb-2">{t('business.calculator.formula')}</small>
                  <code className="text-info">
                    {t('business.calculator.salePrice')} = {t('business.common.cmvLabel')} × {t('business.common.markupLabel')}
                  </code>
                  <br />
                  <code className="text-slate-400 small">
                    Markup = 1 / (1 - ({t('business.settings.fixedExpensesRate')} + {t('business.settings.variableCosts')} + {t('business.settings.investmentRate')} + {t('business.settings.profitMargin')}))
                  </code>
                </div>
              </div>
            </div>
          </div>

          {/* Breakdown da Configuração Selecionada */}
          <div className="col-lg-6">
            {selectedSetting && (
              <div className="card border-0 h-100" style={{ background: '#1e293b' }}>
                <div className="card-header border-0" style={{ background: 'transparent' }}>
                  <h6 className="text-white mb-0">
                    <i className="bi bi-pie-chart me-2"></i>
                    {t('business.calculator.breakdown')}
                  </h6>
                </div>
                <div className="card-body">
                  {/* Markup Factor */}
                  <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(selectedSetting.markup_factor || 0).toFixed(4)}</h2>
                  </div>

                  {/* Detalhes */}
                  <div className="mb-3">
                    <div className="d-flex justify-content-between py-2" style={{ borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
                      <span className="text-slate-400">{t('business.settings.monthlyRevenue')}</span>
                      <span className="text-white">{currency(selectedSetting.monthly_revenue, selectedSetting.currency)}</span>
                    </div>
                    <div className="d-flex justify-content-between py-2" style={{ borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
                      <span className="text-slate-400">{t('business.settings.fixedExpenses')}</span>
                      <span className="text-white">{currency(selectedSetting.fixed_expenses, selectedSetting.currency)}</span>
                    </div>
                    <div className="d-flex justify-content-between py-2" style={{ borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
                      <span className="text-slate-400">{t('business.settings.fixedExpensesRate')}</span>
                      <span className="text-warning">{parseFloat(selectedSetting.fixed_expenses_rate || 0).toFixed(2)}%</span>
                    </div>
                  </div>

                  <div className="mb-3">
                    <small className="text-slate-500 d-block mb-2">{t('business.settings.variableCosts')}</small>
                    <div className="d-flex justify-content-between py-1">
                      <span className="text-slate-400 small">{t('business.settings.taxRate')}</span>
                      <span className="text-white small">{selectedSetting.tax_rate}%</span>
                    </div>
                    <div className="d-flex justify-content-between py-1">
                      <span className="text-slate-400 small">{t('business.settings.salesCommission')}</span>
                      <span className="text-white small">{selectedSetting.sales_commission}%</span>
                    </div>
                    <div className="d-flex justify-content-between py-1">
                      <span className="text-slate-400 small">{t('business.settings.cardFee')}</span>
                      <span className="text-white small">{selectedSetting.card_fee}%</span>
                    </div>
                    {selectedSetting.other_variable_costs > 0 && (
                      <div className="d-flex justify-content-between py-1">
                        <span className="text-slate-400 small">{t('business.settings.otherVariableCosts')}</span>
                        <span className="text-white small">{selectedSetting.other_variable_costs}%</span>
                      </div>
                    )}
                    <div className="d-flex justify-content-between py-2 mt-1" style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }}>
                      <span className="text-slate-400">{t('business.settings.totalVariableCosts')}</span>
                      <span className="text-warning">{parseFloat(selectedSetting.total_variable_costs || 0).toFixed(2)}%</span>
                    </div>
                  </div>

                  <div className="mb-3">
                    <div className="d-flex justify-content-between py-2" style={{ borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
                      <span className="text-slate-400">{t('business.settings.investmentRate')}</span>
                      <span className="text-info">{selectedSetting.investment_rate}%</span>
                    </div>
                    <div className="d-flex justify-content-between py-2" style={{ borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
                      <span className="text-slate-400">{t('business.settings.profitMargin')}</span>
                      <span className="text-success">{selectedSetting.profit_margin}%</span>
                    </div>
                  </div>

                  {/* Total Deduções */}
                  <div className="p-3 rounded" style={{ background: 'rgba(239, 68, 68, 0.1)' }}>
                    <div className="d-flex justify-content-between">
                      <span className="text-slate-400">{t('business.settings.totalDeductions')}</span>
                      <span className="text-danger fw-bold">
                        {(parseFloat(selectedSetting.fixed_expenses_rate || 0) + parseFloat(selectedSetting.total_variable_costs || 0) + parseFloat(selectedSetting.investment_rate || 0) + parseFloat(selectedSetting.profit_margin || 0)).toFixed(2)}%
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Tabela de Preços Rápidos */}
          {selectedSetting && sheets.length > 0 && (
            <div className="col-12">
              <div className="card border-0" style={{ background: '#1e293b' }}>
                <div className="card-header border-0" style={{ background: 'transparent' }}>
                  <h6 className="text-white mb-0">
                    <i className="bi bi-table me-2"></i>
                    {t('business.calculator.quickPrices')}
                  </h6>
                </div>
                <div className="card-body">
                  <div className="table-responsive">
                    <table className="table table-dark table-hover mb-0">
                      <thead>
                        <tr>
                          <th className="text-slate-400">{t('business.products.name')}</th>
                          <th className="text-slate-400 text-end">CMV</th>
                          <th className="text-slate-400 text-end">{t('business.calculator.salePrice')}</th>
                          <th className="text-slate-400 text-end">{t('business.calculator.contributionMargin')}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {sheets.filter(s => s.is_active && s.currency === selectedSetting.currency).slice(0, 10).map(sheet => {
                          const salePrice = sheet.cmv_total * selectedSetting.markup_factor;
                          const margin = salePrice - sheet.cmv_total;
                          return (
                            <tr key={sheet.id}>
                              <td className="text-white">{sheet.name}</td>
                              <td className="text-end text-danger">{currency(sheet.cmv_total, sheet.currency)}</td>
                              <td className="text-end text-success">{currency(salePrice, sheet.currency)}</td>
                              <td className="text-end text-info">{currency(margin, sheet.currency)}</td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </>
  );
};

export default PriceCalculatorTab;
