<template>
  <div
    class="modal fade"
    id="editUser"
    tabindex="-1"
    role="dialog"
    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">ویرایش کاربر</h5>
          <button
            type="button"
            class="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="editUser">
            <BRow class="g-3">
              <BCol class="col-lg-6">
                <div class="form-group">
                  <label class="form-label">نام</label>
                  <input
                    v-model="localName"
                    type="text"
                    class="form-control"
                    placeholder="نام را وارد نمایید"
                  />
                </div>
              </BCol>

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

              <BCol class="col-lg-6">
                <div class="form-group">
                  <label class="form-label">نقش</label>

                  <select
                    class="form-select"
                    v-model="localRole"
                    @change="clearError('role')"
                    placeholder="نوع کاربر"
                  >
                    <option value="admin">مدیر</option>
                    <option value="client">مشتری</option>
                    <option value="operator">اپراتور</option>
                  </select>

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

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

              <ConfigCountriesSelect v-model:country-code="localCountryCode"/>
            </BRow>

            <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="close"
              >
                بستن
              </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>

<script>
import ApiServiece from "@/services/ApiService";
import { ref, toRef, watch } from "vue";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ConfigCountriesSelect from "@/components/ConfigCountriesSelect.vue";

export default {
  components: {ConfigCountriesSelect},
  props: {
    name: {
      type: String,
      required: true,
    },
    mobile: {
      type: String,
      required: true,
    },
    id: {
      type: String,
      required: true,
    },
    role: {
      type: String,
      required: true,
    },
    countryCode: {
      type: Number,
      required: true,
    },
  },

  setup(props, { emit }) {
    const password = ref();
    const localName = toRef(props.name);
    const localMobile = toRef(props.mobile);
    const localRole = toRef(props.role);
    const localCountryCode = toRef(props.countryCode);
    const localId = toRef(props.id);
    const errors = ref({});
    const loading = ref(false);

    watch(
      () => props.name,
      (newVal) => (localName.value = newVal)
    );
    watch(
      () => props.mobile,
      (newVal) => (localMobile.value = newVal)
    );
    watch(
      () => props.id,
      (newVal) => (localId.value = newVal)
    );

    watch(
      () => props.role,
      (newVal) => (localRole.value = newVal)
    );

    watch(
        () => props.countryCode,
        (newVal) => {
          localCountryCode.value = Number(newVal);
        }
    );


    const validateForm = () => {
      errors.value = {};
      if (!localMobile.value)
        errors.value.localMobile = "وارد کردن موبایل ضروری می باشد";
      if (!localRole.value)
        errors.value.localMobile = "انتخاب کردن نقش  کاربر ضروری می باشد";
      if (!localCountryCode.value)
        errors.value.localCountryCode = "انتخاب کردن پیش شماره ضروری می باشد";
      if (password.value && password.value.length < 8) {
        errors.value.password = " رمز عبور باید حداقل 8 کاراکتر باشد";
      }
      return Object.keys(errors.value).length === 0;
    };

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

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

      const formData = new FormData();
      formData.append("mobile", localMobile.value);
      if (localName.value)
        formData.append("name", localName.value);
      formData.append("role", localRole.value);
      if (password.value) {
        formData.append("password", password.value);
      }
      formData.append("country_config_id", localCountryCode.value)

      ApiServiece.put(`admin/users/${localId.value}`, formData)
        .then(() => {
          toast.success("!کاربر با موفقیت ویرایش شد", {
            position: "top-right",
            autoClose: 1000,
          });
          
        })
        .then(() => {
          setTimeout(() => {
            document.getElementById("close").click();
            emit("user-updated");
          }, 500);
        })
        .catch((error) => {
          toast.error(error?.response?.data?.message , {
            position: "top-right",
            autoClose: 1000,
            onClose: () => emit("user-updated"),
          });
        })
        .finally(() => {
          loading.value = false;
        });
    };

    return {
      errors,
      loading,
      clearError,
      localName,
      localMobile,
      password,
      editUser,
      localRole,
      localCountryCode,
    };
  },
};
</script>

<style scoped>
.profile-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-upload-icon {
  font-size: 64px;
  color: #6c757d;
  border: 2px dashed #6c757d;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 20px;
}

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

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 1rem;
}

.input-group {
  margin-top: 0.5rem;
}
.profile-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-upload-btn {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 2px solid #007bff;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.profile-upload-btn i {
  font-size: 20px;
  color: #007bff;
}

.profile-image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

.profile-placeholder {
  border: 2px dashed #007bff;
}

.d-none {
  display: none;
}
.profile-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-upload-btn {
  width: 30px; /* اندازه دکمه را کوچک‌تر کنید */
  height: 30px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc; /* کمی خط دور دکمه برای بهتر دیده شدن */
  background-color: #fff;
  cursor: pointer;
}

.profile-upload-btn i {
  font-size: 16px; /* اندازه آیکون را کوچک‌تر کنید */
  color: #007bff; /* رنگ آیکون را تغییر دهید */
}

.profile-image-preview img,
.profile-placeholder {
  width: 80px;
  height: 80px;
}

.profile-placeholder i {
  font-size: 40px;
}
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 1.5rem; /* Increased padding for better spacing */
}

.modal-header {
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 1rem; /* Added padding-bottom to separate the header from the content */
}

.modal-body {
  padding: 1rem 1.5rem; /* Adjusted padding for a more balanced layout */
}

.form-group {
  margin-bottom: 1.5rem; /* Increased margin between form groups */
}

.input-group {
  margin-top: 0.5rem;
}

.profile-image-preview:hover .overlay {
  opacity: 1;
}

.profile-image-preview:hover img,
.profile-image-preview:hover .profile-placeholder {
  opacity: 0.7;
}
</style>
