import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage";
import axios from "axios";
import * as api from "@/api/auth";
import { router } from "expo-router";

let interceptorInitialized = false;

export const useAuthStore = create(
  persist(
    (set, get) => {
      if (!interceptorInitialized.current) {
        axios.interceptors.response.use(
          (response) => response,
          (error) => {
            if (
              (error.response && error.response.status === 401) ||
              error.response.status === 403
            ) {
              console.warn(error.response.data);
              set({ user_id: null, token: null, isLoading: false });
              delete axios.defaults.headers.common["Authorization"];
              router.replace("/login");
            }
            return Promise.reject(error);
          }
        );
        interceptorInitialized = true;
      }
      return {
        user_id: null,
        token: null,
        isLoading: false,
        error: null,

        signIn: async (email, password) => {
          set({ isLoading: true, error: null });
          try {
            const response = await api.login({email, password});
            set({ user_id: response.user_id, token: response.token, isLoading: false });
          } catch (error) {
            set({
              error: error.response?.data?.message || error.message,
              isLoading: false,
            });
            throw error;
          }
        },

        signUp: async (userData) => {
          set({ isLoading: true, error: null });
          try {
            const response = await api.register(userData);
            set({ user_id: response.user_id, token: response.token, isLoading: false });
          } catch (error) {
            set({
              error: error.response?.data?.message || error.message,
              isLoading: false,
            });
            throw error;
          }
        },

        signInWithGoogle: async (googleToken) => {
          set({ isLoading: true, error: null });
          try {
            const response = await api.googleLogin(googleToken);
            set({ user_id: response.user_id, token: response.token, isLoading: false });
          } catch (error) {
            set({
              error: error.response?.data?.message || error.message,
              isLoading: false,
            });
            throw error;
          }
        },

        signOut: async () => {
          const { token } = get();
          try {
            await api.logout(token);
          } catch (error) {
            console.error("Logout error:", error);
          } finally {
            set({ user_id: null, token: null });
            router.replace("/login");
          }
        },
      };
    },
    {
      name: "auth-storage",
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
);
