'use strict';

document.addEventListener('DOMContentLoaded', () => {
  const table = document.querySelector('.datatables-permissions');
  const addRoleModal = document.getElementById('addRoleModal');
  const editRoleModal = document.getElementById('editRoleModal');
  const selectAllPermissions = document.getElementById('selectAllPermissions');
  const permissionCheckboxes = document.querySelectorAll('.role-permission');
  const editRoleForm = document.getElementById('editRoleForm');
  const editRoleName = document.getElementById('edit_name');
  const editRoleId = document.getElementById('edit_role_id');

  if (table) {
    new DataTable(table, {
      order: [[1, 'asc']],
      columnDefs: [
        {
          className: 'control',
          orderable: false,
          searchable: false,
          targets: 0,
          render: function () {
            return '';
          }
        },
        {
          targets: 1,
          visible: false,
          searchable: false
        },
        {
          targets: -1,
          orderable: false,
          searchable: false
        }
      ],
      layout: {
        topStart: {
          rowClass: 'row m-3 my-0 justify-content-between',
          features: [
            {
              pageLength: {
                menu: [10, 25, 50, 100],
                text: 'Mostrar _MENU_'
              }
            }
          ]
        },
        topEnd: {
          features: [
            {
              search: {
                placeholder: 'Buscar roles',
                text: '_INPUT_'
              }
            }
          ]
        },
        bottomStart: {
          rowClass: 'row mx-3 justify-content-between',
          features: ['info']
        },
        bottomEnd: 'paging'
      },
      language: {
        paginate: {
          next: '<i class="icon-base ti tabler-chevron-right scaleX-n1-rtl icon-18px"></i>',
          previous: '<i class="icon-base ti tabler-chevron-left scaleX-n1-rtl icon-18px"></i>',
          first: '<i class="icon-base ti tabler-chevrons-left scaleX-n1-rtl icon-18px"></i>',
          last: '<i class="icon-base ti tabler-chevrons-right scaleX-n1-rtl icon-18px"></i>'
        }
      }
    });

    setTimeout(() => {
      const mappings = [
        { selector: '.dt-search', add: 'me-4' },
        { selector: '.dt-search .form-control', remove: 'form-control-sm' },
        { selector: '.dt-length', add: 'mb-0 mb-md-5' },
        { selector: '.dt-length .form-select', remove: 'form-select-sm' },
        {
          selector: '.dt-layout-end',
          remove: 'justify-content-between',
          add: 'justify-content-md-between justify-content-center d-flex flex-wrap gap-md-4 mb-sm-0 mb-6 mt-0'
        },
        { 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 (selectAllPermissions) {
    selectAllPermissions.addEventListener('change', () => {
      permissionCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllPermissions.checked;
      });
    });

    permissionCheckboxes.forEach(checkbox => {
      checkbox.addEventListener('change', () => {
        const allChecked = Array.from(permissionCheckboxes).every(item => item.checked);
        selectAllPermissions.checked = allChecked;
      });
    });

    const initialAllChecked = Array.from(permissionCheckboxes).every(item => item.checked);
    selectAllPermissions.checked = initialAllChecked;
  }

  document.addEventListener('click', event => {
    const editButton = event.target.closest('.btn-edit-role');

    if (!editButton || !editRoleForm || !editRoleName || !editRoleId) {
      return;
    }

    const roleId = editButton.dataset.roleId;
    const roleName = editButton.dataset.roleName;
    const updateUrl = editButton.dataset.updateUrl;
    const permissions = JSON.parse(editButton.dataset.permissions || '{}');

    editRoleForm.action = updateUrl;
    editRoleName.value = roleName || '';
    editRoleId.value = roleId || '';

    document.querySelectorAll('.edit-role-permission').forEach(item => {
      item.checked = false;
    });

    Object.keys(permissions).forEach(module => {
      const modulePermissions = permissions[module] || {};
      Object.keys(modulePermissions).forEach(action => {
        const checkbox = document.getElementById(`edit_perm_${module}_${action}`);
        if (checkbox) {
          checkbox.checked = !!modulePermissions[action];
        }
      });
    });

    if (editRoleModal) {
      const modal = bootstrap.Modal.getOrCreateInstance(editRoleModal);
      modal.show();
    }
  });

  document.addEventListener('click', event => {
    const deleteButton = event.target.closest('.btn-delete-role');

    if (!deleteButton) {
      return;
    }

    const formId = deleteButton.dataset.formId;
    const members = Number(deleteButton.dataset.members || 0);
    const form = document.getElementById(formId);

    if (!form) {
      return;
    }

    if (members > 0) {
      Swal.fire({
        icon: 'warning',
        title: 'No se puede eliminar',
        text: 'Este rol tiene usuarios asignados.',
        confirmButtonText: 'Aceptar',
        customClass: {
          confirmButton: 'btn btn-primary'
        },
        buttonsStyling: false
      });

      return;
    }

    Swal.fire({
      title: '¿Eliminar rol?',
      text: 'Esta acción no se puede deshacer.',
      icon: 'warning',
      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();
      }
    });
  });

  if (addRoleModal && window.__openRoleModal) {
    const modal = bootstrap.Modal.getOrCreateInstance(addRoleModal);
    modal.show();
  }

  if (editRoleModal && window.__openEditRoleModal) {
    const roleId = window.__editRoleOldId;
    const button = roleId ? document.querySelector(`.btn-edit-role[data-role-id="${roleId}"]`) : null;

    if (button) {
      button.click();
    } else {
      const modal = bootstrap.Modal.getOrCreateInstance(editRoleModal);
      modal.show();
    }
  }
});
