<script>
import { ref } from 'vue'
import { editOrderItem } from "@/components/shop/OrdersItems.vue";
import Swal from "sweetalert2";

//

export const showEditOrderItemForm = async (orderItemId, name, price, notes, reference, quantity, allowEdit, afterSubmit = null) => {
  await Swal.fire({
    title: 'Edit Item',
    html: `
      <form id="editOrderItemForm">
        <div class="field">
          <label>Valgt produkt:</label>
          <div class="control">
            <input class="input is-dark" type="text" id="name" value="${name}" disabled/>
          </div>
        </div>
        <div class="field">
          <label>Pris (Pr. stk)</label>
          <div class="control">
            <input class="input is-dark" type="number" id="price" value="${price}" />
          </div>
        </div>
        <div class="field">
          <label>Noter (Sendes på faktura til kunde)</label>
          <div class="control">
            <textarea class="textarea is-dark" type="text" id="notes">${notes}</textarea>
          </div>
        </div>
        <div class="field">
          <label>Reference (Sendes på faktura til kunde)</label>
          <div class="control">
            <input class="input is-dark" type="text" id="reference" value="${reference}" />
          </div>
        </div>
        <div class="field">
          <label>Antal</label>
          <div class="control">
            <input class="input is-dark" type="number" id="quantity" value="${quantity}" />
          </div>
        </div>
      </form>
    `,
    showCancelButton: true,
    showConfirmButton: allowEdit,
    confirmButtonText: 'Save',
    cancelButtonText: 'Cancel',
    preConfirm: () => {
      // Show loading
      Swal.showLoading();
      editOrderItem(orderItemId, document.getElementById('price').value, document.getElementById('notes').value, document.getElementById('reference').value, document.getElementById('quantity').value)
          .then(() => {
            // Close the modal
            Swal.close();
            // If afterSubmit is set, run it
            if (afterSubmit) {
              afterSubmit();
            }
          })
          .catch((e) => {
            Swal.fire('Error', e.response.data.error ?? e.response, 'error');
          });
    }
  });
}

</script>