import React, { useState, useEffect, useRef } from "react";
import GameDataManager from "../../../services/GameDataManager.js";
import "./DungeonScreen.css";
import DungeonFinish from "../tabs/components/DungeonFinish.jsx";

const DungeonScreen = ({ session, socket }) => {
  const [battle, setBattle] = useState(session.battle || null);
  const [roomIndex, setRoomIndex] = useState(session.roomIndex);
  const [totalRooms, setTotalRooms] = useState(session.totalRooms || 1);
  const [timeLeft, setTimeLeft] = useState(10);
  const [summary, setSummary] = useState(null);
  const [activeAttacker, setActiveAttacker] = useState(null);
  const [selectedTarget, setSelectedTarget] = useState(null);
  const [log, setLog] = useState([
    "SYSTEM: Neural link established. Scanning sector...",
  ]);

  const logEndRef = useRef(null);
  const timerRef = useRef(null);

  const addLog = (text) => {
    const time = new Date().toLocaleTimeString([], {
      hour12: false,
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
    setLog((prev) => [...prev, `[${time}] ${text}`]);
  };

  useEffect(() => {
    logEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [log]);

  useEffect(() => {
    if (!battle || battle.isOver || activeAttacker) {
      if (timerRef.current) clearInterval(timerRef.current);
      return;
    }

    const isPlayer = battle.turnOrder[battle.currentTurnIndex] === "player";
    if (!isPlayer) return;

    setTimeLeft(10);
    if (timerRef.current) clearInterval(timerRef.current);

    timerRef.current = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 1) {
          handleCombatAction(null);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timerRef.current);
  }, [battle?.currentTurnIndex, battle?.isOver, activeAttacker]);

  useEffect(() => {
    socket.on("dungeon:battle_update", async (data) => {
      if (data.log && Array.isArray(data.log)) {
        for (const action of data.log) {
          if (typeof action === "object" && action.attackerId) {
            setActiveAttacker(action.attackerId);
            action.messages?.forEach((msg) => addLog(msg));

            if (action.hpState) {
              setBattle((prev) => ({
                ...prev,
                player: { ...prev.player, hp: action.hpState.playerHp },
                enemies: prev.enemies.map((e) => {
                  const s = action.hpState.enemies.find(
                    (ae) => ae.id === e.instanceId,
                  );
                  return s ? { ...e, hp: s.hp, isDead: s.isDead } : e;
                }),
              }));
            }
            await new Promise((r) => setTimeout(r, 1500));
          } else if (typeof action === "string") {
            addLog(action);
          }
        }
      }

      setBattle(data.battle);
      setActiveAttacker(null);
      setSelectedTarget(null);

      if (data.status === "victory")
        addLog("MISSION_OBJECTIVE: Threats neutralized.");
      if (data.status === "defeat") {
        addLog("CRITICAL_ERROR: Bio-sign lost.");
        setTimeout(() => window.location.reload(), 3000);
      }
    });

    socket.on("dungeon:room_update", (data) => {
      setRoomIndex(data.roomIndex);
      setTotalRooms(data.totalRooms);
      setBattle(data.battle);
      addLog(`--- ENTERING SECTOR ${data.roomIndex + 1} ---`);
    });

    socket.on("dungeon:completed", (data) => {
      setSummary(data.rewards);
      addLog("MISSION_SUCCESS: All objectives secured.");
    });

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

  const handleCombatAction = (targetId = selectedTarget) => {
    const isPlayer = battle?.turnOrder[battle?.currentTurnIndex] === "player";
    if (!battle || battle.isOver || activeAttacker || !isPlayer) return;

    socket.emit("dungeon:combat_action", { targetInstanceId: targetId });
    if (!targetId) addLog("Sequence timeout! Skipping...");
    else addLog("Initiating strike sequence...");
    setSelectedTarget(null);
  };

  const handleNextRoom = () => {
    socket.emit("dungeon:next_room");
  };

  const isPlayerTurn =
    battle?.turnOrder[battle?.currentTurnIndex] === "player" &&
    !activeAttacker &&
    !battle.isOver;

  return (
    <div className="dungeon-active-screen">
      {summary && (
        <DungeonFinish
          rewards={summary}
          onExit={() => window.location.reload()}
        />
      )}

      <div className="dungeon-header">
        <div className="room-progress">
          <div className="progress-text">
            SECTOR {roomIndex + 1} / {totalRooms}
          </div>
          <div className="progress-bar">
            <div
              className="fill"
              style={{ width: `${((roomIndex + 1) / totalRooms) * 100}%` }}
            ></div>
          </div>
        </div>

        {battle && !battle.isOver && (
          <div
            className={`turn-progress-container ${isPlayerTurn ? "player-phase" : "enemy-phase"}`}
          >
            <div className="turn-label">
              {isPlayerTurn ? "YOUR TURN" : "PROCESSING..."}
            </div>
            <div className="turn-timer-bar">
              <div
                className="turn-timer-fill"
                style={{
                  width: `${(timeLeft / 10) * 100}%`,
                  transition: timeLeft === 10 ? "none" : "width 1s linear",
                  visibility: isPlayerTurn ? "visible" : "hidden",
                }}
              />
            </div>
          </div>
        )}
      </div>

      <div className="battle-arena">
        {battle ? (
          <div className="mobs-grid">
            {battle.enemies.map((mob) => (
              <div
                key={mob.instanceId}
                className={`enemy-card ${mob.isDead ? "defeated" : ""} ${selectedTarget === mob.instanceId ? "selected" : ""} ${isPlayerTurn && !mob.isDead ? "selectable" : ""} ${activeAttacker === mob.instanceId ? "attacking" : ""}`}
                onClick={() =>
                  isPlayerTurn &&
                  !mob.isDead &&
                  setSelectedTarget(mob.instanceId)
                }
              >
                <div className="enemy-hp-mini">
                  <div
                    className="fill"
                    style={{ width: `${(mob.hp / mob.maxHp) * 100}%` }}
                  />
                </div>
                <div className="enemy-icon">
                  <i
                    className={`fas ${mob.isDead ? "fa-skull-crossbones" : "fa-robot"}`}
                  ></i>
                </div>
                <span className="mob-name">{GameDataManager.t(mob.name)}</span>
              </div>
            ))}
          </div>
        ) : (
          <div className="empty-room">
            <i className="fas fa-satellite-dish"></i>
            <p>AREA SECURE</p>
          </div>
        )}
      </div>

      <div className="player-section">
        {battle && (
          <div
            className={`player-hp-main ${activeAttacker && activeAttacker !== "player" ? "taking-damage" : ""}`}
          >
            <div className="hp-header">
              <span>COMMANDER_INTEGRITY</span>
              <span>
                {battle.player.hp} / {battle.player.maxHp}
              </span>
            </div>
            <div className="hp-bar-large">
              <div
                className="fill"
                style={{
                  width: `${(battle.player.hp / battle.player.maxHp) * 100}%`,
                }}
              />
            </div>
          </div>
        )}
        <div className="combat-interface-row">
          <div className="combat-log custom-scroll">
            {log.map((entry, i) => (
              <div key={i} className="log-entry">
                <span className="log-arrow">&gt;</span> {entry}
              </div>
            ))}
            <div ref={logEndRef} />
          </div>
          {battle && !battle.isOver && (
            <button
              className={`btn-execute-combat ${!selectedTarget || !isPlayerTurn ? "disabled" : ""}`}
              disabled={!selectedTarget || !isPlayerTurn}
              onClick={() => handleCombatAction()}
            >
              EXECUTE_STRIKE
            </button>
          )}
        </div>
      </div>

      <div className="dungeon-controls">
        {((battle?.isOver && battle.player.hp > 0) || !battle) && !summary && (
          <button className="ctrl-btn next" onClick={handleNextRoom}>
            PROCEED <i className="fas fa-chevron-right"></i>
          </button>
        )}
      </div>
    </div>
  );
};

export default DungeonScreen;
