<script>
import Rightbar from "@/components/right-bar.vue";

import { ref, onUnmounted, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import ApiServiece from "@/services/ApiService";
import Swal from "sweetalert2";
export default {
  name: "FORGOT-PASSWORD",
  components: {
    Rightbar,
  },
  setup() {
    const settings = ref();
    const logo = ref();
    const verifyOtpLoading = ref(false);
    const sendOtpLoading = ref(false);
    const errors = ref({});
    const router = useRouter();
    const store = useStore();
    const mobile = ref("");
    const otpSent = ref(false);
    const timer = ref(60);
    const otpCode = ref("");
    const resendAvailable = ref(false);
    let timerInterval = null;

    const sendOtp = () => {
      if (!validateSendOtpForm()) return;
      sendOtpLoading.value = true;
      ApiServiece.post(`auth/send-otp`, { mobile: mobile.value })
        .then((resp) => {
          console.log(resp.data);
          otpSent.value = true;
          resendAvailable.value = false;
          sendOtpLoading.value = false;
          Swal.fire({
            icon: "info",
            title: "کد تایید ارسال شد",
            text: "کد تایید به شماره شما ارسال شد. لطفاً کد را قبل از منقضی شدن وارد نمایید",
            confirmButtonText: "باشه",
          });
          startTimer();
        })
        .catch((err) => {
          sendOtpLoading.value = false;
          Swal.fire({
            icon: "error",
            title: "خطا در ارسال کد",
            text: err.response.data.message,
            confirmButtonText: "متوجه شدم",
          });
        });
    };

    const startTimer = () => {
      timerInterval = setInterval(() => {
        if (timer.value > 0) {
          timer.value--;
        } else {
          clearInterval(timerInterval);
          resendAvailable.value = true;
        }
      }, 1000);
    };

    const resendOtp = () => {
      otpCode.value = "";
      timer.value = 60;
      resendAvailable.value = false;
      sendOtp(); // Resend OTP
      startTimer(); // Restart the countdown
    };

    const verifyOtp = async () => {
      if (!validateVerifyOtpForm()) return;
      verifyOtpLoading.value = true;
      try {
        await store.dispatch("user/verifyOtp", {
          mobile: mobile.value,
          otpCode: otpCode.value,
        });
        console.log("worked");
        verifyOtpLoading.value = false;
        router.push({ name: "reset-password-v2" });
      } catch (error) {
        verifyOtpLoading.value = false;
        Swal.fire({
          icon: "error",
          title: "خطایی رخ داد",
          text: `${error.message}`,
          confirmButtonText: "باشه",
        });
      }
    };

    const validateSendOtpForm = () => {
      errors.value = {};

      if (!mobile.value) errors.value.mobile = "موبایل خود را وارد نمایید";
      return Object.keys(errors.value).length === 0;
    };

    const validateVerifyOtpForm = () => {
      errors.value = {};

      if (!mobile.value) errors.value.mobile = "موبایل خود را وارد نمایید";
      if (!otpCode.value) errors.value.otpCode = "کد ارسالی را وارد نمایید";
      return Object.keys(errors.value).length === 0;
    };

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

    onUnmounted(() => {
      if (timerInterval) clearInterval(timerInterval);
    });

    const getSettings = async () => {
      logo.value = localStorage.getItem("logo");
      try {
        const response = await ApiServiece.get("settings/logo_fav");
        settings.value = response.data.data;
      } catch (error) {
        console.error("Error fetching settings:", error);
      }
    };

    onMounted(() => {
      getSettings();
    });

    return {
      sendOtp,
      resendOtp,
      mobile,
      otpSent,
      otpCode,
      timer,
      resendAvailable,
      verifyOtp,
      clearError,
      errors,
      validateVerifyOtpForm,
      sendOtpLoading,
      verifyOtpLoading,
      logo,
      settings,
    };
  },
};
</script>

<template>
  <div class="auth-main v2">
    <div class="bg-overlay bg-dark"></div>
    <div class="auth-wrapper">
      <div class="auth-form">
        <div class="card my-5 mx-3">
          <div class="card-body" style="direction: rtl">
            <div class="text-center mb-4">
              <img :src="logo" alt="Logo" class="styled-logo" />
            </div>
            <h4 class="f-w-500 mb-1">فراموشی رمز عبور</h4>

            <p class="mb-3">
              بازگشت به صفحه
              <router-link to="/login-v2" class="link-primary">
                ورود
              </router-link>
            </p>

            <div class="mb-3">
              <input
                @input="clearError('mobile')"
                type="text"
                class="form-control"
                id="floatingInput"
                placeholder="شماره تماس"
                v-model="mobile"
              />
              <small v-if="errors.mobile" class="text-danger">{{
                errors.mobile
              }}</small>
            </div>

            <div v-if="otpSent" class="mt-3">
              <div class="mb-3">
                <input
                  @input="clearError('otpCode')"
                  type="text"
                  class="form-control"
                  placeholder="کد ورود"
                  v-model="otpCode"
                  :disabled="timer === 0"
                />
                <small v-if="errors.otpCode" class="text-danger">{{
                  errors.otpCode
                }}</small>
              </div>
              <div>
                <p v-if="timer > 0">زمان باقی‌مانده: {{ timer }} ثانیه</p>
                <p v-else>زمان منقضی شده است.</p>
              </div>

              <div class="d-grid mt-3" v-if="otpSent && timer > 0">
                <button
                  @click="verifyOtp"
                  type="button"
                  class="btn btn-success"
                  :disabled="verifyOtpLoading"
                >
                  <span
                    v-if="verifyOtpLoading"
                    class="spinner-border spinner-border-sm"
                    role="status"
                    aria-hidden="true"
                  ></span>
                  <span v-else>ورود</span>
                </button>
              </div>
            </div>

            <div class="d-grid mt-3">
              <button
                v-if="!otpSent"
                @click="sendOtp"
                type="button"
                class="btn btn-primary"
                :disabled="sendOtpLoading"
              >
                <span
                  v-if="sendOtpLoading"
                  class="spinner-border spinner-border-sm"
                  role="status"
                  aria-hidden="true"
                ></span>
                <span v-else> ارسال کد ورود </span>
              </button>

              <button
                v-if="resendAvailable && otpSent"
                @click="resendOtp"
                type="button"
                class="btn btn-primary"
              >
                ارسال مجدد کد
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <Rightbar />
</template>

<style scoped>
.styled-logo {
  display: block;
  max-width: 120px; /* Adjust the logo size here */
  width: 100%;
  height: auto;
  border-radius: 10px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
  margin: 0 auto 30px;
  margin-bottom: 90px;
}

.card {
  border: none;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.card-body {
  padding: 40px;
}

h4 {
  font-size: 1.5rem;
  font-weight: 500;
}

.text-center {
  text-align: center;
}

.mb-3 {
  margin-bottom: 1.5rem;
}

.form-control {
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  padding: 0.8rem 1rem;
}
</style>
