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

const BusinessSettingModal = ({ setting, onSave, onClose }) => {
  const { t } = useTranslation();
  const isEditing = !!setting;
  
  const [formData, setFormData] = useState({
    name: '',
    currency: 'EUR',
    business_type: 'products',
    employees_count: '1',
    hours_per_week: '40',
    working_days_per_week: '5',
    working_days_per_month: '22',
    productivity_rate: '80',
    monthly_revenue: '',
    fixed_expenses: '',
    tax_rate: '',
    price_includes_tax: true,
    vat_rate: '21',
    sales_commission: '',
    card_fee: '',
    other_variable_costs: '',
    investment_rate: '',
    profit_margin: '',
    is_active: true,
  });
  
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);
  const [preview, setPreview] = useState(null);

  useEffect(() => {
    if (setting) {
      setFormData({
        name: setting.name || '',
        currency: setting.currency || 'EUR',
        business_type: setting.business_type || 'products',
        employees_count: setting.employees_count?.toString() || '1',
        hours_per_week: setting.hours_per_week?.toString() || '40',
        working_days_per_week: setting.working_days_per_week?.toString() || '5',
        working_days_per_month: setting.working_days_per_month?.toString() || '22',
        productivity_rate: setting.productivity_rate?.toString() || '80',
        monthly_revenue: setting.monthly_revenue?.toString() || '',
        fixed_expenses: setting.fixed_expenses?.toString() || '',
        tax_rate: setting.tax_rate?.toString() || '',
        price_includes_tax: setting.price_includes_tax ?? true,
        vat_rate: setting.vat_rate?.toString() || '21',
        sales_commission: setting.sales_commission?.toString() || '',
        card_fee: setting.card_fee?.toString() || '',
        other_variable_costs: setting.other_variable_costs?.toString() || '',
        investment_rate: setting.investment_rate?.toString() || '',
        profit_margin: setting.profit_margin?.toString() || '',
        is_active: setting.is_active ?? true,
      });
    }
  }, [setting]);

  // Calcular preview do markup em tempo real
  useEffect(() => {
    const monthlyRevenue = parseFloat(formData.monthly_revenue) || 0;
    const fixedExpenses = parseFloat(formData.fixed_expenses) || 0;
    const taxRate = parseFloat(formData.tax_rate) || 0;
    const priceIncludesTax = formData.price_includes_tax;
    const vatRate = parseFloat(formData.vat_rate) || 0;
    const salesCommission = parseFloat(formData.sales_commission) || 0;
    const cardFee = parseFloat(formData.card_fee) || 0;
    const otherVariableCosts = parseFloat(formData.other_variable_costs) || 0;
    const investmentRate = parseFloat(formData.investment_rate) || 0;
    const profitMargin = parseFloat(formData.profit_margin) || 0;
    
    // Calcular horas produtivas (para serviços)
    // Chave: horas por semana - as outras são derivadas
    const employees = parseInt(formData.employees_count) || 1;
    const hoursPerWeek = parseFloat(formData.hours_per_week) || 40;
    const daysPerWeek = parseInt(formData.working_days_per_week) || 5;
    const daysPerMonth = parseInt(formData.working_days_per_month) || 22;
    const productivity = parseFloat(formData.productivity_rate) || 80;
    
    // Derivar horas por dia a partir de horas por semana
    const hoursPerDay = daysPerWeek > 0 ? hoursPerWeek / daysPerWeek : 8;
    
    // Horas produtivas = funcionários × horas/dia × dias/mês × produtividade
    const productiveHours = employees * hoursPerDay * daysPerMonth * (productivity / 100);
    const fixedCostPerHour = productiveHours > 0 ? fixedExpenses / productiveHours : 0;

    // Calcular % despesas fixas (para produtos)
    const fixedExpensesRate = monthlyRevenue > 0 ? (fixedExpenses / monthlyRevenue) * 100 : 0;
    
    // Total custos variáveis - se B2C, tax_rate NÃO entra nas deduções
    const totalVariableCosts = (priceIncludesTax ? 0 : taxRate) + salesCommission + cardFee + otherVariableCosts;
    
    // Total deduções (em decimal)
    const totalDeductions = (fixedExpensesRate + totalVariableCosts + investmentRate + profitMargin) / 100;
    
    // Markup base (sem IVA)
    let markup = 0;
    if (totalDeductions < 1) {
      markup = 1 / (1 - totalDeductions);
    }
    
    // Se B2C, o preço final inclui IVA
    const finalMultiplier = priceIncludesTax ? markup * (1 + vatRate / 100) : markup;

    setPreview({
      fixedExpensesRate: fixedExpensesRate.toFixed(2),
      totalVariableCosts: totalVariableCosts.toFixed(2),
      totalDeductions: (totalDeductions * 100).toFixed(2),
      markup: markup.toFixed(4),
      finalMultiplier: finalMultiplier.toFixed(4),
      vatRate: vatRate.toFixed(2),
      priceIncludesTax,
      isValid: totalDeductions < 1,
      // Para serviços - derivados de horas por semana
      hoursPerWeek: hoursPerWeek.toFixed(1),
      hoursPerDay: hoursPerDay.toFixed(2),
      productiveHours: productiveHours.toFixed(1),
      fixedCostPerHour: fixedCostPerHour.toFixed(2),
    });
  }, [formData]);

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSaving(true);
    setError(null);

    try {
      const dataToSend = {
        ...formData,
        business_type: formData.business_type,
        employees_count: parseInt(formData.employees_count) || 1,
        hours_per_week: parseFloat(formData.hours_per_week) || 40,
        working_days_per_week: parseInt(formData.working_days_per_week) || 5,
        working_days_per_month: parseInt(formData.working_days_per_month) || 22,
        productivity_rate: parseFloat(formData.productivity_rate) || 80,
        monthly_revenue: parseFloat(formData.monthly_revenue) || 0,
        fixed_expenses: parseFloat(formData.fixed_expenses) || 0,
        tax_rate: parseFloat(formData.tax_rate) || 0,
        price_includes_tax: formData.price_includes_tax,
        vat_rate: parseFloat(formData.vat_rate) || 0,
        sales_commission: parseFloat(formData.sales_commission) || 0,
        card_fee: parseFloat(formData.card_fee) || 0,
        other_variable_costs: parseFloat(formData.other_variable_costs) || 0,
        investment_rate: parseFloat(formData.investment_rate) || 0,
        profit_margin: parseFloat(formData.profit_margin) || 0,
      };

      let result;
      if (isEditing) {
        result = await businessSettingService.update(setting.id, dataToSend);
      } else {
        result = await businessSettingService.create(dataToSend);
      }
      
      onSave(result);
    } catch (err) {
      setError(err.response?.data?.message || err.response?.data?.errors || t('common.error'));
    } finally {
      setSaving(false);
    }
  };

  const currencies = ['EUR', 'USD', 'BRL', 'GBP'];

  return (
    <div className="modal show d-block" style={{ background: 'rgba(0,0,0,0.8)' }}>
      <div className="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" style={{ maxHeight: '90vh' }}>
        <div className="modal-content" style={{ background: '#1e293b', border: 'none', maxHeight: '90vh' }}>
          <div className="modal-header border-0">
            <h5 className="modal-title text-white">
              <i className="bi bi-gear me-2"></i>
              {isEditing ? t('business.settings.edit') : t('business.settings.add')}
            </h5>
            <button type="button" className="btn-close btn-close-white" onClick={onClose}></button>
          </div>
          
          <form onSubmit={handleSubmit}>
            <div className="modal-body" style={{ maxHeight: 'calc(90vh - 130px)', overflowY: 'auto' }}>
              {error && (
                <div className="alert alert-danger">{typeof error === 'string' ? error : JSON.stringify(error)}</div>
              )}

              <div className="row g-3">
                {/* Nome e Moeda */}
                <div className="col-md-8">
                  <label className="form-label text-slate-400">{t('business.settings.name')}</label>
                  <input
                    type="text"
                    className="form-control bg-dark text-white border-secondary"
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    placeholder={t('business.settings.namePlaceholder')}
                    required
                  />
                </div>
                <div className="col-md-4">
                  <label className="form-label text-slate-400">{t('common.currency')}</label>
                  <select
                    className="form-select bg-dark text-white border-secondary"
                    name="currency"
                    value={formData.currency}
                    onChange={handleChange}
                    required
                  >
                    {currencies.map(c => (
                      <option key={c} value={c}>{c}</option>
                    ))}
                  </select>
                </div>

                {/* Tipo de Negócio */}
                <div className="col-12">
                  <hr className="border-secondary my-2" />
                  <h6 className="text-slate-400 small mb-3">
                    <i className="bi bi-shop me-2"></i>
                    {t('business.settings.businessType')}
                  </h6>
                </div>
                <div className="col-12">
                  <div className="row g-2">
                    <div className="col-4">
                      <div 
                        className={`p-2 rounded border text-center cursor-pointer ${formData.business_type === 'products' ? 'border-primary bg-primary bg-opacity-10' : 'border-secondary'}`}
                        onClick={() => setFormData(prev => ({ ...prev, business_type: 'products' }))}
                        style={{ cursor: 'pointer' }}
                      >
                        <i className={`bi bi-box-seam fs-4 ${formData.business_type === 'products' ? 'text-primary' : 'text-slate-400'}`}></i>
                        <div className={`small fw-bold mt-1 ${formData.business_type === 'products' ? 'text-white' : 'text-slate-400'}`}>
                          {t('business.settings.typeProducts')}
                        </div>
                      </div>
                    </div>
                    <div className="col-4">
                      <div 
                        className={`p-2 rounded border text-center cursor-pointer ${formData.business_type === 'services' ? 'border-success bg-success bg-opacity-10' : 'border-secondary'}`}
                        onClick={() => setFormData(prev => ({ ...prev, business_type: 'services' }))}
                        style={{ cursor: 'pointer' }}
                      >
                        <i className={`bi bi-person-workspace fs-4 ${formData.business_type === 'services' ? 'text-success' : 'text-slate-400'}`}></i>
                        <div className={`small fw-bold mt-1 ${formData.business_type === 'services' ? 'text-white' : 'text-slate-400'}`}>
                          {t('business.settings.typeServices')}
                        </div>
                      </div>
                    </div>
                    <div className="col-4">
                      <div 
                        className={`p-2 rounded border text-center cursor-pointer ${formData.business_type === 'both' ? 'border-warning bg-warning bg-opacity-10' : 'border-secondary'}`}
                        onClick={() => setFormData(prev => ({ ...prev, business_type: 'both' }))}
                        style={{ cursor: 'pointer' }}
                      >
                        <i className={`bi bi-shop-window fs-4 ${formData.business_type === 'both' ? 'text-warning' : 'text-slate-400'}`}></i>
                        <div className={`small fw-bold mt-1 ${formData.business_type === 'both' ? 'text-white' : 'text-slate-400'}`}>
                          {t('business.settings.typeBoth')}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Configuração de Horas Produtivas - Solo para servicios */}
                {(formData.business_type === 'services' || formData.business_type === 'both') && (
                  <>
                    <div className="col-12">
                      <div className="card bg-success bg-opacity-10 border-success">
                        <div className="card-body py-3">
                          <h6 className="text-success mb-3">
                            <i className="bi bi-clock-history me-2"></i>
                            {t('business.settings.productiveHours')}
                          </h6>
                          <div className="row g-2">
                            <div className="col-6 col-md-3">
                              <label className="form-label text-slate-400 small">{t('business.settings.employeesCount')}</label>
                              <input
                                type="number"
                                min="1"
                                className="form-control form-control-sm bg-dark text-white border-secondary"
                                name="employees_count"
                                value={formData.employees_count}
                                onChange={handleChange}
                              />
                            </div>
                            <div className="col-6 col-md-3">
                              <label className="form-label text-slate-400 small">{t('business.settings.hoursPerWeek')}</label>
                              <input
                                type="number"
                                step="0.5"
                                min="1"
                                max="168"
                                className="form-control form-control-sm bg-dark text-white border-secondary"
                                name="hours_per_week"
                                value={formData.hours_per_week}
                                onChange={handleChange}
                              />
                            </div>
                            <div className="col-6 col-md-3">
                              <label className="form-label text-slate-400 small">{t('business.settings.daysPerWeek')}</label>
                              <input
                                type="number"
                                min="1"
                                max="7"
                                className="form-control form-control-sm bg-dark text-white border-secondary"
                                name="working_days_per_week"
                                value={formData.working_days_per_week}
                                onChange={handleChange}
                              />
                            </div>
                            <div className="col-6 col-md-3">
                              <label className="form-label text-slate-400 small">{t('business.settings.productivity')}</label>
                              <div className="input-group input-group-sm">
                                <input
                                  type="number"
                                  min="10"
                                  max="100"
                                  className="form-control bg-dark text-white border-secondary"
                                  name="productivity_rate"
                                  value={formData.productivity_rate}
                                  onChange={handleChange}
                                />
                                <span className="input-group-text bg-dark text-slate-400 border-secondary">%</span>
                              </div>
                            </div>
                          </div>
                          <div className="row g-2 mt-1">
                            <div className="col-6 col-md-3">
                              <label className="form-label text-slate-400 small">{t('business.settings.workingDays')}</label>
                              <input
                                type="number"
                                min="1"
                                max="31"
                                className="form-control form-control-sm bg-dark text-white border-secondary"
                                name="working_days_per_month"
                                value={formData.working_days_per_month}
                                onChange={handleChange}
                              />
                            </div>
                            <div className="col-6 col-md-9">
                              <label className="form-label text-slate-400 small">{t('business.settings.derivedHoursPerDay')}</label>
                              <input
                                type="text"
                                readOnly
                                className="form-control form-control-sm bg-secondary bg-opacity-25 text-slate-300 border-secondary"
                                value={preview ? `${preview.hoursPerDay} ${t('business.common.hoursPerDayUnit')}` : '-'}
                              />
                            </div>
                          </div>
                          {preview && (
                            <div className="mt-3 pt-3 border-top border-success border-opacity-25">
                              <div className="row text-center small">
                                <div className="col-6">
                                  <span className="text-slate-400">{t('business.settings.totalProductiveHours')}:</span>
                                  <span className="text-white ms-2 fw-bold">{preview.productiveHours} h/{t('common.month')}</span>
                                </div>
                                <div className="col-6">
                                  <span className="text-slate-400">{t('business.settings.fixedCostPerHour')}:</span>
                                  <span className="text-success ms-2 fw-bold">{formData.currency} {preview.fixedCostPerHour}{t('business.common.perHourUnit')}</span>
                                </div>
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </>
                )}

                {/* Receita e Despesas Fixas */}
                <div className="col-12">
                  <hr className="border-secondary my-2" />
                  <h6 className="text-slate-400 small mb-3">
                    <i className="bi bi-graph-up me-2"></i>
                    {t('business.settings.revenueAndExpenses')}
                  </h6>
                </div>
                
                {/* Receita mensal - Solo para productos */}
                {(formData.business_type === 'products' || formData.business_type === 'both') && (
                <div className="col-md-6">
                  <label className="form-label text-slate-400">{t('business.settings.monthlyRevenue')}</label>
                  <input
                    type="number"
                    step="0.01"
                    className="form-control bg-dark text-white border-secondary"
                    name="monthly_revenue"
                    value={formData.monthly_revenue}
                    onChange={handleChange}
                    placeholder="40000.00"
                    required={formData.business_type === 'products'}
                  />
                  <small className="text-slate-500">{t('business.settings.monthlyRevenueHelp')}</small>
                </div>
                )}
                <div className={formData.business_type === 'services' ? 'col-12' : 'col-md-6'}>
                  <label className="form-label text-slate-400">{t('business.settings.fixedExpenses')}</label>
                  <input
                    type="number"
                    step="0.01"
                    className="form-control bg-dark text-white border-secondary"
                    name="fixed_expenses"
                    value={formData.fixed_expenses}
                    onChange={handleChange}
                    placeholder="12000.00"
                    required
                  />
                  <small className="text-slate-500">{t('business.settings.fixedExpensesHelp')}</small>
                </div>

                {/* Custos Variáveis */}
                <div className="col-12">
                  <hr className="border-secondary my-2" />
                  <h6 className="text-slate-400 small mb-3">
                    <i className="bi bi-percent me-2"></i>
                    {t('business.settings.variableCosts')} (%)
                  </h6>
                </div>

                {/* B2B vs B2C - Tipo de Precio */}
                <div className="col-12">
                  <div className="card bg-info bg-opacity-10 border-info mb-3">
                    <div className="card-body py-3">
                      <div className="d-flex align-items-start gap-3">
                        <i className="bi bi-info-circle text-info fs-4"></i>
                        <div className="flex-grow-1">
                          <h6 className="text-info mb-2">{t('business.settings.priceType')}</h6>
                          <div className="d-flex gap-4">
                            <div className="form-check">
                              <input
                                type="radio"
                                className="form-check-input"
                                id="priceB2C"
                                name="price_includes_tax"
                                checked={formData.price_includes_tax === true}
                                onChange={() => setFormData(prev => ({ ...prev, price_includes_tax: true }))}
                              />
                              <label className="form-check-label" htmlFor="priceB2C">
                                <strong className="text-white">B2C</strong>
                                <small className="d-block text-slate-400">{t('business.settings.b2cDescription')}</small>
                              </label>
                            </div>
                            <div className="form-check">
                              <input
                                type="radio"
                                className="form-check-input"
                                id="priceB2B"
                                name="price_includes_tax"
                                checked={formData.price_includes_tax === false}
                                onChange={() => setFormData(prev => ({ ...prev, price_includes_tax: false }))}
                              />
                              <label className="form-check-label" htmlFor="priceB2B">
                                <strong className="text-white">B2B</strong>
                                <small className="d-block text-slate-400">{t('business.settings.b2bDescription')}</small>
                              </label>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* IVA/VAT Rate - Solo visible en B2C */}
                {formData.price_includes_tax && (
                  <div className="col-md-3">
                    <label className="form-label text-slate-400">
                      {t('business.settings.vatRate')}
                      <i className="bi bi-info-circle ms-1" title={t('business.settings.vatRateHelp')}></i>
                    </label>
                    <div className="input-group">
                      <input
                        type="number"
                        step="0.01"
                        className="form-control bg-dark text-white border-secondary"
                        name="vat_rate"
                        value={formData.vat_rate}
                        onChange={handleChange}
                        placeholder="21"
                      />
                      <span className="input-group-text bg-dark text-slate-400 border-secondary">%</span>
                    </div>
                    <small className="text-slate-500">{t('business.settings.vatRateExample')}</small>
                  </div>
                )}

                <div className="col-md-3">
                  <label className="form-label text-slate-400">
                    {formData.price_includes_tax ? t('business.settings.otherTaxes') : t('business.settings.taxRate')}
                  </label>
                  <div className="input-group">
                    <input
                      type="number"
                      step="0.01"
                      className="form-control bg-dark text-white border-secondary"
                      name="tax_rate"
                      value={formData.tax_rate}
                      onChange={handleChange}
                      placeholder={formData.price_includes_tax ? "0" : "9"}
                      required
                    />
                    <span className="input-group-text bg-dark text-slate-400 border-secondary">%</span>
                  </div>
                  {formData.price_includes_tax && (
                    <small className="text-slate-500">{t('business.settings.otherTaxesHelp')}</small>
                  )}
                </div>
                <div className="col-md-3">
                  <label className="form-label text-slate-400">{t('business.settings.salesCommission')}</label>
                  <div className="input-group">
                    <input
                      type="number"
                      step="0.01"
                      className="form-control bg-dark text-white border-secondary"
                      name="sales_commission"
                      value={formData.sales_commission}
                      onChange={handleChange}
                      placeholder="5"
                      required
                    />
                    <span className="input-group-text bg-dark text-slate-400 border-secondary">%</span>
                  </div>
                </div>
                <div className="col-md-3">
                  <label className="form-label text-slate-400">{t('business.settings.cardFee')}</label>
                  <div className="input-group">
                    <input
                      type="number"
                      step="0.01"
                      className="form-control bg-dark text-white border-secondary"
                      name="card_fee"
                      value={formData.card_fee}
                      onChange={handleChange}
                      placeholder="3"
                      required
                    />
                    <span className="input-group-text bg-dark text-slate-400 border-secondary">%</span>
                  </div>
                </div>
                <div className="col-md-3">
                  <label className="form-label text-slate-400">{t('business.settings.otherVariableCosts')}</label>
                  <div className="input-group">
                    <input
                      type="number"
                      step="0.01"
                      className="form-control bg-dark text-white border-secondary"
                      name="other_variable_costs"
                      value={formData.other_variable_costs}
                      onChange={handleChange}
                      placeholder="0"
                    />
                    <span className="input-group-text bg-dark text-slate-400 border-secondary">%</span>
                  </div>
                </div>

                {/* Investimento e Lucro */}
                <div className="col-12">
                  <hr className="border-secondary my-2" />
                  <h6 className="text-slate-400 small mb-3">
                    <i className="bi bi-piggy-bank me-2"></i>
                    {t('business.settings.investmentAndProfit')} (%)
                  </h6>
                </div>
                <div className="col-md-6">
                  <label className="form-label text-slate-400">{t('business.settings.investmentRate')}</label>
                  <div className="input-group">
                    <input
                      type="number"
                      step="0.01"
                      className="form-control bg-dark text-white border-secondary"
                      name="investment_rate"
                      value={formData.investment_rate}
                      onChange={handleChange}
                      placeholder="10"
                      required
                    />
                    <span className="input-group-text bg-dark text-slate-400 border-secondary">%</span>
                  </div>
                  <small className="text-slate-500">{t('business.settings.investmentRateHelp')}</small>
                </div>
                <div className="col-md-6">
                  <label className="form-label text-slate-400">{t('business.settings.profitMargin')}</label>
                  <div className="input-group">
                    <input
                      type="number"
                      step="0.01"
                      className="form-control bg-dark text-white border-secondary"
                      name="profit_margin"
                      value={formData.profit_margin}
                      onChange={handleChange}
                      placeholder="15"
                      required
                    />
                    <span className="input-group-text bg-dark text-slate-400 border-secondary">%</span>
                  </div>
                  <small className="text-slate-500">{t('business.settings.profitMarginHelp')}</small>
                </div>

                {/* Preview do Markup */}
                {preview && (
                  <div className="col-12">
                    <hr className="border-secondary my-2" />
                    <div className={`p-3 rounded ${preview.isValid ? '' : 'border border-danger'}`} style={{ background: 'rgba(59, 130, 246, 0.1)' }}>
                      <h6 className="text-slate-400 small mb-3">
                        <i className="bi bi-calculator me-2"></i>
                        {t('business.settings.markupPreview')}
                      </h6>
                      
                      <div className="row g-2 small mb-3">
                        <div className="col-6 col-md-3">
                          <span className="text-slate-500">{t('business.settings.fixedExpensesRate')}:</span>
                          <span className="text-white ms-2">{preview.fixedExpensesRate}%</span>
                        </div>
                        <div className="col-6 col-md-3">
                          <span className="text-slate-500">{t('business.settings.totalVariableCosts')}:</span>
                          <span className="text-white ms-2">{preview.totalVariableCosts}%</span>
                        </div>
                        <div className="col-6 col-md-3">
                          <span className="text-slate-500">{t('business.settings.totalDeductions')}:</span>
                          <span className="text-warning ms-2">{preview.totalDeductions}%</span>
                        </div>
                        {preview.priceIncludesTax && (
                          <div className="col-6 col-md-3">
                            <span className="text-slate-500">{t('business.settings.vatRate')}:</span>
                            <span className="text-info ms-2">{preview.vatRate}%</span>
                          </div>
                        )}
                      </div>
                      
                      {preview.isValid ? (
                        <div className="text-center">
                          {preview.priceIncludesTax ? (
                            <>
                              <div className="d-flex justify-content-center align-items-center gap-4">
                                <div>
                                  <small className="text-slate-500 d-block">{t('business.settings.baseMarkup')}</small>
                                  <span className="text-white fs-5">{preview.markup}</span>
                                </div>
                                <span className="text-slate-500 fs-4">×</span>
                                <div>
                                  <small className="text-slate-500 d-block">{t('business.common.plusVat')}</small>
                                  <span className="text-info fs-5">{(1 + parseFloat(preview.vatRate) / 100).toFixed(2)}</span>
                                </div>
                                <span className="text-slate-500 fs-4">=</span>
                                <div>
                                  <small className="text-slate-500 d-block">{t('business.settings.finalMultiplier')}</small>
                                  <span className="text-primary fs-4 fw-bold">{preview.finalMultiplier}</span>
                                </div>
                              </div>
                              <small className="text-info mt-2 d-block">
                                <i className="bi bi-info-circle me-1"></i>
                                {t('business.settings.vatIncluded')}
                              </small>
                            </>
                          ) : (
                            <>
                              <span className="text-slate-400">{t('business.settings.markupFactor')}:</span>
                              <h3 className="text-primary mb-0">{preview.markup}</h3>
                            </>
                          )}
                        </div>
                      ) : (
                        <div className="text-center text-danger">
                          <i className="bi bi-exclamation-triangle me-2"></i>
                          {t('business.settings.invalidMarkup')}
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Status */}
                {isEditing && (
                  <div className="col-12">
                    <div className="form-check">
                      <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-400" htmlFor="is_active">
                        {t('business.settings.isActive')}
                      </label>
                    </div>
                  </div>
                )}
              </div>
            </div>
            
            <div className="modal-footer border-0">
              <button type="button" className="btn btn-secondary" onClick={onClose}>
                {t('common.cancel')}
              </button>
              <button 
                type="submit" 
                className="btn btn-primary" 
                disabled={saving || (preview && !preview.isValid)}
              >
                {saving ? (
                  <>
                    <span className="spinner-border spinner-border-sm me-2"></span>
                    {t('common.saving')}
                  </>
                ) : (
                  <>
                    <i className="bi bi-check-lg me-2"></i>
                    {t('common.save')}
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default BusinessSettingModal;
