'use strict';

document.addEventListener('DOMContentLoaded', () => {
  const table = document.querySelector('.datatables-customers');
  const addCustomerForm = document.getElementById('eCommerceCustomerAddForm');
  const offcanvasElement = document.getElementById('offcanvasEcommerceCustomerAdd');
  const notyf = new Notyf({
    duration: 3200,
    dismissible: true,
    ripple: 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' } }
    ]
  });

  const pageData = window.__ownerClientsData || {};

  if (!table) return;

  if (pageData.toast?.success) {
    notyf.open({ type: 'success', message: pageData.toast.success });
  }
  if (Array.isArray(pageData.toast?.errors) && pageData.toast.errors.length) {
    pageData.toast.errors.forEach(error => notyf.open({ type: 'error', message: error, duration: 5000 }));
  }

  const dt = 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 cliente',
              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 cliente</span></span>',
                className: 'btn btn-primary',
                action: function () {
                  if (offcanvasElement) bootstrap.Offcanvas.getOrCreateInstance(offcanvasElement).show();
                }
              }
            ]
          }
        ]
      },
      bottomStart: {
        rowClass: 'row mx-3 justify-content-between',
        features: ['info']
      },
      bottomEnd: 'paging'
    },
    language: {
      search: '',
      searchPlaceholder: 'Buscar cliente',
      lengthMenu: '_MENU_'
    },
    columnDefs: [
      { targets: [6], orderable: false, searchable: false }
    ]
  });

  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 (window.jQuery && window.jQuery.fn.select2) {
    window.jQuery('#ecommerce-customer-add-country').select2({
      dropdownParent: window.jQuery(offcanvasElement),
      minimumResultsForSearch: 8,
      width: '100%'
    });
  }

  if (addCustomerForm && window.FormValidation) {
    FormValidation.formValidation(addCustomerForm, {
      fields: {
        mariachi_group_id: { validators: { notEmpty: { message: 'Selecciona el grupo musical.' } } },
        name: { validators: { notEmpty: { message: 'Ingresa el nombre.' } } },
        email: {
          validators: {
            emailAddress: { message: 'Correo no válido.' }
          }
        }
      },
      plugins: {
        trigger: new FormValidation.plugins.Trigger(),
        bootstrap5: new FormValidation.plugins.Bootstrap5({
          eleValidClass: '',
          rowSelector: '.form-control-validation'
        }),
        submitButton: new FormValidation.plugins.SubmitButton(),
        autoFocus: new FormValidation.plugins.AutoFocus()
      }
    });
  }

  if (pageData.openAddModal && offcanvasElement) {
    bootstrap.Offcanvas.getOrCreateInstance(offcanvasElement).show();
  }

  table.addEventListener('click', event => {
    const deactivateBtn = event.target.closest('.btn-deactivate-customer');
    if (!deactivateBtn) return;

    const form = document.getElementById(deactivateBtn.dataset.formId || '');
    if (!form) return;

    Swal.fire({
      title: '¿Desactivar cliente?',
      text: `Se desactivará \"${deactivateBtn.dataset.name || 'este cliente'}\".`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Sí, desactivar',
      cancelButtonText: 'Cancelar',
      customClass: {
        confirmButton: 'btn btn-danger me-2',
        cancelButton: 'btn btn-label-secondary'
      },
      buttonsStyling: false
    }).then(result => {
      if (result.isConfirmed) form.submit();
    });
  });
});
