"use client";

import React from "react";
import { useRouter, usePathname } from "next/navigation";
import { toast } from "sonner";
import AuthService from "@/services/auth.service";
import { getToken, removeToken, STORAGE_KEY } from "@/lib/auth";
import { User } from "@/types/auth.type";

interface AuthContextProps {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  isChecking: boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
  checkAuth: () => Promise<boolean>;
}

const AuthContext = React.createContext<AuthContextProps | null>(null);

const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [user, setUserState] = React.useState<User | null>(null);
  const [isLoading, setIsLoading] = React.useState<boolean>(false);
  const [isChecking, setIsChecking] = React.useState<boolean>(false);

  const router = useRouter();
  const pathname = usePathname();

  const checkAuth = React.useCallback(async () => {
    const token = getToken();
    if (!token) return false;

    setIsChecking(true);
    try {
      const response = await AuthService.getMe();
      if (response.data) {
        setUserState(response.data);
        return true;
      }
    } catch (error) {
      console.error("Auth check failed:", error);
      removeToken();
      setUserState(null);
    } finally {
      setIsChecking(false);
    }
    return false;
  }, []);

  const login = async (username: string, password: string) => {
    setIsLoading(true);

    return AuthService.login({ username, password })
      .then((response) => {
        if (response.data.user) setUserState(response.data.user);
        // Token is already set by AuthService, no need to set again
        return Promise.resolve();
      })
      .catch((error) => {
        throw new Error(error.message || "Login Gagal!");
      })
      .finally(() => setIsLoading(false));
  };

  const logout = React.useCallback(() => {
    setUserState(null);
    removeToken();
    router.replace("/admin/login");
    toast.success("Logout berhasil!");
  }, [router]);

  React.useEffect(() => {
    const token = getToken();
    
    // Redirect to login if no token and on protected admin route
    if (!token) {
      if (pathname?.startsWith("/admin") && pathname !== "/admin/login") {
        router.replace("/admin/login");
      }
      return;
    }

    // Skip checkAuth if already authenticated and not on login page
    if (user && pathname !== "/admin/login") return;
    
    // Skip checkAuth if on login page and no user
    if (!user && pathname === "/admin/login") return;

    checkAuth().then((isValid) => {
      if (!isValid && pathname !== "/admin/login") {
        router.replace("/admin/login");
      } else if (isValid && pathname === "/admin/login") {
        router.replace("/admin");
      }
    });
  }, [pathname, router, checkAuth, user]);

  const contextValue: AuthContextProps = {
    user,
    isAuthenticated: !!user,
    isLoading,
    isChecking,
    login,
    logout,
    checkAuth,
  };

  return (
    <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
  );
};

export { AuthProvider, AuthContext };
