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

const CampaignModal = ({ isOpen, onClose, onSaved, campaign, presets, sheets }) => {
  const { t } = useTranslation();
  const { currency } = useFormatters();
  
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [activeStep, setActiveStep] = useState(1);
  const [preview, setPreview] = useState(null);
  
  const [formData, setFormData] = useState({
    name: '',
    code: '',
    description: '',
    discount_type: 'percentage',
    discount_value: 10,
    start_date: '',
    end_date: '',
    start_time: '',
    end_time: '',
    is_active: true,
    apply_to_all_products: false,
    min_price: '',
    min_margin_percent: '',
    protect_against_loss: true,
    show_original_price: true,
    show_discount_badge: true,
    badge_text: '',
    badge_color: '#ef4444',
    priority: 0,
    product_ids: [],
  });

  // Preset colors for badges
  const badgeColors = [
    { name: 'Red', value: '#ef4444' },
    { name: 'Orange', value: '#f97316' },
    { name: 'Yellow', value: '#eab308' },
    { name: 'Green', value: '#22c55e' },
    { name: 'Blue', value: '#3b82f6' },
    { name: 'Purple', value: '#8b5cf6' },
    { name: 'Pink', value: '#ec4899' },
    { name: 'Black', value: '#000000' },
  ];

  // Initialize form when campaign changes
  useEffect(() => {
    if (isOpen) {
      if (campaign?.id) {
        // Editing existing campaign
        setFormData({
          name: campaign.name || '',
          code: campaign.code || '',
          description: campaign.description || '',
          discount_type: campaign.discount_type || 'percentage',
          discount_value: parseFloat(campaign.discount_value) || 10,
          start_date: campaign.start_date?.split('T')[0] || '',
          end_date: campaign.end_date?.split('T')[0] || '',
          start_time: campaign.start_time || '',
          end_time: campaign.end_time || '',
          is_active: campaign.is_active !== false,
          apply_to_all_products: campaign.apply_to_all_products || false,
          min_price: campaign.min_price || '',
          min_margin_percent: campaign.min_margin_percent || '',
          protect_against_loss: campaign.protect_against_loss !== false,
          show_original_price: campaign.show_original_price !== false,
          show_discount_badge: campaign.show_discount_badge !== false,
          badge_text: campaign.badge_text || '',
          badge_color: campaign.badge_color || '#ef4444',
          priority: campaign.priority || 0,
          product_ids: campaign.products?.map(p => p.id) || [],
        });
        setActiveStep(1);
      } else if (campaign?.preset && presets[campaign.preset]) {
        // Creating from preset
        const preset = presets[campaign.preset];
        const today = new Date();
        const endDate = new Date();
        endDate.setDate(endDate.getDate() + 7);
        
        setFormData({
          name: preset.name || '',
          code: preset.code || '',
          description: preset.description || '',
          discount_type: preset.discount_type || 'percentage',
          discount_value: parseFloat(preset.discount_value) || 10,
          start_date: today.toISOString().split('T')[0],
          end_date: endDate.toISOString().split('T')[0],
          start_time: preset.start_time || '',
          end_time: preset.end_time || '',
          is_active: true,
          apply_to_all_products: false,
          min_price: preset.min_price || '',
          min_margin_percent: '',
          protect_against_loss: true,
          show_original_price: preset.show_original_price !== false,
          show_discount_badge: preset.show_discount_badge !== false,
          badge_text: preset.badge_text || '',
          badge_color: preset.badge_color || '#ef4444',
          priority: preset.priority || 0,
          product_ids: [],
        });
        setActiveStep(1);
      } else {
        // New campaign
        const today = new Date();
        const endDate = new Date();
        endDate.setDate(endDate.getDate() + 7);
        
        setFormData({
          name: '',
          code: '',
          description: '',
          discount_type: 'percentage',
          discount_value: 10,
          start_date: today.toISOString().split('T')[0],
          end_date: endDate.toISOString().split('T')[0],
          start_time: '',
          end_time: '',
          is_active: true,
          apply_to_all_products: false,
          min_price: '',
          min_margin_percent: '',
          protect_against_loss: true,
          show_original_price: true,
          show_discount_badge: true,
          badge_text: '',
          badge_color: '#ef4444',
          priority: 0,
          product_ids: [],
        });
        setActiveStep(1);
      }
      setError(null);
      setPreview(null);
    }
  }, [isOpen, campaign, presets]);

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

  const handleProductToggle = (productId) => {
    setFormData(prev => ({
      ...prev,
      product_ids: prev.product_ids.includes(productId)
        ? prev.product_ids.filter(id => id !== productId)
        : [...prev.product_ids, productId],
    }));
  };

  const handleSelectAllProducts = () => {
    const allIds = sheets.map(s => s.id);
    setFormData(prev => ({
      ...prev,
      product_ids: prev.product_ids.length === allIds.length ? [] : allIds,
    }));
  };

  // Preview calculation
  const loadPreview = async () => {
    if (formData.product_ids.length === 0 && !formData.apply_to_all_products) return;
    
    try {
      const productIds = formData.apply_to_all_products 
        ? sheets.map(s => s.id) 
        : formData.product_ids;
        
      const result = await campaignService.preview({
        discount_type: formData.discount_type,
        discount_value: parseFloat(formData.discount_value) || 0,
        min_price: formData.min_price ? parseFloat(formData.min_price) : null,
        min_margin_percent: formData.min_margin_percent ? parseFloat(formData.min_margin_percent) : null,
        protect_against_loss: formData.protect_against_loss,
        product_ids: productIds,
      });
      setPreview(result);
    } catch (err) {
      console.error('Preview error:', err);
    }
  };

  useEffect(() => {
    if (activeStep === 3) {
      loadPreview();
    }
  }, [activeStep, formData.discount_type, formData.discount_value, formData.min_price, formData.min_margin_percent, formData.protect_against_loss, formData.product_ids]);

  // Form validation
  const isStepValid = useMemo(() => {
    switch (activeStep) {
      case 1:
        return formData.name && formData.discount_value > 0 && formData.start_date && formData.end_date;
      case 2:
        return formData.apply_to_all_products || formData.product_ids.length > 0;
      case 3:
        return true;
      default:
        return false;
    }
  }, [activeStep, formData]);

  const handleSubmit = async () => {
    setLoading(true);
    setError(null);
    
    try {
      const data = {
        ...formData,
        discount_value: parseFloat(formData.discount_value) || 0,
        min_price: formData.min_price ? parseFloat(formData.min_price) : null,
        priority: parseInt(formData.priority) || 0,
      };
      
      let result;
      if (campaign?.id) {
        result = await campaignService.update(campaign.id, data);
      } else {
        result = await campaignService.create(data);
      }
      
      onSaved(result);
    } catch (err) {
      setError(err.response?.data?.message || err.response?.data?.errors || t('common.error'));
    } finally {
      setLoading(false);
    }
  };

  // Moved BEFORE conditional return to respect React hooks rules
  const discountPreview = useMemo(() => {
    const basePrice = 100;
    let promoPrice = basePrice;
    
    switch (formData.discount_type) {
      case 'percentage':
        promoPrice = basePrice * (1 - (parseFloat(formData.discount_value) || 0) / 100);
        break;
      case 'fixed':
        promoPrice = basePrice - (parseFloat(formData.discount_value) || 0);
        break;
      case 'price_override':
        promoPrice = parseFloat(formData.discount_value) || 0;
        break;
    }
    
    return { original: basePrice, promo: Math.max(0, promoPrice) };
  }, [formData.discount_type, formData.discount_value]);

  if (!isOpen) return null;

  return (
    <div className="modal fade show d-block" tabIndex="-1" style={{ backgroundColor: 'rgba(0,0,0,0.7)' }}>
      <div className="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div className="modal-content bg-dark text-white">
          {/* Header */}
          <div className="modal-header border-secondary">
            <h5 className="modal-title">
              <i className="bi bi-megaphone me-2"></i>
              {campaign?.id ? t('campaigns.edit') : t('campaigns.create')}
            </h5>
            <button type="button" className="btn-close btn-close-white" onClick={onClose}></button>
          </div>

          {/* Progress Steps */}
          <div className="px-4 pt-3">
            <div className="d-flex justify-content-between">
              {[1, 2, 3].map(step => (
                <div 
                  key={step}
                  className={`flex-fill text-center ${step < 3 ? 'border-bottom pb-2' : ''}`}
                  style={{ 
                    borderColor: step <= activeStep ? '#3b82f6' : 'rgba(255,255,255,0.2)',
                    borderWidth: step <= activeStep ? '2px' : '1px',
                  }}
                >
                  <span 
                    className={`badge rounded-circle ${step === activeStep ? 'bg-primary' : step < activeStep ? 'bg-success' : 'bg-secondary'}`}
                    style={{ width: '24px', height: '24px', lineHeight: '16px' }}
                  >
                    {step < activeStep ? <i className="bi bi-check"></i> : step}
                  </span>
                  <small className={`d-block mt-1 ${step === activeStep ? 'text-primary' : 'text-slate-400'}`}>
                    {step === 1 && t('campaigns.steps.details')}
                    {step === 2 && t('campaigns.steps.products')}
                    {step === 3 && t('campaigns.steps.review')}
                  </small>
                </div>
              ))}
            </div>
          </div>

          {/* Body */}
          <div className="modal-body">
            {error && (
              <div className="alert alert-danger d-flex align-items-center mb-3">
                <i className="bi bi-exclamation-triangle me-2"></i>
                {typeof error === 'object' ? JSON.stringify(error) : error}
              </div>
            )}

            {/* Step 1: Campaign Details */}
            {activeStep === 1 && (
              <div className="step-content">
                {/* Nome e Código */}
                <div className="row g-3 mb-3">
                  <div className="col-md-8">
                    <label className="form-label">{t('campaigns.form.name')} *</label>
                    <input
                      type="text"
                      className="form-control bg-dark text-white"
                      name="name"
                      value={formData.name}
                      onChange={handleChange}
                      placeholder={t('campaigns.form.namePlaceholder')}
                    />
                  </div>
                  <div className="col-md-4">
                    <label className="form-label">{t('campaigns.form.code')}</label>
                    <input
                      type="text"
                      className="form-control bg-dark text-white"
                      name="code"
                      value={formData.code}
                      onChange={handleChange}
                      placeholder="BLACK2024"
                    />
                  </div>
                </div>

                {/* Descrição */}
                <div className="mb-3">
                  <label className="form-label">{t('campaigns.form.description')}</label>
                  <textarea
                    className="form-control bg-dark text-white"
                    name="description"
                    rows="2"
                    value={formData.description}
                    onChange={handleChange}
                  ></textarea>
                </div>

                {/* Tipo e Valor do Desconto */}
                <div className="row g-3 mb-3">
                  <div className="col-md-6">
                    <label className="form-label">{t('campaigns.form.discountType')} *</label>
                    <select
                      className="form-select bg-dark text-white"
                      name="discount_type"
                      value={formData.discount_type}
                      onChange={handleChange}
                    >
                      <option value="percentage">{t('campaigns.discountTypes.percentage')}</option>
                      <option value="fixed">{t('campaigns.discountTypes.fixed')}</option>
                      <option value="price_override">{t('campaigns.discountTypes.priceOverride')}</option>
                    </select>
                  </div>
                  <div className="col-md-6">
                    <label className="form-label">{t('campaigns.form.discountValue')} *</label>
                    <div className="input-group">
                      {formData.discount_type !== 'percentage' && (
                        <span className="input-group-text bg-secondary text-white">$</span>
                      )}
                      <input
                        type="number"
                        className="form-control bg-dark text-white"
                        name="discount_value"
                        value={formData.discount_value}
                        onChange={handleChange}
                        min="0"
                        step={formData.discount_type === 'percentage' ? '1' : '0.01'}
                      />
                      {formData.discount_type === 'percentage' && (
                        <span className="input-group-text bg-secondary text-white">%</span>
                      )}
                    </div>
                  </div>
                </div>

                {/* Preview do Desconto */}
                <div className="alert alert-info d-flex align-items-center justify-content-center mb-3">
                  <span className="text-muted me-2">{t('campaigns.form.example')}:</span>
                  <span className="text-decoration-line-through me-2">{currency(discountPreview.original)}</span>
                  <i className="bi bi-arrow-right mx-2"></i>
                  <span className="fw-bold text-success">{currency(discountPreview.promo)}</span>
                </div>

                {/* PROTEÇÃO DE RENTABILIDADE */}
                <div className="card bg-success bg-opacity-10 border-success mb-3">
                  <div className="card-body">
                    <h6 className="text-success mb-3">
                      <i className="bi bi-shield-check me-2"></i>
                      {t('campaigns.form.profitProtection')}
                    </h6>

                    <div className="form-check mb-3">
                      <input
                        type="checkbox"
                        className="form-check-input"
                        id="protect_against_loss"
                        name="protect_against_loss"
                        checked={formData.protect_against_loss}
                        onChange={handleChange}
                      />
                      <label className="form-check-label" htmlFor="protect_against_loss">
                        <strong>{t('campaigns.form.protectAgainstLoss')}</strong>
                        <small className="d-block text-slate-400">{t('campaigns.form.protectAgainstLossHelp')}</small>
                      </label>
                    </div>

                    <div className="row g-3">
                      <div className="col-md-6">
                        <label className="form-label">{t('campaigns.form.minPrice')}</label>
                        <input
                          type="number"
                          className="form-control bg-dark text-white"
                          name="min_price"
                          value={formData.min_price}
                          onChange={handleChange}
                          min="0"
                          step="0.01"
                          placeholder={t('campaigns.form.minPricePlaceholder')}
                        />
                        <small className="text-slate-400">{t('campaigns.form.minPriceHelp')}</small>
                      </div>
                      <div className="col-md-6">
                        <label className="form-label">{t('campaigns.form.minMarginPercent')}</label>
                        <div className="input-group">
                          <input
                            type="number"
                            className="form-control bg-dark text-white"
                            name="min_margin_percent"
                            value={formData.min_margin_percent}
                            onChange={handleChange}
                            min="0"
                            max="100"
                            step="1"
                            placeholder="5"
                          />
                          <span className="input-group-text bg-secondary text-white">%</span>
                        </div>
                        <small className="text-slate-400">{t('campaigns.form.minMarginHelp')}</small>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Datas */}
                <div className="row g-3 mb-3">
                  <div className="col-md-6">
                    <label className="form-label">{t('campaigns.form.startDate')} *</label>
                    <input
                      type="date"
                      className="form-control bg-dark text-white"
                      name="start_date"
                      value={formData.start_date}
                      onChange={handleChange}
                    />
                  </div>
                  <div className="col-md-6">
                    <label className="form-label">{t('campaigns.form.endDate')} *</label>
                    <input
                      type="date"
                      className="form-control bg-dark text-white"
                      name="end_date"
                      value={formData.end_date}
                      onChange={handleChange}
                    />
                  </div>
                </div>

                {/* Horas */}
                <div className="row g-3 mb-3">
                  <div className="col-md-6">
                    <label className="form-label">{t('campaigns.form.startTime')}</label>
                    <input
                      type="time"
                      className="form-control bg-dark text-white"
                      name="start_time"
                      value={formData.start_time}
                      onChange={handleChange}
                    />
                  </div>
                  <div className="col-md-6">
                    <label className="form-label">{t('campaigns.form.endTime')}</label>
                    <input
                      type="time"
                      className="form-control bg-dark text-white"
                      name="end_time"
                      value={formData.end_time}
                      onChange={handleChange}
                    />
                  </div>
                </div>

                {/* Badge Settings */}
                <div className="card bg-secondary bg-opacity-25 mb-3">
                  <div className="card-body">
                    <h6 className="text-white mb-3">
                      <i className="bi bi-tag me-2"></i>
                      {t('campaigns.form.badgeSettings')}
                    </h6>
                    
                    <div className="form-check mb-2">
                      <input
                        type="checkbox"
                        className="form-check-input"
                        id="show_discount_badge"
                        name="show_discount_badge"
                        checked={formData.show_discount_badge}
                        onChange={handleChange}
                      />
                      <label className="form-check-label" htmlFor="show_discount_badge">
                        {t('campaigns.form.showBadge')}
                      </label>
                    </div>

                    <div className="form-check mb-3">
                      <input
                        type="checkbox"
                        className="form-check-input"
                        id="show_original_price"
                        name="show_original_price"
                        checked={formData.show_original_price}
                        onChange={handleChange}
                      />
                      <label className="form-check-label" htmlFor="show_original_price">
                        {t('campaigns.form.showOriginalPrice')}
                      </label>
                    </div>

                    {formData.show_discount_badge && (
                      <>
                        <div className="mb-3">
                          <label className="form-label">{t('campaigns.form.badgeText')}</label>
                          <input
                            type="text"
                            className="form-control bg-dark text-white"
                            name="badge_text"
                            value={formData.badge_text}
                            onChange={handleChange}
                            placeholder="-30% OFF"
                          />
                        </div>

                        <div className="mb-2">
                          <label className="form-label">{t('campaigns.form.badgeColor')}</label>
                          <div className="d-flex flex-wrap gap-2">
                            {badgeColors.map(color => (
                              <button
                                key={color.value}
                                type="button"
                                className={`btn btn-sm ${formData.badge_color === color.value ? 'border-2 border-white' : 'border-0'}`}
                                style={{ 
                                  backgroundColor: color.value, 
                                  width: '32px', 
                                  height: '32px',
                                }}
                                onClick={() => setFormData(prev => ({ ...prev, badge_color: color.value }))}
                              ></button>
                            ))}
                          </div>
                        </div>

                        {/* Badge Preview */}
                        <div className="mt-3">
                          <span className="text-slate-400 small me-2">{t('campaigns.form.preview')}:</span>
                          <span 
                            className="badge"
                            style={{ 
                              backgroundColor: formData.badge_color,
                              color: '#fff',
                              fontSize: '0.9rem',
                            }}
                          >
                            {formData.badge_text || `-${formData.discount_value}%`}
                          </span>
                        </div>
                      </>
                    )}
                  </div>
                </div>

                {/* Ativo */}
                <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" htmlFor="is_active">
                    {t('campaigns.form.isActive')}
                  </label>
                </div>
              </div>
            )}

            {/* Step 2: Select Products */}
            {activeStep === 2 && (
              <div className="step-content">
                <div className="form-check mb-4">
                  <input
                    type="checkbox"
                    className="form-check-input"
                    id="apply_to_all_products"
                    name="apply_to_all_products"
                    checked={formData.apply_to_all_products}
                    onChange={handleChange}
                  />
                  <label className="form-check-label" htmlFor="apply_to_all_products">
                    <strong>{t('campaigns.form.applyToAll')}</strong>
                    <small className="d-block text-slate-400">{t('campaigns.form.applyToAllHelp')}</small>
                  </label>
                </div>

                {!formData.apply_to_all_products && (
                  <>
                    <div className="d-flex justify-content-between align-items-center mb-3">
                      <span className="text-slate-400">
                        {formData.product_ids.length} {t('campaigns.productsSelected')}
                      </span>
                      <button 
                        type="button"
                        className="btn btn-sm btn-outline-primary"
                        onClick={handleSelectAllProducts}
                      >
                        {formData.product_ids.length === sheets.length 
                          ? t('campaigns.deselectAll') 
                          : t('campaigns.selectAll')}
                      </button>
                    </div>

                    <div className="products-list" style={{ maxHeight: '400px', overflowY: 'auto' }}>
                      {sheets.map(sheet => (
                        <div 
                          key={sheet.id}
                          className={`d-flex align-items-center justify-content-between p-2 rounded mb-2 cursor-pointer ${
                            formData.product_ids.includes(sheet.id) 
                              ? 'bg-primary bg-opacity-25 border border-primary' 
                              : 'bg-secondary bg-opacity-25'
                          }`}
                          onClick={() => handleProductToggle(sheet.id)}
                          style={{ cursor: 'pointer' }}
                        >
                          <div className="d-flex align-items-center gap-2">
                            <input
                              type="checkbox"
                              className="form-check-input"
                              checked={formData.product_ids.includes(sheet.id)}
                              onChange={() => {}}
                            />
                            <div>
                              <div className="text-white">{sheet.name}</div>
                              <small className="text-slate-400">{sheet.category}</small>
                            </div>
                          </div>
                          <div className="text-end">
                            <div className="text-white">{currency(sheet.final_price || sheet.sale_price)}</div>
                            <small className="text-success">
                              {currency(parseFloat(sheet.final_price || sheet.sale_price) * (1 - parseFloat(formData.discount_value) / 100))}
                            </small>
                          </div>
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </div>
            )}

            {/* Step 3: Review */}
            {activeStep === 3 && (
              <div className="step-content">
                <div className="card bg-secondary bg-opacity-25 mb-3">
                  <div className="card-body">
                    <h6 className="text-white mb-3">{t('campaigns.review.summary')}</h6>
                    
                    <div className="row g-3">
                      <div className="col-6">
                        <small className="text-slate-400">{t('campaigns.form.name')}</small>
                        <div className="text-white">{formData.name}</div>
                      </div>
                      <div className="col-6">
                        <small className="text-slate-400">{t('campaigns.discount')}</small>
                        <div className="text-white">
                          {formData.discount_type === 'percentage' && `-${formData.discount_value}%`}
                          {formData.discount_type === 'fixed' && `-${currency(formData.discount_value)}`}
                          {formData.discount_type === 'price_override' && currency(formData.discount_value)}
                        </div>
                      </div>
                      <div className="col-6">
                        <small className="text-slate-400">{t('campaigns.period')}</small>
                        <div className="text-white">{formData.start_date} - {formData.end_date}</div>
                      </div>
                      <div className="col-6">
                        <small className="text-slate-400">{t('campaigns.products')}</small>
                        <div className="text-white">
                          {formData.apply_to_all_products 
                            ? t('campaigns.allProducts') 
                            : `${formData.product_ids.length} ${t('campaigns.productsSelected')}`}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Preview Results */}
                {preview && (
                  <>
                    {/* Alertas de Rentabilidade */}
                    {preview.totals?.unprofitable_count > 0 && (
                      <div className="alert alert-danger d-flex align-items-center mb-3">
                        <i className="bi bi-exclamation-triangle-fill me-2"></i>
                        <div>
                          <strong>{t('campaigns.review.profitWarning')}</strong>
                          <div className="small">
                            {t('campaigns.review.unprofitableProducts', { count: preview.totals.unprofitable_count })}
                          </div>
                        </div>
                      </div>
                    )}
                    
                    {preview.totals?.protected_count > 0 && (
                      <div className="alert alert-info d-flex align-items-center mb-3">
                        <i className="bi bi-shield-check me-2"></i>
                        <div>
                          <strong>{t('campaigns.review.pricesProtected')}</strong>
                          <div className="small">
                            {t('campaigns.review.protectedProducts', { count: preview.totals.protected_count })}
                          </div>
                        </div>
                      </div>
                    )}
                    
                    <div className="card bg-secondary bg-opacity-25 mb-3">
                      <div className="card-body">
                        <h6 className="text-white mb-3">{t('campaigns.review.priceImpact')}</h6>
                        
                        <div className="row g-3 mb-3">
                          <div className="col-3">
                            <div className="text-center">
                              <small className="text-slate-400">{t('campaigns.review.totalOriginal')}</small>
                              <div className="h5 text-white mb-0">{currency(preview.totals?.total_original || 0)}</div>
                            </div>
                          </div>
                          <div className="col-3">
                            <div className="text-center">
                              <small className="text-slate-400">{t('campaigns.review.totalPromo')}</small>
                              <div className="h5 text-success mb-0">{currency(preview.totals?.total_promotional || 0)}</div>
                            </div>
                          </div>
                          <div className="col-3">
                            <div className="text-center">
                              <small className="text-slate-400">{t('campaigns.review.avgDiscount')}</small>
                              <div className="h5 text-warning mb-0">-{(preview.totals?.avg_discount || 0).toFixed(1)}%</div>
                            </div>
                          </div>
                          <div className="col-3">
                            <div className="text-center">
                              <small className="text-slate-400">{t('campaigns.review.totalCmv')}</small>
                              <div className="h5 text-slate-300 mb-0">{currency(preview.totals?.total_cmv || 0)}</div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    {/* Análise de Rentabilidade */}
                    <div className="card bg-success bg-opacity-10 border-success mb-3">
                      <div className="card-body">
                        <h6 className="text-success mb-3">
                          <i className="bi bi-graph-up-arrow me-2"></i>
                          {t('campaigns.review.profitAnalysis')}
                        </h6>
                        
                        <div className="row g-3">
                          <div className="col-4">
                            <div className="text-center">
                              <small className="text-slate-400">{t('campaigns.review.totalProfit')}</small>
                              <div className={`h5 mb-0 ${(preview.totals?.total_promo_margin || 0) >= 0 ? 'text-success' : 'text-danger'}`}>
                                {currency(preview.totals?.total_promo_margin || 0)}
                              </div>
                            </div>
                          </div>
                          <div className="col-4">
                            <div className="text-center">
                              <small className="text-slate-400">{t('campaigns.review.avgPromoMargin')}</small>
                              <div className={`h5 mb-0 ${(preview.totals?.avg_promo_margin_percent || 0) >= 10 ? 'text-success' : 'text-warning'}`}>
                                {(preview.totals?.avg_promo_margin_percent || 0).toFixed(1)}%
                              </div>
                            </div>
                          </div>
                          <div className="col-4">
                            <div className="text-center">
                              <small className="text-slate-400">{t('campaigns.review.originalMargin')}</small>
                              <div className="h5 text-slate-300 mb-0">
                                {(preview.totals?.avg_original_margin_percent || 0).toFixed(1)}%
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    {preview.products && preview.products.length > 0 && (
                      <div className="card bg-secondary bg-opacity-25">
                        <div className="card-body">
                          <h6 className="text-white mb-3">{t('campaigns.review.productDetails')}</h6>
                          <div className="table-responsive" style={{ maxHeight: '250px' }}>
                            <table className="table table-sm table-dark mb-0">
                              <thead className="sticky-top bg-dark">
                                <tr>
                                  <th>{t('campaigns.review.product')}</th>
                                  <th className="text-end">{t('campaigns.review.cmv')}</th>
                                  <th className="text-end">{t('campaigns.review.original')}</th>
                                  <th className="text-end">{t('campaigns.review.promo')}</th>
                                  <th className="text-end">{t('campaigns.review.margin')}</th>
                                  <th className="text-center">{t('campaigns.review.status')}</th>
                                </tr>
                              </thead>
                              <tbody>
                                {preview.products.slice(0, 15).map(p => (
                                  <tr key={p.id} className={!p.is_profitable ? 'table-danger' : ''}>
                                    <td>
                                      {p.name}
                                      {p.was_protected && (
                                        <i className="bi bi-shield-check text-info ms-1" title={p.protection_reason}></i>
                                      )}
                                    </td>
                                    <td className="text-end text-slate-400">{currency(p.cmv)}</td>
                                    <td className="text-end text-decoration-line-through text-slate-400">
                                      {currency(p.original_price)}
                                    </td>
                                    <td className="text-end text-success">{currency(p.promotional_price)}</td>
                                    <td className={`text-end ${p.promo_margin_percent >= 10 ? 'text-success' : p.promo_margin_percent >= 0 ? 'text-warning' : 'text-danger'}`}>
                                      {p.promo_margin_percent.toFixed(1)}%
                                    </td>
                                    <td className="text-center">
                                      {p.is_profitable ? (
                                        <span className="badge bg-success">
                                          <i className="bi bi-check-circle"></i>
                                        </span>
                                      ) : (
                                        <span className="badge bg-danger">
                                          <i className="bi bi-exclamation-triangle"></i>
                                        </span>
                                      )}
                                    </td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                            {preview.products.length > 15 && (
                              <small className="text-slate-400">
                                {t('campaigns.review.andMore', { count: preview.products.length - 15 })}
                              </small>
                            )}
                          </div>
                        </div>
                      </div>
                    )}
                  </>
                )}
              </div>
            )}
          </div>

          {/* Footer */}
          <div className="modal-footer border-secondary">
            <button type="button" className="btn btn-secondary" onClick={onClose}>
              {t('common.cancel')}
            </button>
            
            {activeStep > 1 && (
              <button 
                type="button" 
                className="btn btn-outline-primary"
                onClick={() => setActiveStep(prev => prev - 1)}
              >
                <i className="bi bi-arrow-left me-1"></i>
                {t('common.back')}
              </button>
            )}
            
            {activeStep < 3 ? (
              <button 
                type="button" 
                className="btn btn-primary"
                onClick={() => setActiveStep(prev => prev + 1)}
                disabled={!isStepValid}
              >
                {t('common.next')}
                <i className="bi bi-arrow-right ms-1"></i>
              </button>
            ) : (
              <button 
                type="button" 
                className="btn btn-success"
                onClick={handleSubmit}
                disabled={loading || !isStepValid}
              >
                {loading ? (
                  <>
                    <span className="spinner-border spinner-border-sm me-1"></span>
                    {t('common.saving')}
                  </>
                ) : (
                  <>
                    <i className="bi bi-check-lg me-1"></i>
                    {campaign?.id ? t('common.save') : t('campaigns.create')}
                  </>
                )}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default CampaignModal;
