import React, { useEffect, useState } from "react";
import "./GameInterface.css";
import GameHeader from "./components/GameHeader";
import Navigation from "./components/Navigation";
import Console from "../../components/Console/Console.jsx";

import DashboardTab from "./tabs/DashboardTab";
import InventoryTab from "./tabs/InventoryTab";
import DungeonsTab from "./tabs/DungeonsTab";
import SkillsTab from "./tabs/SkillsTab";
import BaseTab from "./tabs/BaseTab";
import QuestsTab from "./tabs/QuestsTab";
import ShopTab from "./tabs/ShopTab";
import CraftingTab from "./tabs/CraftingTab";
import ChatTab from "./tabs/ChatTab";
import ItemListTab from "./tabs/ItemListTab.jsx";
import Notification from "./tabs/NotificationTab.jsx";
import DungeonScreen from "./components/DungeonScreen";
import { useSocket } from "../../hooks/useSocket.js";

const GameInterface = ({ onExit }) => {
  const [activeTab, setActiveTab] = useState("dashboard");
  const [activeDungeonSession, setActiveDungeonSession] = useState(null);
  const { socket } = useSocket();

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

    socket.on("dungeon:started", (sessionData) => {
      setActiveDungeonSession(sessionData);
    });

    socket.on("dungeon:completed", (results) => {
      setActiveDungeonSession(null);
    });

    socket.on("error", (err) => {
      alert(`SYSTEM_ERROR: ${err.message}`);
    });

    return () => {
      socket.off("dungeon:started");
      socket.off("dungeon:completed");
      socket.off("error");
    };
  }, [socket]);

  const handleStartDungeon = (dungeonId) => {
    socket.emit("dungeon:start", { dungeonId });
  };

  const handleAbortMission = () => {
    if (
      window.confirm(
        "ARE YOU SURE YOU WANT TO ABORT? Energy will not be refunded.",
      )
    ) {
      setActiveDungeonSession(null);
    }
  };

  if (activeDungeonSession) {
    return (
      <DungeonScreen
        session={activeDungeonSession}
        socket={socket}
        onExit={handleAbortMission}
      />
    );
  }

  const tabs = {
    dashboard: <DashboardTab />,
    dungeons: <DungeonsTab startDungeon={handleStartDungeon} />,
    skills: <SkillsTab />,
    base: <BaseTab />,
    quests: <QuestsTab />,
    inventory: <InventoryTab />,
    shop: <ShopTab />,
    crafting: <CraftingTab />,
    itemlist: <ItemListTab />,
    chat: <ChatTab />,
    notifications: <Notification />,
  };

  return (
    <div id="gameInterface" className="game-interface">
      <GameHeader onReturn={onExit} />
      <Navigation activeTab={activeTab} onTabChange={setActiveTab} />
      <main className="main-content">
        {tabs[activeTab] || <DashboardTab />}
      </main>
      <Console />
    </div>
  );
};

export default GameInterface;
