'use strict';

document.addEventListener('DOMContentLoaded', () => {
  const table = document.querySelector('.datatables-owner-artists');
  const createOffcanvasEl = document.getElementById('offcanvasCreateArtist');
  const editOffcanvasEl = document.getElementById('offcanvasEditArtist');
  const editForm = document.getElementById('editArtistForm');
  const openCreateBtn = document.getElementById('btnOpenCreateArtist');

  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' } }
    ]
  });

  const pageData = window.__artistPageData || {};

  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: [[6, '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 ítem', 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: [7], orderable: false, searchable: false }
      ],
      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 aux = document.createElement('div');
              aux.innerHTML = item;
              return (aux.textContent || aux.innerText || '').replace(/\s+/g, ' ').trim();
            })
          );

          [...values].filter(Boolean).sort((a, b) => a.localeCompare(b, 'es')).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, '.artist_type_filter', 'ArtistTypeFilter', 'Filtrar por tipo');
        createFilter(5, '.artist_status_filter', 'ArtistStatusFilter', 'Filtrar por estado');
        createFilter(6, '.artist_order_filter', 'ArtistOrderFilter', 'Filtrar por orden');
      }
    });

    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-artist');
      if (editButton && editForm && editOffcanvasEl) {
        editForm.action = editButton.dataset.updateUrl || '#';

        const editItemId = document.getElementById('edit_item_id');
        const editName = document.getElementById('edit_name');
        const editType = document.getElementById('edit_type');
        const editInternalCost = document.getElementById('edit_internal_cost');
        const editPrice = document.getElementById('edit_base_price');
        const editSort = document.getElementById('edit_sort_order');
        const editActive = document.getElementById('edit_is_active');

        if (editItemId) editItemId.value = editButton.dataset.id || '';
        if (editName) editName.value = editButton.dataset.name || '';
        if (editType) editType.value = editButton.dataset.type || 'included';
        if (editInternalCost) editInternalCost.value = editButton.dataset.internalCost || 0;
        if (editPrice) editPrice.value = editButton.dataset.basePrice || 0;
        if (editSort) editSort.value = editButton.dataset.sortOrder || 100;
        if (editActive) editActive.value = editButton.dataset.isActive || '1';

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

      const deleteButton = event.target.closest('.btn-delete-artist');
      if (deleteButton) {
        const form = document.getElementById(deleteButton.dataset.formId || '');
        if (!form) return;

        Swal.fire({
          title: '¿Eliminar ítem?',
          text: `Se eliminará \"${deleteButton.dataset.name || 'este ítem'}\".`,
          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 (createOffcanvasEl && pageData.openCreateModal) {
    bootstrap.Offcanvas.getOrCreateInstance(createOffcanvasEl).show();
  }

  if (editOffcanvasEl && pageData.openEditModal) {
    const oldEditButton = pageData.editItemId ? document.querySelector(`.btn-edit-artist[data-id="${pageData.editItemId}"]`) : null;
    if (oldEditButton) {
      oldEditButton.click();
    } else {
      bootstrap.Offcanvas.getOrCreateInstance(editOffcanvasEl).show();
    }
  }
});
