import React, { createContext, useContext, useState, useEffect } from 'react';
import { getUserFromToken } from '../components/utils/jwt';

interface AuthContextType {
  token: string | null;
  userId: string | null;
  login: (token: string, userId: string, role: string[]) => void;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [token, setToken] = useState<string | null>(null);
  const [userId, setUserId] = useState<string | null>(null);
  const [role, setRole] = useState<string[] | null>(null);

  useEffect(() => {
    const storedToken = localStorage.getItem('token');
    const storedUserId = localStorage.getItem('userId');
    if (!storedToken) {
      return
    }
    if (storedToken && storedUserId) {
      setToken(storedToken);
      setUserId(storedUserId);
    }

  const user = getUserFromToken(storedToken);
  if (!user) {
    logout(); // z. B. localStorage.clear() + navigate("/login")
    return;
  }
    // ⏳ Logout bei Ablauf
  const timeout = setTimeout(() => {
    logout();
  }, user.exp * 1000 - Date.now());

  return () => clearTimeout(timeout);

  }, []);

  const login = (token: string, userId: string, role: string[]) => {
    setToken(token);
    setUserId(userId);
    setRole(role);
    localStorage.setItem('token', token);
    localStorage.setItem('userId', userId);
    localStorage.setItem('role', JSON.stringify(role)); // Store array as string
  };

  const logout = () => {
    setToken(null);
    setUserId(null);
    setRole(null);
    localStorage.removeItem('token');
    localStorage.removeItem('userId');
    localStorage.removeItem('role');
    localStorage.clear(); // Optional: Entfernt alle gespeicherten Daten
    // Hier könntest du auch eine Weiterleitung zur Login-Seite hinzufügen
  };

  return (
    <AuthContext.Provider value={{ token, userId, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

/**
 * Custom React hook to access the authentication context.
 *
 * @returns {AuthContextType} The current authentication context value.
 * @throws {Error} If used outside of an `AuthProvider`.
 *
 * @example
 * const { user, login, logout } = useAuth();
 */
export function useAuth() {
  const context = useContext(AuthContext);
  if (!context) throw new Error('useAuth must be used within AuthProvider');
  return context;
}
