<script setup>
  import { ref, reactive, defineExpose, defineEmits } from "vue";
  import ApiService from "@/services/ApiService";
  import {toast} from "vue3-toastify";
  import {BRow} from "bootstrap-vue-next";
  import codeCountries from "@/utils/code-countries"

  const initForm = {
    title: null,
    minimum_shipping_weight: null,
    per_kilograms_cost: null,
    status: 'in_active',
    country_code: null,
  }

  const emit = defineEmits(['country-updated'])

  const errors = ref({})

  const loading = ref(false)

  const form = reactive({...initForm})

  const clearError = (field) => {
    errors.value[field] = "";
  };

  const validateForm = () => {
    errors.value = {};
    if (!form.title) errors.value.title = "وارد کردن عنوان کشور ضروری می باشد";
    if (!form.minimum_shipping_weight) errors.value.minimum_shipping_weight = "وارد کردن حداقل وزن حمل ونقل ضروری می باشد";
    if (!form.per_kilograms_cost) errors.value.per_kilograms_cost = "وارد کردن هزینه ضروری می باشد";
    if (!form.country_code) errors.value.country_code = "وارد کردن پیش شماره کشور ضروری می باشد";

    return Object.keys(errors.value).length === 0;
  };

  const addCountry = async () => {
    if (!validateForm()) {
      toast.error("لطفا فیلد های لازم را وارد نمایید", {
        position: "top-right",
        autoClose: 1000,
      });
      return;
    }

    try {
      loading.value = true

      const url = form?.id ? `admin/country-configs/${form?.id}` : 'admin/country-configs'

      const { data: { success, message } } = await ApiService[form?.id ? 'put' : 'post'](url, form)

      if (success) {
        toast.success(message)

        Object.assign(form, initForm)

        document.getElementById("closeModal").click();

        emit("country-updated");
      }
    } catch (e) {
      toast.error(e?.response?.data?.message)
    } finally {
      loading.value = false
    }
  };

  const closeModal = () => {
    if (form?.id)
      form.id = undefined

    Object.assign(form, initForm)
  }

  defineExpose({ form })
</script>

<template>
  <div
      class="modal fade"
      id="countriesModal"
      tabindex="-1"
      role="dialog"
      data-bs-backdrop="static"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
  >
    <div class="modal-dialog modal-sm" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">
            {{ form?.id ? 'ویرایش کشور' : 'اضافه کردن کشور' }}
          </h5>
          <button
              type="button"
              class="btn-close"
              id="closeModal"
              data-bs-dismiss="modal"
              aria-label="Close"
              @click="closeModal"
          ></button>
        </div>

        <div class="modal-body">
          <form @submit.prevent="addCountry">
            <BRow class="g-3">
              <!-- Form fields -->

              <BCol class="col-lg-6">
                <div class="form-group">
                  <label class="form-label">نام کشور</label>
                  <input
                      v-model="form.title"
                      type="text"
                      class="form-control"
                      placeholder="نام کشور را وارد نمایید"
                  />
                  <small v-if="errors.title" class="text-danger">{{
                      errors.title
                    }}</small>
                </div>
              </BCol>

              <BCol class="col-lg-6">
                <div class="form-group">
                  <label class="form-label">حداقل هزینه حمل و نقل</label>
                  <input
                      v-model="form.minimum_shipping_weight"
                      @input="clearError('minimum_shipping_weight')"
                      type="number"
                      class="form-control"
                  />
                  <small v-if="errors.minimum_shipping_weight" class="text-danger">{{
                      errors.minimum_shipping_weight
                    }}</small>
                </div>
              </BCol>

              <BCol class="col-lg-6">
                <div class="form-group">
                  <label class="form-label">هزینه هر کیلو گرم</label>
                  <input
                      v-model="form.per_kilograms_cost"
                      @input="clearError('per_kilograms_cost')"
                      type="number"
                      class="form-control"
                  />
                  <small v-if="errors.per_kilograms_cost" class="text-danger">{{
                      errors.per_kilograms_cost
                    }}</small>
                </div>
              </BCol>

              <BCol class="col-lg-6">
                <div class="form-group">
                  <label class="form-label">انتخاب پیش شماره</label>

                  <select
                      class="form-select"
                      v-model="form.country_code"
                      @change="clearError('country_code')"
                  >
                    <option v-for="code in codeCountries" :value="code?.dial_code" :key="code?.code">
                      {{ code?.name }}({{ code?.dial_code }})
                    </option>
                  </select>

                  <small v-if="errors.country_code" class="text-danger">{{errors.country_code}}</small>
                </div>
              </BCol>

              <BCol class="col-lg-6">
                <div class="form-group">
                  <label class="form-label">وضعیت</label>

                  <select
                      class="form-select"
                      v-model="form.status"
                      @change="clearError('status')"
                  >
                    <option value="active">فعال</option>
                    <option value="in_active">غیر فعال</option>
                  </select>

                  <small v-if="errors.status" class="text-danger">{{errors.status}}</small>
                </div>
              </BCol>

            </BRow>

            <!-- Submit Buttons -->
            <div
                class="d-flex justify-content-end gap-2"
                style="margin-top: 20px"
            >
              <button
                  type="button"
                  class="btn btn-secondary"
                  data-bs-dismiss="modal"
                  id="addClose"
              >
                بستن
              </button>
              <button type="submit" class="btn btn-primary" :disabled="loading">
                <span
                    v-if="loading"
                    class="spinner-border spinner-border-sm"
                    role="status"
                    aria-hidden="true"
                ></span>
                ذخیره
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 1.5rem;
}

.modal-body {
  padding: 1rem 1.5rem;
}

.modal-header {
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 1rem;
}

.selected-icon-container i {
  font-size: 2.5rem;
}

.icon-container i {
  font-size: 2rem;
  margin-right: 10px;
}
</style>