import React, { useEffect, useState } from "react";
import { FaUserCircle } from "react-icons/fa";
import { NavLink, useNavigate } from "react-router-dom"; // Import NavLink for navigation
import "./Navbar.css"; // Navbar-specific styles
import axios from "axios";
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

const Navbar = () => {
  const navigate = useNavigate();
  const [user, setUser] = useState(null);

  useEffect(() => {
    const loggedInUser = localStorage.getItem("user");
    if (loggedInUser) {
      setUser(JSON.parse(loggedInUser));
    } else {
      axios.get("http://localhost:8080/api/user/profile", { withCredentials: true })
        .then((response) => {
          setUser(response.data.user);
        })
        .catch((error) => {
          console.error("Error fetching user data:", error);
        });
    }
  }, []);

  // Handle logout functionality
  const handleLogout = async () => {
    try {
      // Call the logout API
      await axios.get("http://localhost:8080/auth/logout", { withCredentials: true });

      // Redirect to the login page after successful logout
      navigate("/");
    } catch (error) {
      console.error("Error during logout:", error);
      toast.error("Failed to log out. Please try again.");
    }
  };

  return (
    <header className="navbar">
      <div className="navbar-container">
        <ToastContainer />

        <NavLink to="/Welcome" className="navbar-logo">
          <img src="logo_.png" alt="Logo" className="logo-img" />
        </NavLink>


        <div className="button-container">

          {/* Consolidated buttons in the center */}

          <NavLink to="/consolidated" className="consolidated-button nav-btn">
            Faculty Consolidated
          </NavLink>
          <NavLink to="/courseConsolidated" className="consolidated-button nav-btn">
            Course Consolidated
          </NavLink>
          <NavLink to="/departmentConsolidated" className="navbar-title nav-btn">
            Department Consolidated
          </NavLink>
        </div>
        <div>
          <button className="logout-button" onClick={handleLogout}>
            Logout
          </button>
        </div>

        {/* User icon at the right */}
        <NavLink to="/accounts" className="user-icon-link">
          {user && user.profilePicture ? (
            <img
              src={user.profilePicture}
              alt="Profile"
              className="user-icon"
              style={{ width: '40px', height: '40px', borderRadius: '50%' }}
            />
          ) : (
            <FaUserCircle className="user-icon" />
          )}
        </NavLink>
      </div>
    </header>
  );
};

export default Navbar;
