'use strict';

document.addEventListener('DOMContentLoaded', () => {
  const table = document.querySelector('.datatables-users');
  const addUserForm = document.getElementById('addNewUserForm');
  const offcanvasElement = document.getElementById('offcanvasAddUser');
  const roleSelect = document.getElementById('role');
  const staffRoleSelect = document.getElementById('staff_role');
  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
      });
    });
  }

  const swalData = window.__swalData || {};

  if (swalData.success) {
    Swal.fire({
      icon: 'success',
      title: 'Listo',
      text: swalData.success,
      confirmButtonText: 'Aceptar',
      customClass: {
        confirmButton: 'btn btn-primary'
      },
      buttonsStyling: false
    });
  }

  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 usuario',
              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 usuario</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 usuario',
      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 container = document.createElement('div');
              container.innerHTML = item;
              return (container.textContent || container.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(2, '.user_role', 'UserRole', 'Filtrar por rol');
      createFilter(5, '.user_status', 'UserStatus', '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 (addUserForm && window.FormValidation) {
    FormValidation.formValidation(addUserForm, {
      fields: {
        name: {
          validators: {
            notEmpty: { message: 'Ingresa el nombre.' }
          }
        },
        email: {
          validators: {
            notEmpty: { message: 'Ingresa el correo.' },
            emailAddress: { message: 'El correo no es válido.' }
          }
        },
        password: {
          validators: {
            notEmpty: { message: 'Ingresa la contraseña.' },
            stringLength: {
              min: 8,
              message: 'La contraseña debe tener al menos 8 caracteres.'
            }
          }
        },
        role: {
          validators: {
            notEmpty: { message: 'Selecciona un rol.' }
          }
        }
      },
      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 (window.__openAddUser && offcanvasElement) {
    const offcanvas = bootstrap.Offcanvas.getOrCreateInstance(offcanvasElement);
    offcanvas.show();
  }

  const syncStaffRoleAvailability = () => {
    if (!roleSelect || !staffRoleSelect) {
      return;
    }

    const isStaff = roleSelect.value === 'STAFF';
    staffRoleSelect.disabled = !isStaff;

    if (!isStaff) {
      staffRoleSelect.value = '';
    }
  };

  if (roleSelect && staffRoleSelect) {
    syncStaffRoleAvailability();
    roleSelect.addEventListener('change', syncStaffRoleAvailability);
  }

  table.addEventListener('click', event => {
    const button = event.target.closest('.btn-deactivate-user');

    if (!button) {
      return;
    }

    event.preventDefault();

    const form = button.closest('form');

    if (!form) {
      return;
    }

    Swal.fire({
      title: '¿Desactivar usuario?',
      text: 'El usuario perderá acceso al sistema.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Sí, desactivar',
      cancelButtonText: 'No, cancelar',
      customClass: {
        confirmButton: 'btn btn-danger me-2',
        cancelButton: 'btn btn-label-secondary'
      },
      buttonsStyling: false
    }).then(result => {
      if (result.isConfirmed) {
        form.submit();
      }
    });
  });
});
