import axios from "axios";
import Swal from "sweetalert2";
const url = process.env.VUE_APP_ROOT_URL;

const state = {
  user: null,
  loading: false,
  token: null,
  isAuthenticated: false,
};

export const mutations = {
  SET_USER(state, user) {
    if (user) {
      state.user = user;
      state.isAuthenticated = true;
    } else {
      state.user = null;
      state.isAuthenticated = false;
    }
  },

  SET_TOKEN(state, token) {
    state.token = token;
  },

  LOGOUT(state) {
    state.user = null;
    state.token = null;
    state.isAuthenticated = false;
    localStorage.removeItem("token");
    localStorage.removeItem("user_profile");
  },

  SET_LOADING(state, status) {
    state.loading = status;
  },
};

export const actions = {
  async loginUser({ commit }, credentials) {
    try {
      const { data } = await axios.post(`${url}auth/admin/login`, credentials, {
        headers: {
          "Content-Type": "application/json",
        },
      });

      if (!data) {
        throw new Error("شماره موبایل یا رمز عبور اشتباه است");
      }

      if (
          data?.data?.user?.role === "admin"
          ||
          data?.data?.user?.role === "operator"
      ) {
        commit("SET_TOKEN", data.data.token);

        localStorage.setItem("token", data.data.token);

        localStorage.setItem("user_profile", JSON.stringify(data.data.user));
      } else {
        throw new Error("شماره موبایل یا رمز عبور اشتباه است");
      }
    } catch (error) {
      console.error("Login failed:", error.response?.data || error.message);
      throw new Error(
        error.response?.data?.message ||
          "ورود با مشکل مواجه شد ...! لطفا دوباره امتحان کنید"
      );
    } finally {
      commit("SET_LOADING", false);
    }
  },

  async verifyOtp({ commit }, { mobile, otpCode }) {
    try {
      const response = await axios.post(
        `${url}auth/verify-otp`,
        { mobile, otp: otpCode },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      );

      if (response.data.success) {
        const token = response?.data?.data?.token;

        const user = response?.data?.data?.user;

        if (user?.role === "admin" || user?.role === "operator") {
          localStorage.setItem("token", token);

          localStorage.setItem("user_profile", JSON.stringify(user));

          commit("SET_TOKEN", token);

          commit("SET_USER", user);

          return response.data;
        } else {
          throw new Error("شماره موبایل یا رمز عبور نامعتبر است");
        }
      } else {
        const errorMsg = response.data.message || "خطا در تایید کد";
        throw new Error(errorMsg);
      }
    } catch (error) {
      // console.error(
      //   "OTP verification failed:",
      //   error.response?.data || error.message
      // );
      Swal.fire({
        icon: "error",
        text: `${error?.response?.data?.message}`,
        confirmButtonText: "باشه",
      });

      throw new Error(
          error.response?.data?.message ||
          "ورود با مشکل مواجه شد ...! لطفا دوباره امتحان کنید"
      );
    }
  },

  async resetPassword({ state }, { newPassword, confirmPassword }) {
    if (newPassword !== confirmPassword) {
      throw new Error("رمز عبور و تکرار آن یکسان نیستند");
    }
    console.log("asdad", state.token);
    const token = state.token;

    if (!token) {
      throw new Error("توکن معتبر یافت نشد، لطفاً دوباره وارد شوید.");
    }

    try {
      const response = await axios.post(
        `${url}auth/password`,
        { password: newPassword, password_confirmation: confirmPassword },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
        }
      );

      if (response.data.success) {
        console.log("Password reset successfully");

        return response.data;
      } else {
        throw new Error("تغییر رمز عبور با مشکل مواجه شد.");
      }
    } catch (error) {
      console.error(
        "Password reset failed:",
        error.response?.data || error.message
      );
      throw new Error(
        error.response?.data?.msg || "تغییر رمز عبور با مشکل مواجه شد."
      );
    }
  },

  async logout({ commit }) {
    try {
      const token = localStorage.getItem("token");

      if (token) {
        const response = await axios.post(
          `${url}auth/logout`,
          {},
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );

        if (response.data.success) {
          console.log(response.data.message);

        } else {
          console.error("Logout failed: " + response.data.message);
        }
      }

      commit("LOGOUT");
      localStorage.removeItem("token");
      console.log("Logged out successfully from local state");
    } catch (error) {
      console.error("Error during logout:", error);
      commit("LOGOUT");
      localStorage.removeItem("token");
    }
  },

  async verifyLogin({ commit }) {
    const token = localStorage.getItem("token");

    if (!token) {
      commit("LOGOUT");
      console.log("No token found, user logged out.");
      return;
    }

    try {
      const response = await axios.get(`${url}auth/me`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.data.success) {
        const user = response.data.data;

        console.log("API response data:", response.data);
        console.log("User to be set:", user);

        commit("SET_USER", user);
      } else {
        console.log("Invalid user data, logging out.");
        commit("LOGOUT");
      }
    } catch (error) {
      console.error("Error verifying login:", error);
      commit("LOGOUT");
    }
  },

  loadUserFromLocalStorage({ commit }) {
    const token = localStorage.getItem("token");

    if (token) {
      commit("SET_TOKEN", token);
    }
  },
};

export const getters = {
  getUser(state) {
    return state.user;
  },
  getToken(state) {
    return state.token;
  },
  isAuthenticated(state) {
    return state.isAuthenticated; // Return isAuthenticated directly
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
