import React, { useState, useEffect } from "react";
import GameDataManager from "../../../services/GameDataManager.js";
import { useSocket } from "../../../hooks/useSocket";
import "./Navigation.css";

const Navigation = ({ activeTab, onTabChange }) => {
  const { socket } = useSocket();
  const [unreadCount, setUnreadCount] = useState(0);

  const tabs = [
    { id: "dashboard", icon: "fa-tachometer-alt" },
    { id: "dungeons", icon: "fa-dungeon" },
    { id: "skills", icon: "fa-graduation-cap" },
    { id: "inventory", icon: "fa-archive" },
    { id: "shop", icon: "fa-store" },
    { id: "crafting", icon: "fa-hammer" },
    { id: "itemlist", icon: "fa-list-ul" },
    { id: "chat", icon: "fa-comments" },
    { id: "notifications", icon: "fa-bell" },
  ];

  useEffect(() => {
    if (!socket) return;

    const handleNotifyUpdate = (count) => {
      setUnreadCount(count);
    };

    socket.on("notifications:unread_count", handleNotifyUpdate);

    socket.on("notification:new", () => {
      if (activeTab !== "notifications") {
        setUnreadCount((prev) => prev + 1);
      }
    });

    return () => {
      socket.off("notifications:unread_count", handleNotifyUpdate);
      socket.off("notification:new");
    };
  }, [socket, activeTab]);

  const handleTabClick = (id) => {
    if (id === "notifications") setUnreadCount(0);
    onTabChange(id);
  };

  const getLabel = (id) => {
    if (id === "itemlist") return "ITEM_LIST";
    if (id === "chat") return "CHAT";
    if (id === "notifications") return "ALERTS";
    return GameDataManager.t(`category.tabs.original.${id}`);
  };

  return (
    <nav className="main-nav">
      <div className="nav-container">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            className={`nav-btn ${activeTab === tab.id ? "active" : ""} ${tab.id}`}
            onClick={() => handleTabClick(tab.id)}
          >
            <div className="nav-btn-content">
              <div className="icon-wrapper">
                <i className={`fas ${tab.icon}`}></i>
                {tab.id === "notifications" && unreadCount > 0 && (
                  <span className="nav-badge">{unreadCount}</span>
                )}
              </div>
              <span className="nav-label">{getLabel(tab.id)}</span>
            </div>
            <div className="nav-active-indicator"></div>
          </button>
        ))}
      </div>
    </nav>
  );
};

export default Navigation;
