import { useState } from 'react';
import authService from '../services/authService';
import { jwtDecode } from 'jwt-decode';
import { useNavigate } from 'react-router-dom';

const useAuth = () => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const navigate = useNavigate();

  const login = async (email, password) => {
    setLoading(true);
    setError(null);
    try {
      const { TOKEN } = await authService.login(email, password);
      localStorage.setItem('token', TOKEN);
      const decoded = jwtDecode(TOKEN);
      setUser(decoded);
      if (decoded.ROLE == 'student') {
        window.location.href = '/learning';
      }else if (decoded.ROLE == 'teacher') {
        window.location.href = '/portal';
      }else if (decoded.ROLE == 'admin') {
        window.location.href = '/admin';
      }

    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const register = async (email, password, role) => {
    setLoading(true);
    setError(null);
    try {
      const { token } = await authService.register(email, password, role);
      localStorage.setItem('token', token);
      const decoded = jwtDecode(token);
      setUser(decoded);
      navigate(`/${decoded.role}`);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const forgotPassword = async (email) => {
    setLoading(true);
    setError(null);
    try {
      await authService.forgotPassword(email);
      // Handle success response (e.g. navigate to success page)
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const logout = () => {
    authService.logout();
    setUser(null);
    if (!localStorage.removeItem('token')) {
      navigate('/login');
    }else{
      logout();
    }
  };

  const getUserFromToken = () => {
    const token = localStorage.getItem('token');
    if (token) {
      const decoded = jwtDecode(token);
      setUser(decoded);
    }
  };

  return {
    user,
    loading,
    error,
    login,
    register,
    forgotPassword,
    logout,
    getUserFromToken,
  };
};

export default useAuth;
