import { createContext, useState, useContext, useEffect } from "react";
import type { JSX } from 'react';
import { getUserFromToken } from '../utils/jwt';
// import { loginUser } from "../api/user";

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

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

export const AuthProvider = ({ children }: { children: JSX.Element }) => {
  const [token, setToken] = useState<string | null>(null);
  const [userId, setUserId] = useState<string | null>(null);
  // const [userEmail, setuserEmail] = 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);
    localStorage.setItem('token', token);
    localStorage.setItem('userId', userId);
    localStorage.setItem('role', JSON.stringify(role)); // Store array as string
  };

  const logout = () => {
    setToken(null);
    setUserId(null);
    localStorage.removeItem('token');
    localStorage.removeItem('userId');
  };

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

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