'use strict';

document.addEventListener('DOMContentLoaded', () => {
  const triggerSelector = '.btn-manage-price-rules';
  const modalEl = document.getElementById('priceRulesModal');
  if (!modalEl) return;

  const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
  const listBody = document.getElementById('priceRulesTableBody');
  const targetLabel = document.getElementById('priceRulesTargetLabel');
  const createForm = document.getElementById('priceRuleCreateForm');
  const formTitle = document.getElementById('priceRuleFormTitle');
  const submitBtn = document.getElementById('priceRuleSubmitBtn');
  const cancelEditBtn = document.getElementById('priceRuleCancelEditBtn');
  const typeInput = document.getElementById('priceRuleType');
  const weekdayWrap = document.getElementById('priceRuleWeekdayWrap');
  const rangeWrap = document.getElementById('priceRuleRangeWrap');
  const specificWrap = document.getElementById('priceRuleSpecificWrap');
  const packageWrap = document.getElementById('priceRulePackageWrap');
  const applyItemsOverrideInput = document.getElementById('priceRuleApplyItemsOverride');
  const giftIncludedCards = document.getElementById('priceRuleGiftIncludedCards');
  const giftAdditionalCards = document.getElementById('priceRuleGiftAdditionalCards');
  const artistCards = document.getElementById('priceRuleArtistCards');
  const otherCostCards = document.getElementById('priceRuleOtherCostCards');
  const calculatedInternalInput = document.getElementById('priceRuleCalculatedInternal');
  const calculatedCustomerInput = document.getElementById('priceRuleCalculatedCustomer');
  const calculatedCommissionInput = document.getElementById('priceRuleCalculatedCommission');

  const endpoints = {
    index: modalEl.dataset.indexUrl || '',
    store: modalEl.dataset.storeUrl || '',
    updateBase: modalEl.dataset.updateBaseUrl || '',
    destroyBase: modalEl.dataset.destroyBaseUrl || ''
  };

  const csrf = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

  const notyf = typeof Notyf !== 'undefined'
    ? new Notyf({
        duration: 3200,
        dismissible: true,
        position: { x: 'right', y: 'top' },
        types: [
          { type: 'success', className: 'notyf__success', icon: { className: 'icon-base ti tabler-check' } },
          { type: 'error', className: 'notyf__error', icon: { className: 'icon-base ti tabler-alert-circle' } }
        ]
      })
    : null;

  const notify = (type, message) => {
    if (notyf) {
      notyf.open({ type, message });
      return;
    }
    if (type === 'error') {
      console.error(message);
    } else {
      console.log(message);
    }
  };

  let currentTarget = { type: '', id: '' };
  let currentRules = [];
  let editingRuleId = null;
  let deleteRuleId = null;
  const packageCatalog = window.packageRuleCatalogOptions || { gifts: [], artists: [], otherCosts: [] };

  const normalizeMoney = value => {
    if (value === null || value === undefined || value === '') return '-';
    const parsed = Number(value || 0);
    if (Number.isNaN(parsed)) return '-';
    return `$${parsed.toLocaleString('es-CO')}`;
  };

  const parsePrice = value => {
    const parsed = Number(value || 0);
    return Number.isFinite(parsed) ? parsed : 0;
  };

  const ruleTypeLabel = type => {
    switch (type) {
      case 'always': return 'Siempre';
      case 'weekday': return 'Días de semana';
      case 'date_range': return 'Rango de fechas';
      case 'specific_date': return 'Fecha puntual';
      default: return type;
    }
  };

  const weekdaysLabel = values => {
    const map = { 1: 'Lun', 2: 'Mar', 3: 'Mié', 4: 'Jue', 5: 'Vie', 6: 'Sáb', 7: 'Dom' };
    const items = (values || []).map(v => map[Number(v)]).filter(Boolean);
    return items.length ? items.join(', ') : '-';
  };

  const showTypeFields = () => {
    const type = typeInput?.value || 'always';
    if (weekdayWrap) weekdayWrap.classList.toggle('d-none', type !== 'weekday');
    if (rangeWrap) rangeWrap.classList.toggle('d-none', type !== 'date_range');
    if (specificWrap) specificWrap.classList.toggle('d-none', type !== 'specific_date');
  };

  const resetRuleForm = () => {
    editingRuleId = null;
    createForm?.reset();
    if (formTitle) formTitle.textContent = 'Crear regla';
    if (submitBtn) submitBtn.innerHTML = '<i class="icon-base ti tabler-plus icon-xs me-1"></i>Guardar regla';
    cancelEditBtn?.classList.add('d-none');
    if (applyItemsOverrideInput) applyItemsOverrideInput.checked = false;
    showTypeFields();
    syncPackageOverrideVisibility();
    updateCalculatedSummary();
  };

  const renderRules = rules => {
    if (!listBody) return;

    currentRules = Array.isArray(rules) ? rules : [];

    if (!Array.isArray(rules) || rules.length === 0) {
      listBody.innerHTML = '<tr><td colspan="9" class="text-center text-body-secondary py-4">Sin reglas de precio.</td></tr>';
      return;
    }

    listBody.innerHTML = rules
      .map(rule => {
        const detail = rule.rule_type === 'weekday'
          ? weekdaysLabel(rule.weekday_values)
          : (rule.rule_type === 'date_range'
            ? `${rule.start_date || '-'} a ${rule.end_date || '-'}`
            : (rule.rule_type === 'specific_date' ? (rule.specific_date || '-') : 'Todo el año'));

        const hasComposition = Boolean(rule.has_item_overrides);
        return `
          <tr>
            <td class="fw-medium">${rule.name}</td>
            <td>${ruleTypeLabel(rule.rule_type)}</td>
            <td>${detail}</td>
            <td>${normalizeMoney(rule.internal_cost)}</td>
            <td>${normalizeMoney(rule.customer_price)}</td>
            <td>${hasComposition ? '<span class="badge bg-label-info">Especial</span>' : '<span class="text-body-secondary">Base</span>'}</td>
            <td>${rule.priority}</td>
            <td><span class="badge ${rule.is_active ? 'bg-label-success' : 'bg-label-secondary'}">${rule.is_active ? 'Activa' : 'Inactiva'}</span></td>
            <td>
              <button type="button" class="btn btn-sm btn-label-primary btn-edit-price-rule" data-id="${rule.id}" title="Editar">
                <i class="icon-base ti tabler-pencil"></i>
              </button>
              <button type="button" class="btn btn-sm btn-label-danger btn-delete-price-rule" data-id="${rule.id}" title="Eliminar">
                <i class="icon-base ti tabler-trash"></i>
              </button>
            </td>
          </tr>`;
      })
      .join('');
  };

  const renderCards = (container, options, fieldName) => {
    if (!container) return;
    const list = Array.isArray(options) ? options : [];
    if (list.length === 0) {
      container.innerHTML = '<div class="col-12 text-body-secondary small">Sin elementos disponibles.</div>';
      return;
    }

    container.innerHTML = list.map(option => `
      <div class="col-md-6">
        <label class="border rounded p-2 d-flex align-items-start gap-2 w-100">
          <input
            class="form-check-input mt-1 price-rule-item-checkbox"
            type="checkbox"
            name="${fieldName}[]"
            value="${option.code}"
            data-internal-cost="${parsePrice(option.internal_cost)}"
            data-customer-price="${parsePrice(option.base_price)}">
          <span>
            <strong>${option.name}</strong>
            ${option.internal_cost !== undefined || option.base_price !== undefined
              ? `<br><small class="text-body-secondary">Interno: ${normalizeMoney(option.internal_cost)} | Cliente: ${normalizeMoney(option.base_price)}</small>`
              : ''}
          </span>
        </label>
      </div>
    `).join('');
  };

  const setItemCheckboxesDisabled = disabled => {
    modalEl.querySelectorAll('.price-rule-item-checkbox').forEach(input => {
      input.disabled = disabled;
      if (disabled) {
        input.checked = false;
      }
    });
    updateCalculatedSummary();
  };

  const fillPackageSelection = (fieldName, values) => {
    const valueSet = new Set(Array.isArray(values) ? values : []);
    modalEl.querySelectorAll(`.price-rule-item-checkbox[name="${fieldName}[]"]`).forEach(input => {
      input.checked = valueSet.has(input.value);
    });
  };

  const startEditingRule = rule => {
    if (!rule || !createForm) return;

    editingRuleId = Number(rule.id);
    if (formTitle) formTitle.textContent = 'Editar regla';
    if (submitBtn) submitBtn.innerHTML = '<i class="icon-base ti tabler-device-floppy icon-xs me-1"></i>Guardar cambios';
    cancelEditBtn?.classList.remove('d-none');

    createForm.querySelector('[name="name"]').value = rule.name || '';
    createForm.querySelector('[name="rule_type"]').value = rule.rule_type || 'always';
    createForm.querySelector('[name="priority"]').value = rule.priority || 100;
    createForm.querySelector('[name="is_active"]').value = rule.is_active ? '1' : '0';
    createForm.querySelector('[name="internal_cost"]').value = rule.internal_cost ?? '';
    createForm.querySelector('[name="customer_price"]').value = rule.customer_price ?? '';
    createForm.querySelector('[name="start_date"]').value = rule.start_date || '';
    createForm.querySelector('[name="end_date"]').value = rule.end_date || '';
    createForm.querySelector('[name="specific_date"]').value = rule.specific_date || '';

    createForm.querySelectorAll('[name="weekday_values[]"]').forEach(input => {
      const inputValue = Number(input.value);
      input.checked = Array.isArray(rule.weekday_values) && rule.weekday_values.map(Number).includes(inputValue);
    });

    if (applyItemsOverrideInput) {
      applyItemsOverrideInput.checked = Boolean(rule.has_item_overrides);
    }
    fillPackageSelection('gift_codes', rule.gift_codes || []);
    fillPackageSelection('artist_codes', rule.artist_codes || []);
    fillPackageSelection('other_cost_codes', rule.other_cost_codes || []);

    showTypeFields();
    syncPackageOverrideVisibility();
    updateCalculatedSummary();
    createForm.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const updateCalculatedSummary = () => {
    const selected = Array.from(modalEl.querySelectorAll('.price-rule-item-checkbox:checked'));
    const internalTotal = selected.reduce((sum, item) => sum + parsePrice(item.dataset.internalCost), 0);
    const customerTotal = selected.reduce((sum, item) => sum + parsePrice(item.dataset.customerPrice), 0);
    const commissionTotal = customerTotal - internalTotal;

    if (calculatedInternalInput) calculatedInternalInput.value = normalizeMoney(internalTotal);
    if (calculatedCustomerInput) calculatedCustomerInput.value = normalizeMoney(customerTotal);
    if (calculatedCommissionInput) calculatedCommissionInput.value = normalizeMoney(commissionTotal);
  };

  const syncPackageOverrideVisibility = () => {
    if (!packageWrap) return;
    const isPackage = currentTarget.type === 'package';
    packageWrap.classList.toggle('d-none', !isPackage);
    if (!isPackage) {
      if (applyItemsOverrideInput) applyItemsOverrideInput.checked = false;
      setItemCheckboxesDisabled(true);
      return;
    }
    setItemCheckboxesDisabled(!(applyItemsOverrideInput && applyItemsOverrideInput.checked));
  };

  const loadRules = async () => {
    if (!currentTarget.type || !currentTarget.id || !endpoints.index) return;

    const params = new URLSearchParams({
      target_type: currentTarget.type,
      target_id: String(currentTarget.id)
    });

    const response = await fetch(`${endpoints.index}?${params.toString()}`, {
      headers: { Accept: 'application/json' }
    });

    const data = await response.json();
    if (!response.ok || !data.success) {
      throw new Error(data.message || 'No se pudieron cargar las reglas.');
    }

    renderRules(data.rules || []);
  };

  document.querySelectorAll(triggerSelector).forEach(button => {
    button.addEventListener('click', async () => {
      currentTarget = {
        type: button.dataset.targetType || '',
        id: button.dataset.targetId || ''
      };

      if (targetLabel) {
        targetLabel.textContent = button.dataset.targetName || 'Ítem';
      }

      resetRuleForm();
      renderCards(
        giftIncludedCards,
        (packageCatalog.gifts || []).filter(item => item.type === 'included'),
        'gift_codes'
      );
      renderCards(
        giftAdditionalCards,
        (packageCatalog.gifts || []).filter(item => item.type === 'additional'),
        'gift_codes'
      );
      renderCards(artistCards, packageCatalog.artists || [], 'artist_codes');
      renderCards(otherCostCards, packageCatalog.otherCosts || [], 'other_cost_codes');
      syncPackageOverrideVisibility();
      updateCalculatedSummary();
      showTypeFields();
      modal.show();

      try {
        await loadRules();
      } catch (error) {
        notify('error', error.message || 'Error cargando reglas.');
      }
    });
  });

  typeInput?.addEventListener('change', showTypeFields);
  applyItemsOverrideInput?.addEventListener('change', syncPackageOverrideVisibility);
  cancelEditBtn?.addEventListener('click', resetRuleForm);
  showTypeFields();
  modalEl.addEventListener('change', event => {
    if (event.target && event.target.classList && event.target.classList.contains('price-rule-item-checkbox')) {
      updateCalculatedSummary();
    }
  });

  createForm?.addEventListener('submit', async event => {
    event.preventDefault();
    if (!endpoints.store || !currentTarget.type || !currentTarget.id) return;

    const formData = new FormData(createForm);
    formData.append('target_type', currentTarget.type);
    formData.append('target_id', currentTarget.id);

    const method = editingRuleId ? 'PUT' : 'POST';
    const submitUrl = editingRuleId ? `${endpoints.updateBase}/${editingRuleId}` : endpoints.store;

    try {
      const response = await fetch(submitUrl, {
        method,
        headers: {
          'X-CSRF-TOKEN': csrf,
          Accept: 'application/json'
        },
        body: formData
      });

      const data = await response.json();
      if (!response.ok || !data.success) {
        if (data?.errors && typeof data.errors === 'object') {
          const firstKey = Object.keys(data.errors)[0];
          throw new Error(data.errors[firstKey]?.[0] || 'No se pudo crear la regla.');
        }
        throw new Error(data.message || 'No se pudo crear la regla.');
      }

      notify('success', data.message || (editingRuleId ? 'Regla actualizada.' : 'Regla creada.'));
      resetRuleForm();
      await loadRules();
    } catch (error) {
      notify('error', error.message || 'Error guardando regla.');
    }
  });

  const deleteModalEl = document.getElementById('deletePriceRuleModal');
  const deleteModal = deleteModalEl ? bootstrap.Modal.getOrCreateInstance(deleteModalEl) : null;
  const confirmDeleteBtn = document.getElementById('confirmDeletePriceRuleBtn');

  listBody?.addEventListener('click', async event => {
    const editButton = event.target.closest('.btn-edit-price-rule');
    if (editButton?.dataset.id) {
      const ruleId = Number(editButton.dataset.id);
      const rule = currentRules.find(item => Number(item.id) === ruleId);
      if (rule) {
        startEditingRule(rule);
      }
      return;
    }

    const button = event.target.closest('.btn-delete-price-rule');
    if (!button || !button.dataset.id || !endpoints.destroyBase) return;

    deleteRuleId = Number(button.dataset.id);
    deleteModal?.show();
  });

  confirmDeleteBtn?.addEventListener('click', async () => {
    if (!deleteRuleId || !endpoints.destroyBase) return;
    const deletedId = Number(deleteRuleId);

    try {
      const response = await fetch(`${endpoints.destroyBase}/${deletedId}`, {
        method: 'DELETE',
        headers: {
          'X-CSRF-TOKEN': csrf,
          Accept: 'application/json'
        }
      });

      const data = await response.json();
      if (!response.ok || !data.success) {
        throw new Error(data.message || 'No se pudo eliminar la regla.');
      }

      notify('success', data.message || 'Regla eliminada.');
      deleteModal?.hide();
      deleteRuleId = null;
      if (editingRuleId && Number(editingRuleId) === deletedId) {
        resetRuleForm();
      }
      await loadRules();
    } catch (error) {
      notify('error', error.message || 'Error eliminando regla.');
    }
  });
});
