'use strict';

document.addEventListener('DOMContentLoaded', () => {
  const table = document.querySelector('.datatables-organizations');
  const addOrganizationForm = document.getElementById('addNewOrganizationForm');
  const offcanvasElement = document.getElementById('offcanvasAddOrganization');
  const ownerUserSelect = document.getElementById('owner_user_id');
  const editOffcanvasElement = document.getElementById('offcanvasEditMariachiGroup');
  const editForm = document.getElementById('editMariachiGroupForm');
  const editOwnerUserSelect = document.getElementById('edit_owner_user_id');
  const mergeModalElement = document.getElementById('mergeMariachiGroupModal');
  const mergeForm = document.getElementById('mergeMariachiGroupForm');
  const mergeTargetSelect = document.getElementById('merge_target_group_id');
  const mergeSourceName = document.getElementById('mergeSourceGroupName');
  const phoneInput = document.getElementById('contact_phone');
  const countryCodeSelect = document.getElementById('contact_country_code');
  const notyf = new Notyf({
    duration: 3000,
    dismissible: true,
    ripple: true,
    position: { x: 'right', y: 'top' },
    types: [
      { type: 'info', className: 'notyf__info', icon: { className: 'icon-base ti tabler-info-circle' } },
      { type: 'warning', className: 'notyf__warning', icon: { className: 'icon-base ti tabler-alert-triangle' } },
      { type: 'success', className: 'notyf__success', icon: { className: 'icon-base ti tabler-check' } },
      { type: 'error', className: 'notyf__error', icon: { className: 'icon-base ti tabler-x' } }
    ]
  });

  if (!table) {
    return;
  }

  const toastData = window.__toastData || {};

  if (toastData.success) {
    notyf.open({
      type: 'success',
      message: toastData.success
    });
  }

  if (Array.isArray(toastData.errors) && toastData.errors.length) {
    toastData.errors.forEach(error => {
      notyf.open({
        type: 'error',
        message: error,
        duration: 4500
      });
    });
  }

  if (ownerUserSelect && window.jQuery && window.jQuery.fn.select2) {
    window.jQuery(ownerUserSelect).select2({
      placeholder: ownerUserSelect.dataset.placeholder || 'Selecciona un usuario',
      allowClear: ownerUserSelect.dataset.allowClear === 'true',
      dropdownParent: offcanvasElement
    });
  }

  if (editOwnerUserSelect && window.jQuery && window.jQuery.fn.select2) {
    window.jQuery(editOwnerUserSelect).select2({
      placeholder: editOwnerUserSelect.dataset.placeholder || 'Selecciona un usuario',
      allowClear: editOwnerUserSelect.dataset.allowClear === 'true',
      dropdownParent: editOffcanvasElement
    });
  }

  if (countryCodeSelect && phoneInput && phoneInput.value.trim().startsWith('+')) {
    const codeMatch = phoneInput.value.trim().match(/^(\+\d+)/);
    if (codeMatch && codeMatch[1]) {
      countryCodeSelect.value = codeMatch[1];
      phoneInput.value = phoneInput.value.trim().replace(/^(\+\d+)\s*/, '');
    }
  }

  new DataTable(table, {
    order: [[0, 'desc']],
    pageLength: 10,
    layout: {
      topStart: {
        rowClass: 'row m-3 my-0 justify-content-between',
        features: [
          {
            pageLength: {
              menu: [10, 25, 50, 100],
              text: '_MENU_'
            }
          }
        ]
      },
      topEnd: {
        features: [
          {
            search: {
              placeholder: 'Buscar grupo mariachi',
              text: '_INPUT_'
            }
          },
          {
            buttons: [
              {
                extend: 'collection',
                className: 'btn btn-label-secondary dropdown-toggle me-2',
                text: '<span class="d-flex align-items-center gap-2"><i class="icon-base ti tabler-upload icon-xs"></i><span class="d-none d-sm-inline-block">Exportar</span></span>',
                buttons: ['copy', 'csv', 'excel', 'pdf', 'print']
              },
              {
                text: '<span class="d-flex align-items-center gap-2"><i class="icon-base ti tabler-plus icon-xs"></i><span class="d-none d-sm-inline-block">Nuevo grupo mariachi</span></span>',
                className: 'btn btn-primary',
                action: function () {
                  if (offcanvasElement) {
                    const offcanvas = bootstrap.Offcanvas.getOrCreateInstance(offcanvasElement);
                    offcanvas.show();
                  }
                }
              }
            ]
          }
        ]
      },
      bottomStart: {
        rowClass: 'row mx-3 justify-content-between',
        features: ['info']
      },
      bottomEnd: 'paging'
    },
    language: {
      search: '',
      searchPlaceholder: 'Buscar grupo mariachi',
      lengthMenu: '_MENU_'
    },
    initComplete: function () {
      const api = this.api();

      const createFilter = (columnIndex, containerClass, id, placeholder) => {
        const container = document.querySelector(containerClass);

        if (!container) {
          return;
        }

        const select = document.createElement('select');
        select.id = id;
        select.className = 'form-select text-capitalize';
        select.innerHTML = `<option value="">${placeholder}</option>`;
        container.appendChild(select);

        const values = new Set(
          api
            .column(columnIndex)
            .data()
            .toArray()
            .map(item => {
              const helper = document.createElement('div');
              helper.innerHTML = item;
              return (helper.textContent || helper.innerText || '').replace(/\s+/g, ' ').trim();
            })
        );

        [...values]
          .filter(Boolean)
          .sort()
          .forEach(value => {
            const option = document.createElement('option');
            option.value = value;
            option.textContent = value;
            select.appendChild(option);
          });

        select.addEventListener('change', () => {
          const value = select.value ? `^${select.value}$` : '';
          api.column(columnIndex).search(value, true, false).draw();
        });
      };

      createFilter(5, '.organization_status', 'OrganizationStatus', 'Filtrar por estado');
    }
  });

  setTimeout(() => {
    const mappings = [
      { selector: '.dt-buttons .btn', remove: 'btn-secondary' },
      { selector: '.dt-search .form-control', remove: 'form-control-sm' },
      { selector: '.dt-length .form-select', remove: 'form-select-sm', add: 'ms-0' },
      { selector: '.dt-length', add: 'mb-md-6 mb-0' },
      {
        selector: '.dt-layout-end',
        remove: 'justify-content-between',
        add: 'd-flex gap-md-4 justify-content-md-between justify-content-center gap-2 flex-wrap'
      },
      { selector: '.dt-buttons', add: 'd-flex gap-2 mb-md-0 mb-4' },
      { selector: '.dt-layout-table', remove: 'row mt-2' },
      { selector: '.dt-layout-full', remove: 'col-md col-12', add: 'table-responsive' }
    ];

    mappings.forEach(({ selector, remove, add }) => {
      document.querySelectorAll(selector).forEach(element => {
        if (remove) {
          remove.split(' ').forEach(className => element.classList.remove(className));
        }

        if (add) {
          add.split(' ').forEach(className => element.classList.add(className));
        }
      });
    });
  }, 100);

  if (addOrganizationForm && window.FormValidation) {
    FormValidation.formValidation(addOrganizationForm, {
      fields: {
        name: {
          validators: {
            notEmpty: { message: 'Ingresa el nombre.' }
          }
        },
        is_active: {
          validators: {
            notEmpty: { message: 'Selecciona el estado.' }
          }
        }
      },
      plugins: {
        trigger: new FormValidation.plugins.Trigger(),
        bootstrap5: new FormValidation.plugins.Bootstrap5({
          eleValidClass: '',
          rowSelector: '.form-control-validation'
        }),
        defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
        submitButton: new FormValidation.plugins.SubmitButton(),
        autoFocus: new FormValidation.plugins.AutoFocus()
      }
    });
  }

  if (addOrganizationForm && phoneInput && countryCodeSelect) {
    addOrganizationForm.addEventListener('submit', () => {
      const phone = phoneInput.value.trim();
      if (!phone) {
        return;
      }
      if (phone.startsWith('+')) {
        return;
      }
      phoneInput.value = `${countryCodeSelect.value} ${phone}`;
    });
  }

  if (window.__openAddOrganization && offcanvasElement) {
    const offcanvas = bootstrap.Offcanvas.getOrCreateInstance(offcanvasElement);
    offcanvas.show();
  }

  table.addEventListener('click', event => {
    const editButton = event.target.closest('.btn-edit-mariachi-group');

    if (editButton && editForm && editOffcanvasElement) {
      const id = editButton.dataset.id;
      editForm.action = `/admin/grupos-mariachi/${id}`;
      document.getElementById('edit_name').value = editButton.dataset.name || '';
      document.getElementById('edit_contact_phone').value = editButton.dataset.contact_phone || '';
      document.getElementById('edit_country_code').value = editButton.dataset.country_code || 'CO';
      document.getElementById('edit_city').value = editButton.dataset.city || '';
      document.getElementById('edit_notes').value = editButton.dataset.notes || '';
      document.getElementById('edit_is_active').value = editButton.dataset.is_active || '1';

      if (window.jQuery && window.jQuery.fn.select2 && editOwnerUserSelect) {
        window.jQuery(editOwnerUserSelect).val(editButton.dataset.owner_user_id || '').trigger('change');
      } else if (editOwnerUserSelect) {
        editOwnerUserSelect.value = editButton.dataset.owner_user_id || '';
      }

      bootstrap.Offcanvas.getOrCreateInstance(editOffcanvasElement).show();
      return;
    }

    const mergeButton = event.target.closest('.btn-merge-mariachi-group');
    if (mergeButton && mergeForm && mergeTargetSelect && mergeSourceName && mergeModalElement) {
      const sourceId = parseInt(mergeButton.dataset.sourceId || '0', 10);
      const sourceName = mergeButton.dataset.sourceName || '-';
      const groups = Array.isArray(window.__mariachiGroups) ? window.__mariachiGroups : [];

      mergeForm.action = `/admin/grupos-mariachi/${sourceId}/fusionar`;
      mergeSourceName.textContent = sourceName;
      mergeTargetSelect.innerHTML = '';

      groups
        .filter(group => parseInt(group.id, 10) !== sourceId)
        .forEach(group => {
          const option = document.createElement('option');
          option.value = group.id;
          option.textContent = `${group.name} (#${group.id})`;
          mergeTargetSelect.appendChild(option);
        });

      bootstrap.Modal.getOrCreateInstance(mergeModalElement).show();
      return;
    }

    const deactivateButton = event.target.closest('.btn-deactivate-mariachi-group');
    if (deactivateButton) {
      event.preventDefault();
      const form = deactivateButton.closest('form');
      if (!form) {
        return;
      }
      Swal.fire({
        title: '¿Desactivar grupo?',
        text: 'El grupo se mantendrá para histórico, pero no se podrá usar como activo.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Sí, desactivar',
        cancelButtonText: 'Cancelar',
        customClass: {
          confirmButton: 'btn btn-warning me-2',
          cancelButton: 'btn btn-label-secondary'
        },
        buttonsStyling: false
      }).then(result => {
        if (result.isConfirmed) {
          form.submit();
        }
      });
      return;
    }

    const deleteButton = event.target.closest('.btn-delete-mariachi-group');
    if (deleteButton) {
      event.preventDefault();
      const form = deleteButton.closest('form');
      if (!form) {
        return;
      }
      Swal.fire({
        title: '¿Eliminar definitivamente?',
        text: 'Solo se permite si el grupo no tiene datos vinculados.',
        icon: 'error',
        showCancelButton: true,
        confirmButtonText: 'Sí, eliminar',
        cancelButtonText: 'Cancelar',
        customClass: {
          confirmButton: 'btn btn-danger me-2',
          cancelButton: 'btn btn-label-secondary'
        },
        buttonsStyling: false
      }).then(result => {
        if (result.isConfirmed) {
          form.submit();
        }
      });
    }
  });
});
