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

const CampaignsTab = ({ sheets }) => {
  const { t } = useTranslation();
  const { currency, date: formatDate } = useFormatters();
  
  const [campaigns, setCampaigns] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [presets, setPresets] = useState({});
  const [modalOpen, setModalOpen] = useState(false);
  const [editingCampaign, setEditingCampaign] = useState(null);
  const [statusFilter, setStatusFilter] = useState('all');
  const [confirmModal, setConfirmModal] = useState({ show: false, campaign: null });

  // Carregar dados
  const loadData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [campaignsData, presetsData] = await Promise.all([
        campaignService.getAll(statusFilter !== 'all' ? { status: statusFilter } : {}),
        campaignService.getPresets(),
      ]);
      setCampaigns(campaignsData);
      setPresets(presetsData);
    } catch (err) {
      console.error('Error loading campaigns:', err);
      setError(err.response?.data?.message || t('common.error'));
    } finally {
      setLoading(false);
    }
  }, [t, statusFilter]);

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

  const handleCreate = () => {
    setEditingCampaign(null);
    setModalOpen(true);
  };

  const handleEdit = (campaign) => {
    setEditingCampaign(campaign);
    setModalOpen(true);
  };

  const handleDuplicate = async (campaign) => {
    try {
      const duplicated = await campaignService.duplicate(campaign.id);
      setCampaigns(prev => [duplicated, ...prev]);
    } catch (err) {
      setError(err.response?.data?.message || t('common.error'));
    }
  };

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

  const executeDelete = async () => {
    const campaign = confirmModal.campaign;
    setConfirmModal({ show: false, campaign: null });
    try {
      await campaignService.delete(campaign.id);
      setCampaigns(prev => prev.filter(c => c.id !== campaign.id));
    } catch (err) {
      setError(err.response?.data?.message || t('common.error'));
    }
  };

  const handleSaved = (campaign) => {
    if (editingCampaign) {
      setCampaigns(prev => prev.map(c => c.id === campaign.id ? campaign : c));
    } else {
      setCampaigns(prev => [campaign, ...prev]);
    }
    setModalOpen(false);
    setEditingCampaign(null);
  };

  const getStatusBadge = (campaign) => {
    const statusConfig = {
      active: { class: 'bg-success', icon: 'bi-check-circle', label: t('campaigns.status.active') },
      scheduled: { class: 'bg-info', icon: 'bi-clock', label: t('campaigns.status.scheduled') },
      ended: { class: 'bg-secondary', icon: 'bi-x-circle', label: t('campaigns.status.ended') },
      inactive: { class: 'bg-warning', icon: 'bi-pause-circle', label: t('campaigns.status.inactive') },
    };
    const config = statusConfig[campaign.status] || statusConfig.inactive;
    return (
      <span className={`badge ${config.class} d-flex align-items-center gap-1`}>
        <i className={`bi ${config.icon}`}></i>
        {config.label}
      </span>
    );
  };

  const getDiscountDisplay = (campaign) => {
    switch (campaign.discount_type) {
      case 'percentage':
        return `-${parseFloat(campaign.discount_value).toFixed(0)}%`;
      case 'fixed':
        return `-${currency(campaign.discount_value)}`;
      case 'price_override':
        return currency(campaign.discount_value);
      default:
        return '-';
    }
  };

  // Quick preset buttons
  const quickPresets = [
    { key: 'black_friday', icon: 'bi-tag-fill', color: '#000000' },
    { key: 'cyber_monday', icon: 'bi-laptop', color: '#0ea5e9' },
    { key: 'christmas', icon: 'bi-gift', color: '#dc2626' },
    { key: 'flash_sale', icon: 'bi-lightning-charge-fill', color: '#eab308' },
  ];

  return (
    <div className="campaigns-tab">
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div className="d-flex align-items-center gap-3">
          <h5 className="mb-0 text-white">
            <i className="bi bi-megaphone me-2"></i>
            {t('campaigns.title')}
          </h5>
          <span className="badge bg-primary">{campaigns.length}</span>
        </div>
        <div className="d-flex gap-2">
          {/* Status Filter */}
          <select
            className="form-select form-select-sm bg-dark text-white"
            style={{ width: '150px', borderColor: 'rgba(255,255,255,0.2)' }}
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
          >
            <option value="all">{t('campaigns.filter.all')}</option>
            <option value="active">{t('campaigns.filter.active')}</option>
            <option value="scheduled">{t('campaigns.filter.scheduled')}</option>
            <option value="ended">{t('campaigns.filter.ended')}</option>
            <option value="inactive">{t('campaigns.filter.inactive')}</option>
          </select>
          <button className="btn btn-primary btn-sm" onClick={handleCreate}>
            <i className="bi bi-plus-lg me-1"></i>
            {t('campaigns.new')}
          </button>
        </div>
      </div>

      {/* Error */}
      {error && (
        <div className="alert alert-danger d-flex align-items-center mb-4">
          <i className="bi bi-exclamation-triangle me-2"></i>
          {error}
          <button className="btn-close ms-auto" onClick={() => setError(null)}></button>
        </div>
      )}

      {/* Quick Presets */}
      <div className="card bg-dark border-secondary mb-4">
        <div className="card-body">
          <h6 className="text-white mb-3">
            <i className="bi bi-lightning me-2"></i>
            {t('campaigns.quickStart')}
          </h6>
          <div className="d-flex flex-wrap gap-2">
            {quickPresets.map(preset => (
              <button
                key={preset.key}
                className="btn btn-outline-light btn-sm d-flex align-items-center gap-2"
                onClick={() => {
                  setEditingCampaign({ preset: preset.key });
                  setModalOpen(true);
                }}
                style={{ borderColor: preset.color, color: preset.color }}
              >
                <i className={`bi ${preset.icon}`}></i>
                {presets[preset.key]?.name || preset.key}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Campaigns List */}
      {loading ? (
        <div className="text-center py-5">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
        </div>
      ) : campaigns.length === 0 ? (
        <div className="text-center py-5">
          <i className="bi bi-megaphone text-slate-500" style={{ fontSize: '3rem' }}></i>
          <p className="text-slate-400 mt-3">{t('campaigns.empty')}</p>
          <button className="btn btn-primary" onClick={handleCreate}>
            <i className="bi bi-plus-lg me-1"></i>
            {t('campaigns.createFirst')}
          </button>
        </div>
      ) : (
        <div className="row g-3">
          {campaigns.map(campaign => (
            <div key={campaign.id} className="col-md-6 col-lg-4">
              <div 
                className="card bg-dark h-100"
                style={{ 
                  borderColor: campaign.badge_color || 'rgba(255,255,255,0.1)',
                  borderWidth: campaign.is_currently_active ? '2px' : '1px',
                }}
              >
                <div className="card-header d-flex justify-content-between align-items-center py-2">
                  <div className="d-flex align-items-center gap-2">
                    {campaign.show_discount_badge && (
                      <span 
                        className="badge"
                        style={{ 
                          backgroundColor: campaign.badge_color || '#ef4444',
                          color: '#fff',
                        }}
                      >
                        {campaign.badge_text || getDiscountDisplay(campaign)}
                      </span>
                    )}
                    {getStatusBadge(campaign)}
                  </div>
                  <div className="dropdown">
                    <button 
                      className="btn btn-sm text-slate-400"
                      data-bs-toggle="dropdown"
                    >
                      <i className="bi bi-three-dots-vertical"></i>
                    </button>
                    <ul className="dropdown-menu dropdown-menu-end dropdown-menu-dark">
                      <li>
                        <button className="dropdown-item" onClick={() => handleEdit(campaign)}>
                          <i className="bi bi-pencil me-2"></i>
                          {t('common.edit')}
                        </button>
                      </li>
                      <li>
                        <button className="dropdown-item" onClick={() => handleDuplicate(campaign)}>
                          <i className="bi bi-copy me-2"></i>
                          {t('common.duplicate')}
                        </button>
                      </li>
                      <li><hr className="dropdown-divider" /></li>
                      <li>
                        <button 
                          className="dropdown-item text-danger"
                          onClick={() => handleDelete(campaign)}
                        >
                          <i className="bi bi-trash me-2"></i>
                          {t('common.delete')}
                        </button>
                      </li>
                    </ul>
                  </div>
                </div>
                <div className="card-body">
                  <h6 className="text-white mb-2">{campaign.name}</h6>
                  {campaign.description && (
                    <p className="text-slate-400 small mb-3">{campaign.description}</p>
                  )}
                  
                  {/* Desconto */}
                  <div className="d-flex justify-content-between align-items-center mb-2">
                    <span className="text-slate-400 small">{t('campaigns.discount')}:</span>
                    <span className="text-white fw-bold">{getDiscountDisplay(campaign)}</span>
                  </div>
                  
                  {/* Período */}
                  <div className="d-flex justify-content-between align-items-center mb-2">
                    <span className="text-slate-400 small">{t('campaigns.period')}:</span>
                    <span className="text-white small">
                      {formatDate(campaign.start_date)} - {formatDate(campaign.end_date)}
                    </span>
                  </div>
                  
                  {/* Produtos */}
                  <div className="d-flex justify-content-between align-items-center">
                    <span className="text-slate-400 small">{t('campaigns.products')}:</span>
                    <span className="text-white">
                      {campaign.products_count || 0} 
                      {campaign.apply_to_all_products && (
                        <span className="badge bg-info ms-1">{t('campaigns.allProducts')}</span>
                      )}
                    </span>
                  </div>
                  
                  {/* Dias restantes */}
                  {campaign.is_currently_active && campaign.days_remaining !== null && (
                    <div className="mt-3 pt-3 border-top border-secondary">
                      <div className="d-flex justify-content-between align-items-center">
                        <span className="text-slate-400 small">{t('campaigns.daysRemaining')}:</span>
                        <span className={`fw-bold ${campaign.days_remaining <= 3 ? 'text-warning' : 'text-success'}`}>
                          {campaign.days_remaining} {t('campaigns.days')}
                        </span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal */}
      <CampaignModal
        isOpen={modalOpen}
        onClose={() => {
          setModalOpen(false);
          setEditingCampaign(null);
        }}
        onSaved={handleSaved}
        campaign={editingCampaign}
        presets={presets}
        sheets={sheets}
      />

      {/* Confirm Modal */}
      <ConfirmModal
        show={confirmModal.show}
        message={confirmModal.campaign ? t('campaigns.deleteConfirm', { name: confirmModal.campaign.name }) : ''}
        variant="danger"
        onConfirm={executeDelete}
        onCancel={() => setConfirmModal({ show: false, campaign: null })}
      />
    </div>
  );
};

export default CampaignsTab;
