<template>
  <div
    class="tab-pane fade show active"
    id="user-set-profile"
    role="tabpanel"
    aria-labelledby="user-set-profile-tab"
  >
    <BCard no-body>
      <BCardHeader>
        <h5>اطلاعات حساب</h5>
      </BCardHeader>
      <BCardBody class="card-body">
        <BRow>
          <BCol class="col-sm-6">
            <div class="mb-3">
              <label class="form-label">نام</label>
              <input
                type="text"
                v-model="name"
                :class="{ 'is-invalid': errors.name }"
                class="form-control"
                placeholder="نام"
                @input="clearError('name')"
              />
              <small v-if="errors.name" class="text-danger">
                {{ errors.name }}
              </small>
            </div>
          </BCol>
          <BCol class="col-sm-6">
            <div class="mb-3">
              <label class="form-label">شماره تماس</label>
              <input
                type="text"
                :class="{ 'is-invalid': errors.mobile }"
                v-model="mobile"
                class="form-control"
                placeholder="شماره تماس"
                @input="clearError('mobile')"
              />
              <small v-if="errors.mobile" class="text-danger">
                {{ errors.mobile }}
              </small>
            </div>
          </BCol>
          <BCol class="col-sm-6">
            <div class="mb-3">
              <label class="form-label">رمز عبور</label>
              <input
                type="password"
                v-model="password"
                class="form-control"
                placeholder="رمز عبور"
              />
            </div>
          </BCol>
        </BRow>
      </BCardBody>
      <BcardFooter>
        <div class="text-center btn-page">
          <div @click="editProfile" class="btn btn-primary" :disabled="loading">
            <span
              v-if="loading"
              class="spinner-border spinner-border-sm"
              role="status"
              aria-hidden="true"
            ></span>
            <span v-if="!loading">ویرایش</span>
          </div>
        </div>
      </BcardFooter>
    </BCard>
  </div>
</template>
<script>
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import { toRef, watch, ref } from "vue";
import moment from "jalali-moment";
export default {
  props: {
    user: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    const loading = ref(false);
    const errors = ref({});
    const localUser = toRef(props.user);
    const name = ref(props.user.name);
    const mobile = ref(props.user.mobile);
    const password = ref();

    const validateForm = () => {
      errors.value = {};
      if (!name.value) errors.value.name = "وارد کردن نام ضروری می باشد";
      if (!mobile.value) errors.value.mobile = "وارد کردن موبایل ضروری می باشد";

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

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

    const convertToJalali = (date) => {
      return moment(date, "YYYY-MM-DD HH:mm:ss")
        .locale("fa")
        .format("YYYY/MM/DD");
    };

    watch(
      () => props.user,
      (newVal) => {
        if (newVal) {
          localUser.value = newVal;
          name.value = localUser.value.name;
          mobile.value = localUser.value.mobile;
        }
      }
    );

    const editProfile = () => {
      if (!validateForm()) return;
      loading.value = true;
      const formData = new FormData();
      formData.append("name", name.value);
      formData.append("mobile", mobile.value);
      if (password.value) {
        formData.append("password", password.value);
      }
      ApiServiece.put("client/me", formData)
        .then(() => {
          toast.success("!پروفایل با موفقیت ویرایش شد", {
            position: "top-right",
            autoClose: 1000,
          });
          loading.value = false;
        })
        .catch(() => {
          loading.value = false;
          toast.error("!مشکلی در ویرایش پروفایل ایجاد شد", {
            position: "top-right",
            autoClose: 1000,
          });
        });
    };

    return {
      convertToJalali,
      localUser,
      name,
      mobile,
      editProfile,
      clearError,
      errors,
      password,
      loading,
    };
  },
};
</script>
