'use strict';

document.addEventListener('DOMContentLoaded', function (e) {
  let borderColor, bodyBg, headingColor;

  borderColor = config.colors.borderColor;
  bodyBg = config.colors.bodyBg;
  headingColor = config.colors.headingColor;

  const dt_provinsi_table = document.querySelector('.datatables-provinsi');
  var select2 = $('.select2');

  if (select2.length) {
    var $this = select2;
    $this.wrap('<div class="position-relative"></div>').select2({
      placeholder: 'Select Country',
      dropdownParent: $this.parent()
    });
  }

  if (dt_provinsi_table) {
      const dt_provinsi = new DataTable(dt_provinsi_table, {
        ajax: provinsiListUrl,
        columns: [
            { data: 'id' },
            { data: 'kode' }, 
            { data: 'nama' }, 
            { data: 'iso' }
        ],
        columnDefs: [
            {
                targets: 0,
                searchable: false,
                orderable: false,
                render: function (data, type, full, meta) {
                    return '<span class="text-truncate d-flex align-items-center text-heading">' + (meta.row + 1) + '</span>';
                }
            },
            {
                targets: 1,
                render: function (data, type, full, meta) {
                    return '<span class="text-truncate d-flex align-items-center text-heading">' + full['kode'] + '</span>';
                }
            },
            {
                targets: 2,
                render: function (data, type, full, meta) {
                    var name = full['nama'], iso = full['iso'];
                    var stateNum = Math.floor(Math.random() * 6);
                    var states = ['success', 'danger', 'warning', 'info', 'primary', 'secondary'];
                    var state = states[stateNum];
                    var initials = (name.match(/\b\w/g) || []).map(char => char.toUpperCase()).join('');
                    
                    return `
                        <div class="d-flex justify-content-start align-items-center user-name">
                            <div class="avatar-wrapper">
                                <div class="avatar avatar-sm me-4">
                                    <span class="avatar-initial rounded-circle bg-label-${state}">${initials}</span>
                                </div>
                            </div>
                            <div class="d-flex flex-column">
                                <span class="fw-medium text-heading text-truncate">${name}</span>
                                <small>${iso}</small>
                            </div>
                        </div>`;
                }
            },
            {
                targets: -1,
                title: 'Actions',
                searchable: false,
                orderable: false,
                render: function (data, type, full, meta) {
                    return `
                        <div class="d-flex align-items-center">
                            <a href="javascript:;" class="btn btn-icon btn-text-secondary waves-effect waves-light rounded-pill view-edit-record" data-id="${full.id}"><i class="ti tabler-edit ti-md"></i></a>
                            <a href="javascript:;" class="btn btn-icon btn-text-secondary waves-effect waves-light rounded-pill delete-record" data-id="${full.id}"><i class="ti tabler-trash ti-md"></i></a>
                            <a href="javascript:;" class="btn btn-icon btn-text-secondary waves-effect waves-light rounded-pill view-record" data-id="${full.id}"><i class="ti tabler-eye ti-md"></i></a>
                        </div>`;
                }
            }
        ],
        order: [[2, 'desc']],
        layout: {
            topStart: {
                rowClass: 'row m-3 my-0 justify-content-between',
                features: [
                    {
                        pageLength: {
                            menu: [10, 25, 50, 100],
                            text: '_MENU_'
                        }
                    }
                ]
            },
            topEnd: {
                features: [
                    {
                        search: {
                            placeholder: 'Search User',
                            text: '_INPUT_'
                        }
                    },
                    {
                        buttons: [
                            {
                                text: '<i class="ti tabler-plus me-0 me-sm-1 ti-xs"></i><span class="d-none d-sm-inline-block">Add New Provinsi</span>',
                                className: 'add-new btn btn-primary ms-2 waves-effect waves-light',
                                attr: {
                                    'data-bs-toggle': 'offcanvas',
                                    'data-bs-target': '#offcanvasAddProvinsi'
                                }
                            }
                        ]
                    }
                ]
            },
            bottomStart: {
                rowClass: 'row mx-3 justify-content-between',
                features: ['info']
            },
            bottomEnd: {
                rowClass: 'row mx-3 justify-content-between',
                features: ['paging']
            }
        }
    });
  }

  setTimeout(() => {
    const elementsToModify = [
      { selector: '.dt-buttons .btn', classToRemove: 'btn-secondary' },
      { selector: '.dt-search .form-control', classToRemove: 'form-control-sm' },
      { selector: '.dt-length .form-select', classToRemove: 'form-select-sm', classToAdd: 'ms-0' },
      { selector: '.dt-length', classToAdd: 'mb-md-6 mb-0' },
      {
        selector: '.dt-layout-end',
        classToRemove: 'justify-content-between',
        classToAdd: 'd-flex gap-md-4 justify-content-md-between justify-content-center gap-2 flex-wrap'
      },
      { selector: '.dt-buttons', classToAdd: 'd-flex gap-4 mb-md-0 mb-4' },
      { selector: '.dt-layout-table', classToRemove: 'row mt-2' },
      { selector: '.dt-layout-full', classToRemove: 'col-md col-12', classToAdd: 'table-responsive' }
    ];

    elementsToModify.forEach(({ selector, classToRemove, classToAdd }) => {
      document.querySelectorAll(selector).forEach(element => {
        if (classToRemove) {
          classToRemove.split(' ').forEach(className => element.classList.remove(className));
        }
        if (classToAdd) {
          classToAdd.split(' ').forEach(className => element.classList.add(className));
        }
      });
    });
  }, 100);

  const fv = FormValidation.formValidation(addNewProvinsiForm, {
    fields: {
      kode: {
        validators: {
          notEmpty: {
            message: 'Silakan masukkan kode provinsi'
          },
          stringLength: {
            min: 2,
            max: 2,
            message: 'Kode provinsi harus terdiri dari 2 karakter'
          }
        }
      },
      nama: {
        validators: {
          notEmpty: {
            message: 'Silakan masukkan nama provinsi'
          }
        }
      },
      iso: {
        validators: {
          notEmpty: {
            message: 'Silakan masukkan kode ISO provinsi'
          },
          regexp: {
            regexp: /^[A-Z]{2}-[A-Z]{2}$/,
            message: 'The value is not a valid ISO code (e.g., ID-AC)'
          }
        }
      }
    },
    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()
    },
  }).on('core.form.valid', function () {
      const form = document.getElementById('addNewProvinsiForm');
      const formData = new FormData(form);
      const offcanvasAdd = bootstrap.Offcanvas.getInstance(document.querySelector('#offcanvasAddProvinsi'));

      $.ajax({
          url: form.action,
          type: 'POST',
          data: $(form).serialize(),
          success: function (response) {
              if (response.status === 'success') {
                  offcanvasAdd.hide();
                  form.reset();
                  Swal.fire({
                      icon: 'success',
                      title: 'Berhasil!',
                      text: response.message,
                      showConfirmButton: false,
                      timer: 2000,
                      customClass: { confirmButton: 'btn btn-primary' }
                  });

                  $('.datatables-provinsi').DataTable().ajax.reload();
              }
          },
          error: function (xhr) {
              let msg = 'Terjadi kesalahan saat menyimpan data.';
              if (xhr.responseJSON && xhr.responseJSON.message) {
                  msg = xhr.responseJSON.message;
              }
              
              Swal.fire({
                  icon: 'error',
                  title: 'Gagal!',
                  text: msg,
                  customClass: { confirmButton: 'btn btn-primary' }
              });
          }
      });
  });
});

$(function () {
  var offcanvasElement = document.getElementById('offcanvasViewProvinsi');
  var offcanvasView = new bootstrap.Offcanvas(offcanvasElement);

  $(document).on('click', '.view-record', function () {
    var provinsiId = $(this).data('id'); 
    
    var $btn = $(this);
    $btn.addClass('disabled');

    $.ajax({
      url: '/provinsi/' + provinsiId,
      type: 'GET',
      success: function (response) {
        $btn.removeClass('disabled');
        
        if (response.status === 'success') {
          var data = response.data;
          $('#view-provinsi-code').val(data.kode);
          $('#view-provinsi-name').val(data.nama);
          $('#view-provinsi-path').val(data.path);
          $('#view-provinsi-iso').val(data.iso);

          offcanvasView.show();
        }
      },
      error: function (xhr) {
        $btn.removeClass('disabled');
        alert('Gagal mengambil data: ' + xhr.statusText);
      }
    });
  });
});

$(function () {
    const offcanvasEl = document.getElementById('offcanvasEditProvinsi');
    const offcanvasEdit = new bootstrap.Offcanvas(offcanvasEl);

    $(document).on('click', '.view-edit-record', function () {
        const id = $(this).data('id');
        
        $.get(`/provinsi/${id}`, function (response) {
            if (response.status === 'success') {
                const d = response.data;
                $('#edit-provinsi-id').val(d.id);
                $('#edit-provinsi-code').val(d.kode);
                $('#edit-provinsi-name').val(d.nama);
                $('#edit-provinsi-path').val(d.path);
                $('#edit-provinsi-iso').val(d.iso);

                offcanvasEdit.show();
            }
        });
    });

    $('#editProvinsiForm').on('submit', function (e) {
      e.preventDefault();
      
      const id = $('#edit-provinsi-id').val();
      const formData = $(this).serialize();

      $.ajax({
          url: `/provinsi/${id}`,
          type: 'PUT',
          data: formData,
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success: function (response) {
              if (response.status === 'success') {
                  offcanvasEdit.hide();
                  
                  Swal.fire({
                      icon: 'success',
                      title: 'Berhasil!',
                      text: response.message,
                      showConfirmButton: false,
                      timer: 1500
                  });
                  
                  $('.datatables-provinsi').DataTable().ajax.reload();
              }
          },
          error: function (xhr) {
              let errorMsg = 'Terjadi kesalahan sistem.';
              if (xhr.responseJSON && xhr.responseJSON.message) {
                  errorMsg = xhr.responseJSON.message;
              }

              Swal.fire({
                  icon: 'error',
                  title: 'Oops...',
                  text: errorMsg,
                  confirmButtonColor: '#7367f0'
              });
          }
      });
  });
});

$(document).on('click', '.delete-record', function () {
    const id = $(this).data('id');
    const name = $(this).closest('tr').find('.fw-medium').text();

    Swal.fire({
        title: 'Apakah Anda yakin?',
        text: `Provinsi "${name}" akan dihapus secara permanen!`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal',
        customClass: {
            confirmButton: 'btn btn-primary me-3',
            cancelButton: 'btn btn-label-secondary'
        },
        buttonsStyling: false
    }).then(function (result) {
        if (result.value) {
            $.ajax({
                url: `/provinsi/${id}`,
                type: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    if (response.status === 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Terhapus!',
                            text: response.message,
                            showConfirmButton: false,
                            timer: 1500
                        });

                        $('.datatables-provinsi').DataTable().ajax.reload();
                    }
                },
                error: function (xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'Terjadi kesalahan saat menghapus data.',
                        customClass: { confirmButton: 'btn btn-primary' }
                    });
                }
            });
        }
    });
});