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

const ServiceSheetsTab = ({ sheets, settings, onCreated, onUpdated, onDeleted }) => {
  const { t } = useTranslation();
  const { currency } = useFormatters();
  
  const [showModal, setShowModal] = useState(false);
  const [editingSheet, setEditingSheet] = useState(null);
  const [deleting, setDeleting] = useState(null);
  const [filter, setFilter] = useState({ category: '', active: 'all' });
  const [confirmModal, setConfirmModal] = useState({ show: false, sheet: null });

  // Filtrar configurações que permitem serviços
  const serviceSettings = settings.filter(s => s.business_type === 'services' || s.business_type === 'both');

  const handleCreate = () => {
    if (serviceSettings.length === 0) {
      alert(t('business.services.noServiceSettings'));
      return;
    }
    setEditingSheet(null);
    setShowModal(true);
  };

  const handleEdit = (sheet) => {
    setEditingSheet(sheet);
    setShowModal(true);
  };

  const handleDuplicate = async (sheet) => {
    try {
      const duplicated = await serviceSheetService.duplicate(sheet.id);
      onCreated(duplicated);
    } catch (err) {
      alert(err.response?.data?.message || t('common.error'));
    }
  };

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

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

  const handleSave = (savedSheet) => {
    if (editingSheet) {
      onUpdated(savedSheet);
    } else {
      onCreated(savedSheet);
    }
    setShowModal(false);
  };

  // Filtrar fichas
  const filteredSheets = sheets.filter(sheet => {
    if (filter.category && sheet.category !== filter.category) return false;
    if (filter.active === 'active' && !sheet.is_active) return false;
    if (filter.active === 'inactive' && sheet.is_active) return false;
    return true;
  });

  // Categorias únicas
  const categories = [...new Set(sheets.map(s => s.category).filter(Boolean))];

  // Formatar duração
  const formatDuration = (minutes) => {
    if (minutes < 60) return `${minutes} ${t('business.common.minuteShort')}`;
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return mins > 0 ? `${hours}${t('business.common.hourShort')} ${mins}${t('business.common.minuteShort')}` : `${hours}${t('business.common.hourShort')}`;
  };

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

      {/* Alerta se no hay configuraciones de servicio */}
      {serviceSettings.length === 0 && (
        <div className="alert alert-warning d-flex align-items-center mb-4">
          <i className="bi bi-exclamation-triangle me-2"></i>
          <div>
            <strong>{t('business.services.noServiceSettings')}</strong>
            <p className="mb-0 small">{t('business.services.createServiceSetting')}</p>
          </div>
        </div>
      )}

      {/* Filtros */}
      {sheets.length > 0 && (
        <div className="row g-3 mb-4">
          <div className="col-auto">
            <select
              className="form-select form-select-sm bg-dark text-white border-secondary"
              value={filter.category}
              onChange={(e) => setFilter(prev => ({ ...prev, category: e.target.value }))}
            >
              <option value="">{t('business.services.allCategories')}</option>
              {categories.map(cat => (
                <option key={cat} value={cat}>{cat}</option>
              ))}
            </select>
          </div>
          <div className="col-auto">
            <select
              className="form-select form-select-sm bg-dark text-white border-secondary"
              value={filter.active}
              onChange={(e) => setFilter(prev => ({ ...prev, active: e.target.value }))}
            >
              <option value="all">{t('common.all')}</option>
              <option value="active">{t('common.active')}</option>
              <option value="inactive">{t('common.inactive')}</option>
            </select>
          </div>
        </div>
      )}

      {/* Empty State */}
      {sheets.length === 0 && serviceSettings.length > 0 ? (
        <div className="card border-0" style={{ background: '#1e293b' }}>
          <div className="card-body text-center py-5">
            <i className="bi bi-person-workspace fs-1 text-slate-500 mb-3 d-block"></i>
            <h5 className="text-white mb-2">{t('business.services.empty')}</h5>
            <p className="text-slate-400 mb-4">{t('business.services.emptyDescription')}</p>
            <button className="btn btn-success" onClick={handleCreate}>
              <i className="bi bi-plus-lg me-2"></i>
              {t('business.services.createFirst')}
            </button>
          </div>
        </div>
      ) : filteredSheets.length === 0 && sheets.length > 0 ? (
        <div className="text-center py-5">
          <i className="bi bi-funnel fs-1 text-slate-500 mb-3 d-block"></i>
          <p className="text-slate-400">{t('business.services.noResults')}</p>
        </div>
      ) : sheets.length > 0 && (
        /* Services Grid */
        <div className="row g-4">
          {filteredSheets.map(sheet => (
            <div key={sheet.id} className="col-12 col-md-6 col-xl-4">
              <div 
                className="card border-0 h-100" 
                style={{ 
                  background: sheet.is_active ? '#1e293b' : '#0f172a',
                  opacity: sheet.is_active ? 1 : 0.7,
                }}
              >
                <div className="card-header border-0 d-flex justify-content-between align-items-start py-3" style={{ background: 'transparent' }}>
                  <div>
                    <h6 className="text-white mb-1">
                      <i className="bi bi-person-workspace me-2 text-success"></i>
                      {sheet.name}
                      {!sheet.is_active && (
                        <span className="badge bg-secondary ms-2">{t('common.inactive')}</span>
                      )}
                    </h6>
                    <div className="d-flex gap-2 align-items-center">
                      {sheet.code && <small className="text-slate-500">{t('business.common.codeLabel')}: {sheet.code}</small>}
                      <span className="badge bg-success bg-opacity-25 text-success">
                        <i className="bi bi-clock me-1"></i>
                        {formatDuration(sheet.duration_minutes)}
                      </span>
                      {sheet.category && (
                        <span className="badge bg-secondary" style={{ fontSize: '10px' }}>{sheet.category}</span>
                      )}
                    </div>
                  </div>
                  <div className="dropdown">
                    <button className="btn btn-sm btn-outline-secondary border-0" data-bs-toggle="dropdown">
                      <i className="bi bi-three-dots-vertical"></i>
                    </button>
                    <ul className="dropdown-menu dropdown-menu-end" style={{ background: '#1e293b' }}>
                      <li>
                        <button className="dropdown-item text-white" onClick={() => handleEdit(sheet)}>
                          <i className="bi bi-pencil me-2"></i>
                          {t('common.edit')}
                        </button>
                      </li>
                      <li>
                        <button className="dropdown-item text-white" onClick={() => handleDuplicate(sheet)}>
                          <i className="bi bi-copy me-2"></i>
                          {t('business.services.duplicate')}
                        </button>
                      </li>
                      <li><hr className="dropdown-divider" style={{ borderColor: 'rgba(255,255,255,0.1)' }} /></li>
                      <li>
                        <button 
                          className="dropdown-item text-danger" 
                          onClick={() => handleDelete(sheet)}
                          disabled={deleting === sheet.id}
                        >
                          <i className="bi bi-trash me-2"></i>
                          {t('common.delete')}
                        </button>
                      </li>
                    </ul>
                  </div>
                </div>
                
                <div className="card-body py-3">
                  {/* Breakdown de custos */}
                  <div className="row g-2 mb-3">
                    <div className="col-4">
                      <div className="p-2 rounded text-center" style={{ background: 'rgba(59, 130, 246, 0.1)' }}>
                        <small className="text-slate-500 d-block">{t('business.services.fixedCost')}</small>
                        <span className="text-info fw-bold small">
                          {currency(sheet.fixed_cost_portion, sheet.business_setting?.currency || 'EUR')}
                        </span>
                      </div>
                    </div>
                    <div className="col-4">
                      <div className="p-2 rounded text-center" style={{ background: 'rgba(239, 68, 68, 0.1)' }}>
                        <small className="text-slate-500 d-block">{t('business.common.csvLabel')}</small>
                        <span className="text-danger fw-bold small">
                          {currency(sheet.total_csv, sheet.business_setting?.currency || 'EUR')}
                        </span>
                      </div>
                    </div>
                    <div className="col-4">
                      <div className="p-2 rounded text-center" style={{ background: 'rgba(16, 185, 129, 0.1)' }}>
                        <small className="text-slate-500 d-block">{t('business.services.price')}</small>
                        <span className="text-success fw-bold">
                          {currency(sheet.calculated_price, sheet.business_setting?.currency || 'EUR')}
                        </span>
                      </div>
                    </div>
                  </div>
                  
                  {/* Margem */}
                  <div className="d-flex justify-content-between align-items-center mb-2">
                    <span className="text-slate-400 small">{t('business.services.margin')}</span>
                    <span className={`fw-bold ${parseFloat(sheet.margin_percentage) >= 20 ? 'text-success' : parseFloat(sheet.margin_percentage) >= 10 ? 'text-warning' : 'text-danger'}`}>
                      {parseFloat(sheet.margin_percentage || 0).toFixed(1)}%
                    </span>
                  </div>
                  
                  {/* Progress bar de margem */}
                  <div className="progress" style={{ height: '4px', background: '#374151' }}>
                    <div 
                      className={`progress-bar ${parseFloat(sheet.margin_percentage) >= 20 ? 'bg-success' : parseFloat(sheet.margin_percentage) >= 10 ? 'bg-warning' : 'bg-danger'}`}
                      style={{ width: `${Math.min(parseFloat(sheet.margin_percentage) || 0, 100)}%` }}
                    ></div>
                  </div>
                  
                  {/* Componentes do serviço */}
                  {sheet.items && sheet.items.length > 0 && (
                    <div className="mt-3">
                      <small className="text-slate-500">{t('business.services.supplies')} ({sheet.items.length})</small>
                      <div className="d-flex flex-wrap gap-1 mt-1">
                        {sheet.items.slice(0, 3).map(item => (
                          <span key={item.id} className="badge bg-dark text-slate-400" style={{ fontSize: '10px' }}>
                            {item.name}
                          </span>
                        ))}
                        {sheet.items.length > 3 && (
                          <span className="badge bg-dark text-slate-400" style={{ fontSize: '10px' }}>
                            {t('business.common.moreItems', { count: sheet.items.length - 3 })}
                          </span>
                        )}
                      </div>
                    </div>
                  )}
                </div>
                
                <div className="card-footer border-0 py-2" style={{ background: 'transparent' }}>
                  <div className="d-flex justify-content-between align-items-center">
                    <small className="text-slate-500">
                      {sheet.business_setting?.name}
                    </small>
                    <button 
                      className="btn btn-sm btn-outline-success"
                      onClick={() => handleEdit(sheet)}
                    >
                      {t('common.edit')}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal */}
      {showModal && (
        <ServiceSheetModal
          sheet={editingSheet}
          settings={serviceSettings}
          onSave={handleSave}
          onClose={() => setShowModal(false)}
        />
      )}

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

export default ServiceSheetsTab;
