import apis from "~/apis/authApi";
import { defineStore } from "pinia";
import { useCommonStore } from "./commonStore";
import type { User } from "~/types/commonTypes";
import { useStorage } from "@vueuse/core";
import { clearStorage } from "@/manuals/localStorage";
export const useAuthStore = defineStore("authStore", {
  // persist: true,
  persist: {
    storage: piniaPluginPersistedstate.localStorage(),
    pick: [
      "mobile",
      "fullName",
      "isResetPassword",

      "errors",
      "user",
      "isAuthenticated",
      "isRealUser",
      "authHttpService",
    ],
  },
  state: () => ({
    mobile: null as string | null,
    fullName: undefined as object | undefined,
    isResetPassword: false as boolean,

    errors: null as null | object,
    user: {} as User,
    isAuthenticated: false as boolean,
    // isRealUser: useStorage("user_stt", "user").value
    // ? true
    // : (false as boolean),
    isRealUser: useStorage("user_stt", false).value,
    // authHttpService: undefined as object | undefined,
  }),
  getters: {
    currentUser(state) {
      if ("user_id" in state.user) {
        return state.user;
      } else {
        const defaultUserValue: User = {
          user_id: 0,
          user_level: 0,
          token: "",
          expire: 0,
          type: 0,
          refresh_token: "",
          refresh_expire: 0,
          user_data: {
            first_name: "",
            last_name: "",
            avatar: "",
            username: "",
          },
        };

        const user = useStorage("user", defaultUserValue).value;

        if (user) {
          state.user = user;
          return user;
        }
        return {};
      }
    },
    isRealUserGetter(state) {
      return state.isRealUser;
    },
    isGuest(state) {
      return !state.isRealUser;
    },
    isAuthenticatedGetter(state) {
      let tokenStirng = useStorage("id_token", "GuestAccess").value;

      if (tokenStirng && tokenStirng == "GuestAccess") {
        this.isRealUser = false;
        return false;
      } else if (tokenStirng && tokenStirng != "GuestAccess") {
        this.isRealUser = true;
        return true;
      }
    },
    getResetPasswordState(state) {
      return state.isResetPassword;
    },
    getFullName(state) {
      return state.fullName;
    },
    getMobile(state) {
      return state.mobile;
    },
  },
  actions: {
    SET_USER_PHONE_NUMBER(mobile: string) {
      this.mobile = mobile;
    },
    SET_USER_FULL_NAME(fullName: object) {
      this.fullName = fullName;
      // this.fullName.name = fullName?.first_name ?? undefined;
    },
    SET_IS_RESET_PASSWORD(isResetPassword = true) {
      this.isResetPassword = isResetPassword;
    },
    setError(error = null) {
      this.errors = error;
    },
    setUser(response) {
      console.info("setUser");

      const myStore = useCommonStore();

      this.isAuthenticated = true;
      this.isRealUser = true;
      this.user = response;
      this.errors = {};

      let id_token = useStorage("id_token", "");
      id_token.value = this.user.token;

      let user = useStorage("user", {});
      user.value = this.user;

      let user_stt = useStorage("user_stt", "");
      user_stt.value = "user";

      let USER_TYPE = useStorage("USER_TYPE", {});
      USER_TYPE.value = this.user.type;

      myStore.tokenIsValid = true;
    },
    setGuest(user: User) {
      const myStore = useCommonStore();

      this.isAuthenticated = true;
      this.isRealUser = false;
      this.user = user;
      this.errors = {};

      let id_token = useStorage("id_token", "");
      id_token.value = "GuestAccess";

      let userStr = useStorage("user", {});
      userStr.value = this.user;

      let user_stt = useStorage("user_stt", "");
      user_stt.value = "c";

      let USER_TYPE = useStorage("USER_TYPE", "-1");
      USER_TYPE.value = "-1";

      myStore.tokenIsValid = true;
    },
    logout() {
      clearStorage();
      const htmlElm = document.querySelector("html");
      if (htmlElm) htmlElm.style.removeProperty("filter");
    },
    async getCaptcha() {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.captcha, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "GET",
        });

        return response;
      } catch (error) {
        return error;
      }

      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);
      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .getRequest(apis.captcha)
      //     .then((response) => {
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
    async phoneLogin(credentials) {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.phoneLogin, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "POST",
          body: credentials,
        });

        this.setUser(response?.data);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }

      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .postRequest(apis.phoneLogin, credentials)
      //     .then((response) => {
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
    async getActivationCode(credentials) {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.activationCode, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "POST",
          body: credentials,
        });

        this.setUser(response);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }
      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .postRequest(apis.activationCode, credentials)
      //     .then((response) => {
      //       this.setUser(response.data);
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
    async loginWithGoogle(credentials) {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.loginGoogle, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "POST",
          body: credentials,
        });

        this.setUser(response?.data);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }

      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .postRequest(apis.loginGoogle, credentials)
      //     .then((response) => {
      //       this.setUser(response.data);
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
    async login(credentials) {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.login, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "POST",
          body: credentials,
        });

        this.setUser(response.data);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }
      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .postRequest(apis.login, credentials)
      //     .then((response) => {
      //       this.setUser(response.data);
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
    // called from the router.js
    async loginAsGuest2() {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.validateUser, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Authorization: "GuestAccess",
          },
        });

        this.setUser(response?.data);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }

      // return new Promise((resolve, reject) => {
      //   const httpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);
      //   httpService
      //     .getRequest(apis.validateUser, {
      //       headers: {
      //         "Content-Type": "application/x-www-form-urlencoded",
      //         Authorization: "GuestAccess",
      //       },
      //     })
      //     .then((response) => {
      //       // let res = data.data;
      //       // res.data.user_data =res.data;
      //       this.setUser(response.data);
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
    // called from the auth mixin.
    async loginAsGuest() {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.validateUser, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Authorization: "GuestAccess",
          },
        });

        this.setUser(response?.data);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }

      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .getRequest(apis.validateUser, {
      //       headers: {
      //         "Content-Type": "application/x-www-form-urlencoded",
      //         Authorization: "GuestAccess",
      //       },
      //     })
      //     .then((response) => {
      //       // let res = data.data;
      //       // res.data.user_data =res.data;
      //       this.setUser(response.data);
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
    async forget(credentials) {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.forget, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "POST",
          body: credentials,
        });

        this.setUser(response?.data);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }

      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .postRequest(apis.forget, credentials)
      //     .then((response) => {
      //       this.setUser(response.data);
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
    async resetPassword(credentials) {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.resetPassword, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "POST",
          body: credentials,
        });

        this.setUser(response?.data);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }

      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .postRequest(apis.resetPassword, credentials)
      //     .then((response) => {
      //       this.setUser(response.data);
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },

    async register(credentials) {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.register, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "POST",
          body: credentials,
        });

        this.setUser(response?.data);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }

      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .postRequest(apis.register, credentials)
      //     .then((response) => {
      //       this.setUser(response.data);
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
    // verifyRealUser() {
    //   const authHttpService = new HttpService(
    //     import.meta.env.VITE_AUTH_BASE_URL
    //   );

    //   if (getUserStt() != "user") return false;
    //   if (getToken()) {
    //     authHttpService.updateHeaders();
    //     return true;
    //   }
    //   return false;
    // },
    // verifyAuth() {
    //   const authHttpService = new HttpService(
    //     import.meta.env.VITE_AUTH_BASE_URL
    //   );

    //   if (getToken()) {
    //     authHttpService.updateHeaders();
    //     return true;
    //   } else {
    //     logout();
    //     this.setGuest({
    //       id: 3,
    //       first_name: "کاربر",
    //       last_name: "مهمان",
    //       email: "",
    //       username: "Guest",
    //       user_id: 3,
    //       user_data: {
    //         first_name: "کاربر",
    //         last_name: "مهمان",
    //         username: "Guest",
    //       },
    //     });
    //     authHttpService.updateHeaders();
    //     return true;
    //     // logout();
    //     // return false;
    //   }
    // },
    async updatePassword(credentials) {
      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.changePassword, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "POST",
          body: credentials,
        });

        this.setUser(response?.data);
        return response;
      } catch (error) {
        this.errors = error?.response?.data.message;
        return error;
      }

      // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   authHttpService
      //     .postRequest(apis.changePassword, credentials)
      //     .then((response) => {
      //       this.setUser(response.data);
      //       resolve(response);
      //     })
      //     .catch((error) => {
      //       this.errors = error?.response?.data.message;
      //       reject(error?.response?.data);
      //     });
      // });
    },
  },
});
