import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

interface AuthContextValue {
  token: string | null;
  role: string | null;
  volunteerID: number | null;
  login: (token: string) => void;
  logout: () => void;
}

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

function parseJWT(token: string): { volunteer_id: number; role: string } | null {
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload;
  } catch {
    return null;
  }
}

export function AuthProvider({ children }: { children: ReactNode }) {
  const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'));
  const [role, setRole] = useState<string | null>(null);
  const [volunteerID, setVolunteerID] = useState<number | null>(null);

  useEffect(() => {
    if (token) {
      const payload = parseJWT(token);
      setRole(payload?.role ?? null);
      setVolunteerID(payload?.volunteer_id ?? null);
    } else {
      setRole(null);
      setVolunteerID(null);
    }
  }, [token]);

  function login(t: string) {
    localStorage.setItem('token', t);
    setToken(t);
  }

  function logout() {
    localStorage.removeItem('token');
    setToken(null);
  }

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

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used within AuthProvider');
  return ctx;
}
