// contexts/AuthContext.tsx
import React, {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";
import apiClient from "@/services/api"; // نمونه axios که بعداً می‌سازیم
import { useRouter } from "expo-router";
import axios from "axios";

interface AuthContextType {
  isLogin: boolean;
  isLoading: boolean;
  signIn: (token: string) => Promise<void>;
  signOut: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType>({
  isLogin: false,
  isLoading: true,
  signIn: async () => {},
  signOut: async () => {},
});

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const router = useRouter();

  const [isLogin, setIsLogin] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState(true);

  const loadToken = () => {
    axios
      .get("https://api.plania.ir/api/auth/token/verify/")
      .then((res) => {
        setIsLogin(true);
      })
      .catch((err) => {
        if (err.response?.status === 401) {
          axios
            .get(`https://api.plania.ir/api/auth/token/refresh/`)
            .then(() => {
              loadToken();
            }).catch((err)=>{
              if(err.response.status===401){
                setIsLogin(false)
              }
            })
        }
        
      })
      .finally(() => {
        setIsLoading(false);
      });
  };
  useEffect(() => {
    loadToken();
  }, []);
  useEffect(() => {}, [isLogin]);

  const signIn = async (token: string) => {
    try {
      setIsLogin(true);
      router.push({
        pathname: "/(tabs)",
      });
    } catch (error) {
      console.error("Failed to save token", error);
    }
  };

  const signOut = async () => {
    try {
      apiClient.post("api/auth/logout/").then(async (res) => {
        setIsLogin(false);
        router.push({
          pathname: "/(auth)/login",
        });
      });
    } catch (error) {
      console.error("Failed to remove token", error);
    }
  };

  const value = useMemo(
    () => ({
      isLogin,
      isLoading,
      signIn,
      signOut,
    }),
    [isLogin, isLoading, signIn, signOut],
  );
  return (
    <AuthContext.Provider value={{ isLogin, isLoading, signIn, signOut }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
