'use strict';

document.addEventListener('DOMContentLoaded', () => {
  const table = document.querySelector('.datatables-owner-mariachi-groups');
  const createOffcanvasEl = document.getElementById('offcanvasCreateMariachiGroup');
  const editOffcanvasEl = document.getElementById('offcanvasEditMariachiGroup');
  const editForm = document.getElementById('editMariachiGroupForm');
  const openCreateBtn = document.getElementById('btnOpenCreateMariachiGroup');
  const pageData = window.__mariachiGroupsPageData || {};

  const notyf = new Notyf({
    duration: 3500,
    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' } }
    ]
  });

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

  if (openCreateBtn && createOffcanvasEl) {
    openCreateBtn.addEventListener('click', () => {
      bootstrap.Offcanvas.getOrCreateInstance(createOffcanvasEl).show();
    });
  }

  if (table) {
    new DataTable(table, {
      order: [[5, 'asc'], [1, 'asc']],
      pageLength: 10,
      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 grupo', 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>'
        }
      },
      columnDefs: [
        { targets: [0], visible: false },
        { targets: [6], orderable: false, searchable: false }
      ]
    });

    setTimeout(() => {
      const mappings = [
        { 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-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));
        });
      });
    }, 120);

    table.addEventListener('click', event => {
      const editButton = event.target.closest('.btn-edit-mariachi-group');
      if (editButton && editForm && editOffcanvasEl) {
        editForm.action = editButton.dataset.updateUrl || '#';
        const fields = [
          ['edit_mariachi_group_id', 'id'],
          ['edit_group_name', 'name'],
          ['edit_group_description', 'description'],
          ['edit_group_sort_order', 'sortOrder'],
          ['edit_group_is_active', 'isActive'],
          ['edit_group_is_default', 'isDefault']
        ];

        fields.forEach(([elementId, dataKey]) => {
          const field = document.getElementById(elementId);
          if (field) field.value = editButton.dataset[dataKey] ?? '';
        });

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

      const toggleButton = event.target.closest('.btn-toggle-mariachi-group');
      if (!toggleButton) return;

      const formId = toggleButton.dataset.formId;
      const form = formId ? document.getElementById(formId) : null;
      if (!form) return;
      const nextState = toggleButton.dataset.nextState || 'inactivar';
      const isActivating = nextState === 'activar';

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

  if (createOffcanvasEl && pageData.openCreateModal) {
    bootstrap.Offcanvas.getOrCreateInstance(createOffcanvasEl).show();
  }

  if (editOffcanvasEl && pageData.openEditModal) {
    const oldEditButton = pageData.editGroupId
      ? document.querySelector(`.btn-edit-mariachi-group[data-id="${pageData.editGroupId}"]`)
      : null;

    if (oldEditButton) {
      oldEditButton.click();
    } else {
      bootstrap.Offcanvas.getOrCreateInstance(editOffcanvasEl).show();
    }
  }
});
