import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import { useSocket } from "../../../hooks/useSocket";
import GameDataManager from "../../../services/GameDataManager.js";
import ItemModal from "./components/ItemModal";
import "./styles/InventoryTab.css";
import { getServerUrl } from "../../../config/api.js";
import MeteorRegion from "../../../components/Meteor/MeteorRegion.jsx";

const InventoryTab = () => {
  const { socket } = useSocket();
  const [items, setItems] = useState([]);
  const [equipment, setEquipment] = useState({});
  const [selectedItem, setSelectedItem] = useState(null);
  const [showModal, setShowModal] = useState(false);

  const CONNECT_URL = getServerUrl();
  const ASSET_BASE_URL = `${CONNECT_URL}/static/`;

  const manifest = GameDataManager.manifest || {};
  const coreSystems = manifest.core_systems?.categories || {};

  const getFullTextureUrl = (path) => {
    if (!path) return "/assets/no-image.png";
    if (path.startsWith("http")) return path;
    return `${ASSET_BASE_URL}${path}`;
  };

  const enrichItemData = (serverItem, currentSlot = null) => {
    if (!serverItem || (!serverItem.itemId && !serverItem.id)) return null;
    const id = serverItem.itemId || serverItem.id;
    const staticData = GameDataManager.getItem(id);
    return {
      ...serverItem,
      ...staticData,
      id: id,
      textureUrl: getFullTextureUrl(staticData?.texture),
      canEquip: !!staticData?.meta?.equipmentSlot,
      rarity: staticData?.meta?.rarity || "common",
      currentSlot: currentSlot,
    };
  };

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

    const refreshData = () => {
      socket.emit("player:get_inventory");
      socket.emit("player:get_equipment");
    };

    refreshData();

    const handleInventory = (rawItems) => {
      setItems(rawItems.map((item) => enrichItemData(item)).filter(Boolean));
    };

    const handleEquipment = (rawEquip) => {
      const mapped = {};
      Object.keys(rawEquip).forEach((slot) => {
        if (rawEquip[slot]) {
          mapped[slot] = enrichItemData({ itemId: rawEquip[slot] }, slot);
        }
      });
      setEquipment(mapped);
    };

    socket.on("player:inventory_data", handleInventory);
    socket.on("player:equipment_data", handleEquipment);
    socket.on("player:item_equipped", refreshData);
    socket.on("player:item_unequipped", refreshData);

    return () => {
      socket.off("player:inventory_data", handleInventory);
      socket.off("player:equipment_data", handleEquipment);
      socket.off("player:item_equipped", refreshData);
      socket.off("player:item_unequipped", refreshData);
    };
  }, [socket]);

  const equipItem = (item) => {
    const slot = item.meta?.equipmentSlot;
    if (slot) socket.emit("player:equip_item", { itemId: item.id, slot });
  };

  const unequipItem = (slot) => {
    socket.emit("player:unequip_item", { slot });
  };

  const equipmentSlots = {
    personal: Object.keys(coreSystems)
      .filter(
        (k) =>
          k.startsWith("original:personal_") &&
          !k.includes("accessory") &&
          k !== "original:personal_weapons",
      )
      .map((k) => ({
        id: k,
        label: GameDataManager.t(coreSystems[k].displayName),
      })),
    weapons: Object.keys(coreSystems)
      .filter((k) => k === "original:personal_weapons")
      .map((k) => ({
        id: k,
        label: GameDataManager.t(coreSystems[k].displayName),
      })),
    accessories: Object.keys(coreSystems)
      .filter((k) => k.includes("personal_accessory"))
      .map((k) => ({
        id: k,
        label: GameDataManager.t(coreSystems[k].displayName),
      })),
    ship: Object.keys(coreSystems)
      .filter((k) => k.startsWith("original:ship_"))
      .map((k) => ({
        id: k,
        label: GameDataManager.t(coreSystems[k].displayName),
      })),
  };

  const renderSlotGroup = (title, groupSlots) => (
    <div className="equip-group">
      <div className="group-label">{title}</div>
      <div className="equip-list-compact grid-config">
        {groupSlots.map((slot) => (
          <div
            key={slot.id}
            className={`equip-row-mini ${equipment[slot.id] ? "occupied" : ""}`}
            onClick={() =>
              equipment[slot.id] &&
              (setSelectedItem(equipment[slot.id]), setShowModal(true))
            }
          >
            <span className="slot-name-tiny">{slot.label}</span>
            <div
              className={`equip-box-mini ${equipment[slot.id]?.rarity || ""}`}
            >
              {equipment[slot.id] ? (
                <img
                  src={equipment[slot.id].textureUrl}
                  className="item-img-mini"
                />
              ) : (
                <span className="plus">+</span>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="inv-adaptive-container">
      <div className="inv-layout-wrapper">
        <section className="inv-panel loadout">
          <MeteorRegion>
            {renderSlotGroup("SUIT_GEAR", equipmentSlots.personal)}
            {renderSlotGroup("WEAPONRY", equipmentSlots.weapons)}
            {renderSlotGroup("ACCESSORIES", equipmentSlots.accessories)}
            <div className="separator" />
            {renderSlotGroup("SHIP_MODULES", equipmentSlots.ship)}
          </MeteorRegion>
        </section>

        <section className="inv-panel cargo">
          <MeteorRegion>
            <div className="cargo-grid-v2">
              {items.map((item, idx) => {
                const isEquipped = Object.values(equipment).some(
                  (e) => e?.id === item.id,
                );
                return (
                  <div
                    key={`${item.id}-${idx}`}
                    className={`item-slot ${item.rarity} ${isEquipped ? "equipped-in-storage" : ""}`}
                    onClick={() => {
                      setSelectedItem(item);
                      setShowModal(true);
                    }}
                  >
                    <img
                      src={item.textureUrl}
                      width={62}
                      className="item-img-grid"
                    />
                    {isEquipped && <div className="equipped-tag">E</div>}
                    {item.quantity > 1 && (
                      <span className="qty-label">{item.quantity}</span>
                    )}
                  </div>
                );
              })}
            </div>
          </MeteorRegion>
        </section>
      </div>

      {showModal &&
        selectedItem &&
        ReactDOM.createPortal(
          <ItemModal
            item={selectedItem}
            isEquipped={
              !!selectedItem.currentSlot ||
              Object.values(equipment).some((e) => e?.id === selectedItem.id)
            }
            onClose={() => {
              setShowModal(false);
              setSelectedItem(null);
            }}
            onEquip={equipItem}
            onUnequip={(slot) => {
              const actualSlot =
                slot ||
                Object.keys(equipment).find(
                  (k) => equipment[k].id === selectedItem.id,
                );
              unequipItem(actualSlot);
            }}
            formatStatName={(n) => GameDataManager.getStatName(n).toUpperCase()}
            getStatIcon={(n) => GameDataManager.getStatIcon?.(n)}
          />,
          document.body,
        )}
    </div>
  );
};

export default InventoryTab;
