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

const ServiceSheetModal = ({ sheet, settings, onSave, onClose }) => {
  const { t } = useTranslation();
  const { currency } = useFormatters();
  const isEditing = !!sheet;
  
  const [formData, setFormData] = useState({
    name: '',
    code: '',
    description: '',
    category: '',
    business_setting_id: '',
    duration_minutes: '30',
    is_active: true,
    // Strategic pricing fields
    competitor_price: '',
    min_price: '',
    max_price: '',
    premium_multiplier: '1.00',
    pricing_strategy: 'neutral',
    psychological_pricing: false,
    target_margin: '',
  });
  
  const [items, setItems] = useState([]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);
  const [showStrategicPricing, setShowStrategicPricing] = useState(false);

  const itemTypes = [
    { value: 'supply', label: t('business.services.itemTypes.supply') },
    { value: 'consumable', label: t('business.services.itemTypes.consumable') },
    { value: 'material', label: t('business.services.itemTypes.material') },
    { value: 'equipment_usage', label: t('business.services.itemTypes.equipmentUsage') },
    { value: 'other', label: t('business.services.itemTypes.other') },
  ];

  useEffect(() => {
    if (sheet) {
      setFormData({
        name: sheet.name || '',
        code: sheet.code || '',
        description: sheet.description || '',
        category: sheet.category || '',
        business_setting_id: sheet.business_setting_id || '',
        duration_minutes: sheet.duration_minutes || '30',
        is_active: sheet.is_active ?? true,
        // Strategic pricing fields
        competitor_price: sheet.competitor_price || '',
        min_price: sheet.min_price || '',
        max_price: sheet.max_price || '',
        premium_multiplier: sheet.premium_multiplier || '1.00',
        pricing_strategy: sheet.pricing_strategy || 'neutral',
        psychological_pricing: sheet.psychological_pricing ?? false,
        target_margin: sheet.target_margin || '',
      });
      setItems(sheet.items?.map(item => ({
        id: item.id,
        name: item.name,
        type: item.type,
        unit_cost: item.unit_cost,
        quantity_used: item.quantity_used || 1,
        unit: item.unit || '',
      })) || []);
      // Show strategic pricing if any field is set
      if (sheet.competitor_price || sheet.min_price || sheet.max_price || 
          sheet.target_margin || sheet.pricing_strategy !== 'neutral') {
        setShowStrategicPricing(true);
      }
    } else if (settings.length > 0) {
      // Auto-select first service-enabled setting
      setFormData(prev => ({
        ...prev,
        business_setting_id: settings[0].id.toString(),
      }));
    }
  }, [sheet, settings]);

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

  const handleItemChange = (index, field, value) => {
    setItems(prev => prev.map((item, i) => 
      i === index ? { ...item, [field]: value } : item
    ));
  };

  const addItem = () => {
    setItems(prev => [...prev, {
      name: '',
      type: 'supply',
      unit_cost: '',
      quantity_used: 1,
      unit: '',
    }]);
  };

  const removeItem = (index) => {
    setItems(prev => prev.filter((_, i) => i !== index));
  };

  // Calcular CSV total (Custo do Serviço Vendido)
  const calculateCsv = () => {
    return items.reduce((sum, item) => {
      const cost = parseFloat(item.unit_cost) || 0;
      const quantity = parseFloat(item.quantity_used) || 1;
      return sum + (cost * quantity);
    }, 0);
  };

  // Calcular preview del precio
  const calculatePreview = () => {
    if (!formData.business_setting_id) return null;
    const setting = settings.find(s => s.id === parseInt(formData.business_setting_id));
    if (!setting) return null;
    
    const duration = parseFloat(formData.duration_minutes) || 30;
    const csv = calculateCsv();
    
    // Gasto fijo por minuto
    const employees = parseInt(setting.employees_count) || 1;
    const hoursPerDay = parseFloat(setting.hours_per_day) || 8;
    const workingDays = parseInt(setting.working_days_per_month) || 22;
    const productivity = parseFloat(setting.productivity_rate) || 80;
    const productiveHours = employees * hoursPerDay * workingDays * (productivity / 100);
    const fixedExpenses = parseFloat(setting.fixed_expenses) || 0;
    const fixedCostPerHour = productiveHours > 0 ? fixedExpenses / productiveHours : 0;
    const fixedCostPerMinute = fixedCostPerHour / 60;
    
    // Porção de custo fixo proporcional ao tempo
    const fixedCostPortion = fixedCostPerMinute * duration;
    
    // Preço base = (Gasto Fixo + CSV) × Markup
    const markup = parseFloat(setting.markup_factor) || 1;
    const priceWithoutTax = (fixedCostPortion + csv) * markup;
    
    // Se B2C, adiciona IVA
    let finalPrice = priceWithoutTax;
    let vatAmount = 0;
    if (setting.price_includes_tax) {
      const vatRate = parseFloat(setting.vat_rate) || 0;
      finalPrice = priceWithoutTax * (1 + vatRate / 100);
      vatAmount = finalPrice - priceWithoutTax;
    }
    
    return {
      duration,
      csv,
      fixedCostPortion,
      baseCost: fixedCostPortion + csv,
      markup,
      priceWithoutTax,
      vatRate: setting.price_includes_tax ? parseFloat(setting.vat_rate) : 0,
      vatAmount,
      finalPrice,
      fixedCostPerHour,
      currency: setting.currency,
    };
  };

  const preview = calculatePreview();

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

    // Validar itens
    const validItems = items.filter(item => item.name && item.unit_cost);
    
    try {
      const dataToSend = {
        ...formData,
        business_setting_id: parseInt(formData.business_setting_id),
        duration_minutes: parseFloat(formData.duration_minutes) || 30,
        competitor_price: formData.competitor_price ? parseFloat(formData.competitor_price) : null,
        min_price: formData.min_price ? parseFloat(formData.min_price) : null,
        max_price: formData.max_price ? parseFloat(formData.max_price) : null,
        premium_multiplier: parseFloat(formData.premium_multiplier) || 1,
        target_margin: formData.target_margin ? parseFloat(formData.target_margin) : null,
        items: validItems.map(item => ({
          name: item.name,
          type: item.type,
          unit_cost: parseFloat(item.unit_cost) || 0,
          quantity_used: parseFloat(item.quantity_used) || 1,
          unit: item.unit || null,
        })),
      };

      let result;
      if (isEditing) {
        // Para edição, atualizar ficha e depois itens
        result = await serviceSheetService.update(sheet.id, {
          name: formData.name,
          code: formData.code,
          description: formData.description,
          category: formData.category,
          business_setting_id: dataToSend.business_setting_id,
          duration_minutes: dataToSend.duration_minutes,
          is_active: formData.is_active,
          competitor_price: dataToSend.competitor_price,
          min_price: dataToSend.min_price,
          max_price: dataToSend.max_price,
          premium_multiplier: dataToSend.premium_multiplier,
          pricing_strategy: formData.pricing_strategy,
          psychological_pricing: formData.psychological_pricing,
          target_margin: dataToSend.target_margin,
        });
        
        // Gerenciar itens
        const existingIds = items.filter(i => i.id).map(i => i.id);
        const itemsToRemove = sheet.items?.filter(i => !existingIds.includes(i.id)) || [];
        
        for (const item of itemsToRemove) {
          await serviceSheetService.removeItem(sheet.id, item.id);
        }
        
        for (const item of validItems) {
          if (item.id) {
            await serviceSheetService.updateItem(sheet.id, item.id, {
              name: item.name,
              type: item.type,
              unit_cost: parseFloat(item.unit_cost) || 0,
              quantity_used: parseFloat(item.quantity_used) || 1,
              unit: item.unit || null,
            });
          } else {
            await serviceSheetService.addItem(sheet.id, {
              name: item.name,
              type: item.type,
              unit_cost: parseFloat(item.unit_cost) || 0,
              quantity_used: parseFloat(item.quantity_used) || 1,
              unit: item.unit || null,
            });
          }
        }
        
        // Reload to get updated data
        result = await serviceSheetService.get(sheet.id);
      } else {
        result = await serviceSheetService.create(dataToSend);
      }
      
      onSave(result);
    } catch (err) {
      setError(err.response?.data?.message || err.response?.data?.errors || t('common.error'));
    } finally {
      setSaving(false);
    }
  };

  const selectedSetting = settings.find(s => s.id === parseInt(formData.business_setting_id));

  return (
    <div className="modal show d-block" style={{ background: 'rgba(0,0,0,0.8)' }}>
      <div className="modal-dialog modal-xl 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-person-workspace me-2 text-success"></i>
              {isEditing ? t('business.services.edit') : t('business.services.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">
                {/* Información básica */}
                <div className="col-md-6">
                  <label className="form-label text-slate-400">{t('business.services.name')}</label>
                  <input
                    type="text"
                    className="form-control bg-dark text-white border-secondary"
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    placeholder={t('business.services.namePlaceholder')}
                    required
                  />
                </div>
                <div className="col-md-3">
                  <label className="form-label text-slate-400">{t('business.services.code')}</label>
                  <input
                    type="text"
                    className="form-control bg-dark text-white border-secondary"
                    name="code"
                    value={formData.code}
                    onChange={handleChange}
                    placeholder={t('business.services.codePlaceholder')}
                  />
                </div>
                <div className="col-md-3">
                  <label className="form-label text-slate-400">{t('business.services.duration')}</label>
                  <div className="input-group">
                    <input
                      type="number"
                      min="1"
                      className="form-control bg-dark text-white border-secondary"
                      name="duration_minutes"
                      value={formData.duration_minutes}
                      onChange={handleChange}
                      required
                    />
                    <span className="input-group-text bg-dark text-slate-400 border-secondary">{t('business.common.minuteShort')}</span>
                  </div>
                </div>
                
                <div className="col-md-6">
                  <label className="form-label text-slate-400">{t('business.services.category')}</label>
                  <input
                    type="text"
                    className="form-control bg-dark text-white border-secondary"
                    name="category"
                    value={formData.category}
                    onChange={handleChange}
                    placeholder={t('business.services.categoryPlaceholder')}
                  />
                </div>
                <div className="col-md-6">
                  <label className="form-label text-slate-400">{t('business.services.businessSetting')}</label>
                  <select
                    className="form-select bg-dark text-white border-secondary"
                    name="business_setting_id"
                    value={formData.business_setting_id}
                    onChange={handleChange}
                    required
                  >
                    <option value="">{t('business.services.selectSetting')}</option>
                    {settings.map(s => (
                      <option key={s.id} value={s.id}>
                        {s.name} ({s.currency}) - {s.markup_factor}x
                      </option>
                    ))}
                  </select>
                </div>
                
                <div className="col-12">
                  <label className="form-label text-slate-400">{t('business.services.description')}</label>
                  <textarea
                    className="form-control bg-dark text-white border-secondary"
                    name="description"
                    value={formData.description}
                    onChange={handleChange}
                    rows={2}
                    placeholder={t('business.services.descriptionPlaceholder')}
                  />
                </div>

                {/* Insumos / CSV */}
                <div className="col-12">
                  <hr className="border-secondary my-2" />
                  <div className="d-flex justify-content-between align-items-center mb-3">
                    <h6 className="text-slate-400 small mb-0">
                      <i className="bi bi-box-seam me-2"></i>
                      {t('business.services.supplies')} (CSV)
                    </h6>
                    <button type="button" className="btn btn-sm btn-outline-success" onClick={addItem}>
                      <i className="bi bi-plus-lg me-1"></i>
                      {t('business.services.addSupply')}
                    </button>
                  </div>

                  {items.length === 0 ? (
                    <div className="text-center py-4" style={{ background: '#0f172a', borderRadius: '8px' }}>
                      <i className="bi bi-inbox text-slate-500 fs-1 mb-2 d-block"></i>
                      <p className="text-slate-400 small mb-2">{t('business.services.noSupplies')}</p>
                      <button type="button" className="btn btn-sm btn-success" onClick={addItem}>
                        <i className="bi bi-plus-lg me-1"></i>
                        {t('business.services.addFirst')}
                      </button>
                    </div>
                  ) : (
                    <div className="table-responsive">
                      <table className="table table-dark table-sm mb-0" style={{ background: '#0f172a' }}>
                        <thead>
                          <tr className="text-slate-400 small">
                            <th style={{ width: '35%' }}>{t('business.services.supplyName')}</th>
                            <th style={{ width: '20%' }}>{t('business.services.type')}</th>
                            <th style={{ width: '15%' }}>{t('business.services.unitCost')}</th>
                            <th style={{ width: '15%' }}>{t('business.services.quantity')}</th>
                            <th style={{ width: '10%' }}>{t('business.services.total')}</th>
                            <th style={{ width: '5%' }}></th>
                          </tr>
                        </thead>
                        <tbody>
                          {items.map((item, index) => (
                            <tr key={index}>
                              <td>
                                <input
                                  type="text"
                                  className="form-control form-control-sm bg-dark text-white border-secondary"
                                  value={item.name}
                                  onChange={(e) => handleItemChange(index, 'name', e.target.value)}
                                  placeholder={t('business.services.supplyPlaceholder')}
                                />
                              </td>
                              <td>
                                <select
                                  className="form-select form-select-sm bg-dark text-white border-secondary"
                                  value={item.type}
                                  onChange={(e) => handleItemChange(index, 'type', e.target.value)}
                                >
                                  {itemTypes.map(type => (
                                    <option key={type.value} value={type.value}>{type.label}</option>
                                  ))}
                                </select>
                              </td>
                              <td>
                                <input
                                  type="number"
                                  step="0.01"
                                  className="form-control form-control-sm bg-dark text-white border-secondary"
                                  value={item.unit_cost}
                                  onChange={(e) => handleItemChange(index, 'unit_cost', e.target.value)}
                                  placeholder="0.00"
                                />
                              </td>
                              <td>
                                <div className="input-group input-group-sm">
                                  <input
                                    type="number"
                                    step="0.01"
                                    min="0.01"
                                    className="form-control bg-dark text-white border-secondary"
                                    value={item.quantity_used}
                                    onChange={(e) => handleItemChange(index, 'quantity_used', e.target.value)}
                                  />
                                  <input
                                    type="text"
                                    className="form-control bg-dark text-white border-secondary"
                                    value={item.unit}
                                    onChange={(e) => handleItemChange(index, 'unit', e.target.value)}
                                    placeholder={t('business.services.unitPlaceholder')}
                                    style={{ maxWidth: '50px' }}
                                  />
                                </div>
                              </td>
                              <td className="text-success text-end">
                                {currency((parseFloat(item.unit_cost) || 0) * (parseFloat(item.quantity_used) || 1), selectedSetting?.currency || 'EUR')}
                              </td>
                              <td>
                                <button
                                  type="button"
                                  className="btn btn-sm btn-outline-danger border-0"
                                  onClick={() => removeItem(index)}
                                >
                                  <i className="bi bi-trash"></i>
                                </button>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                        <tfoot>
                          <tr className="border-top border-secondary">
                            <td colSpan="4" className="text-end text-slate-400 fw-bold">
                              {t('business.services.totalCsv')}:
                            </td>
                            <td className="text-danger fw-bold text-end">
                              {currency(calculateCsv(), selectedSetting?.currency || 'EUR')}
                            </td>
                            <td></td>
                          </tr>
                        </tfoot>
                      </table>
                    </div>
                  )}
                </div>

                {/* Preview de precio */}
                {preview && (
                  <div className="col-12">
                    <hr className="border-secondary my-2" />
                    <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-calculator me-2"></i>
                          {t('business.services.pricePreview')}
                        </h6>
                        
                        <div className="row g-3 small">
                          <div className="col-md-3">
                            <div className="p-2 rounded text-center" style={{ background: 'rgba(59, 130, 246, 0.2)' }}>
                              <small className="text-slate-400 d-block">{t('business.services.fixedCostPortion')}</small>
                              <span className="text-info fw-bold">
                                {currency(preview.fixedCostPortion, preview.currency)}
                              </span>
                              <small className="text-slate-500 d-block">
                                ({currency(preview.fixedCostPerHour, preview.currency)}/h × {preview.duration}min)
                              </small>
                            </div>
                          </div>
                          <div className="col-md-2">
                            <div className="p-2 rounded text-center" style={{ background: 'rgba(239, 68, 68, 0.2)' }}>
                              <small className="text-slate-400 d-block">CSV</small>
                              <span className="text-danger fw-bold">
                                {currency(preview.csv, preview.currency)}
                              </span>
                            </div>
                          </div>
                          <div className="col-md-2">
                            <div className="p-2 rounded text-center" style={{ background: 'rgba(168, 85, 247, 0.2)' }}>
                              <small className="text-slate-400 d-block">{t('business.services.baseCost')}</small>
                              <span className="text-purple fw-bold" style={{ color: '#a855f7' }}>
                                {currency(preview.baseCost, preview.currency)}
                              </span>
                            </div>
                          </div>
                          <div className="col-md-2">
                            <div className="p-2 rounded text-center" style={{ background: 'rgba(251, 191, 36, 0.2)' }}>
                              <small className="text-slate-400 d-block">{t('business.common.timesMarkup')}</small>
                              <span className="text-warning fw-bold">{preview.markup.toFixed(2)}x</span>
                            </div>
                          </div>
                          <div className="col-md-3">
                            <div className="p-2 rounded text-center" style={{ background: 'rgba(16, 185, 129, 0.2)' }}>
                              <small className="text-slate-400 d-block">{t('business.services.finalPrice')}</small>
                              <span className="text-success fw-bold fs-5">
                                {currency(preview.finalPrice, preview.currency)}
                              </span>
                              {preview.vatRate > 0 && (
                                <small className="text-slate-500 d-block">
                                  ({t('business.services.includesVat')} {preview.vatRate}%)
                                </small>
                              )}
                            </div>
                          </div>
                        </div>
                        
                        <div className="mt-3 text-center">
                          <small className="text-slate-400">
                            <i className="bi bi-info-circle me-1"></i>
                            {t('business.services.formula')}: ({currency(preview.fixedCostPortion, preview.currency)} + {currency(preview.csv, preview.currency)}) × {preview.markup.toFixed(2)} 
                            {preview.vatRate > 0 && ` × ${(1 + preview.vatRate/100).toFixed(2)}`}
                            {' '}= <strong className="text-success">{currency(preview.finalPrice, preview.currency)}</strong>
                          </small>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* Strategic Pricing Toggle */}
                <div className="col-12">
                  <button
                    type="button"
                    className="btn btn-sm btn-outline-secondary w-100"
                    onClick={() => setShowStrategicPricing(!showStrategicPricing)}
                  >
                    <i className={`bi ${showStrategicPricing ? 'bi-chevron-up' : 'bi-chevron-down'} me-2`}></i>
                    {t('business.services.strategicPricing')}
                  </button>
                </div>

                {/* Strategic Pricing Fields */}
                {showStrategicPricing && (
                  <>
                    <div className="col-md-4">
                      <label className="form-label text-slate-400">{t('business.services.competitorPrice')}</label>
                      <input
                        type="number"
                        step="0.01"
                        className="form-control bg-dark text-white border-secondary"
                        name="competitor_price"
                        value={formData.competitor_price}
                        onChange={handleChange}
                        placeholder="0.00"
                      />
                    </div>
                    <div className="col-md-4">
                      <label className="form-label text-slate-400">{t('business.services.minPrice')}</label>
                      <input
                        type="number"
                        step="0.01"
                        className="form-control bg-dark text-white border-secondary"
                        name="min_price"
                        value={formData.min_price}
                        onChange={handleChange}
                        placeholder="0.00"
                      />
                    </div>
                    <div className="col-md-4">
                      <label className="form-label text-slate-400">{t('business.services.maxPrice')}</label>
                      <input
                        type="number"
                        step="0.01"
                        className="form-control bg-dark text-white border-secondary"
                        name="max_price"
                        value={formData.max_price}
                        onChange={handleChange}
                        placeholder="0.00"
                      />
                    </div>
                    <div className="col-md-4">
                      <label className="form-label text-slate-400">{t('business.services.strategy')}</label>
                      <select
                        className="form-select bg-dark text-white border-secondary"
                        name="pricing_strategy"
                        value={formData.pricing_strategy}
                        onChange={handleChange}
                      >
                        <option value="aggressive">{t('business.services.strategyAggressive')}</option>
                        <option value="neutral">{t('business.services.strategyNeutral')}</option>
                        <option value="premium">{t('business.services.strategyPremium')}</option>
                      </select>
                    </div>
                    <div className="col-md-4">
                      <label className="form-label text-slate-400">{t('business.services.premiumMultiplier')}</label>
                      <input
                        type="number"
                        step="0.01"
                        min="0.5"
                        max="3"
                        className="form-control bg-dark text-white border-secondary"
                        name="premium_multiplier"
                        value={formData.premium_multiplier}
                        onChange={handleChange}
                      />
                    </div>
                    <div className="col-md-4">
                      <label className="form-label text-slate-400">{t('business.services.targetMargin')}</label>
                      <div className="input-group">
                        <input
                          type="number"
                          step="0.1"
                          className="form-control bg-dark text-white border-secondary"
                          name="target_margin"
                          value={formData.target_margin}
                          onChange={handleChange}
                          placeholder="30"
                        />
                        <span className="input-group-text bg-dark text-slate-400 border-secondary">%</span>
                      </div>
                    </div>
                    <div className="col-12">
                      <div className="form-check">
                        <input
                          type="checkbox"
                          className="form-check-input"
                          id="psychological_pricing"
                          name="psychological_pricing"
                          checked={formData.psychological_pricing}
                          onChange={handleChange}
                        />
                        <label className="form-check-label text-slate-400" htmlFor="psychological_pricing">
                          {t('business.services.psychologicalPricing')}
                          <small className="d-block text-slate-500">{t('business.services.psychologicalPricingHelp')}</small>
                        </label>
                      </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.services.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-success" disabled={saving}>
                {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 ServiceSheetModal;
