import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import { jwtDecode } from "jwt-decode";

interface AuthContextType {
  token: string | null;
  username: string | null;
  role: string | null;
  isAdmin: boolean;
  login: (token: string) => void;
  logout: () => void;
  isAuthenticated: boolean;
  isAuthLoading: boolean;
}

const AuthContext = createContext<AuthContextType>({
  token: null,
  username: null,
  role: null,
  isAdmin: false,
  login: () => {},
  logout: () => {},
  isAuthenticated: false,
  isAuthLoading: true
});

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [token, setToken] = useState<string | null>(null);
  const [username, setUsername] = useState<string | null>(null);
  const [role, setRole] = useState<string | null>(null);
  const [isAuthLoading, setIsAuthLoading] = useState(true); // NEU

  const isAdmin = role === "admin";
  const isAuthenticated = !!token;

  useEffect(() => {
    const storedToken = localStorage.getItem("token");
    if (storedToken) {
      try {
        const decoded: any = jwtDecode(storedToken);
        setToken(storedToken);
        setUsername(decoded.username);
        setRole(decoded.role);
      } catch (error) {
        console.error("Token konnte nicht gelesen werden");
      }
    }
    setIsAuthLoading(false); // Wichtig, auch wenn kein Token
  }, []);

  const login = (newToken: string) => {
    localStorage.setItem("token", newToken);
    setToken(newToken);

    try {
      const decoded: any = jwtDecode(newToken);
      setUsername(decoded.username);
      setRole(decoded.role);
    } catch (err) {
      console.error("Token konnte nicht gelesen werden");
    }
  };


  const logout = () => {
    localStorage.removeItem("token");
    setToken(null);
    setUsername(null);
    setRole(null);
  };

  return (
    <AuthContext.Provider value={{
      token, username, role, isAdmin,
      login, logout, isAuthenticated,
      isAuthLoading 
    }}>
      {children}
    </AuthContext.Provider>
  );
};


export const useAuth = () => useContext(AuthContext);
