import React, { useState, useEffect } from "react";
import { useSocket } from "../../../hooks/useSocket";
import GameDataManager from "../../../services/GameDataManager.js";
import Button from "../../../components/ui/Button";
import "./styles/InventoryTab.css";
import { getServerUrl } from "../../../config/api.js";

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 equipmentSlots = {
    personal: [
      { id: "personal_helmet", label: "HELMET" },
      { id: "personal_suit", label: "SUIT" },
      { id: "personal_gloves", label: "GLOVES" },
      { id: "personal_boots", label: "BOOTS" },
      { id: "personal_backpack", label: "BACKPACK" },
      { id: "personal_weapons", label: "WEAPON" },
    ],
    ship: [
      { id: "ship_hull", label: "HULL" },
      { id: "ship_shields", label: "SHIELDS" },
      { id: "ship_engines", label: "ENGINES" },
    ],
  };

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

  const enrichItemData = (serverItem) => {
    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",
    };
  };

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

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

    refresh();

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

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

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

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

  const handleItemClick = (item) => {
    setSelectedItem(item);
    setShowModal(true);
  };

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

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

  const renderSlotGroup = (title, groupSlots) => (
    <div className="equip-group">
      <div className="group-label">{title}</div>
      <div className="equip-list-compact">
        {groupSlots.map((slot) => (
          <div
            key={slot.id}
            className={`equip-row-mini ${equipment[slot.id] ? "occupied" : ""}`}
            onClick={() => equipment[slot.id] && unequipItem(slot.id)}
          >
            <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}
                  alt={slot.id}
                  className="item-img-mini"
                />
              ) : (
                <span className="plus">+</span>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="inv-adaptive-container">
      <div className="inv-header-compact">
        <h2 className="inv-logo">TACTICAL_INVENTORY_V2</h2>
        <div className="inv-stats-bar">
          <span>
            LOAD: <span className="text-cyan">{items.length}/50</span>
          </span>
        </div>
      </div>

      <div className="inv-layout-wrapper">
        <section className="inv-panel loadout">
          <div className="panel-label">CORE_SYSTEMS</div>

          {renderSlotGroup("PERSON", equipmentSlots.personal)}
          {renderSlotGroup("SHIP", equipmentSlots.ship)}
        </section>

        <section className="inv-panel cargo">
          <div className="panel-label">STORAGE_UNITS</div>
          <div className="cargo-grid-v2">
            {items.map((item, idx) => (
              <div
                key={`${item.id}-${idx}`}
                className={`item-slot ${item.rarity} ${selectedItem?.id === item.id ? "active" : ""}`}
                onClick={() => handleItemClick(item)}
              >
                <img
                  src={item.textureUrl}
                  alt="item"
                  width={62}
                  className="item-img-grid"
                />
                {item.quantity > 1 && (
                  <span className="qty-label">{item.quantity}</span>
                )}
              </div>
            ))}
          </div>
        </section>
      </div>

      {showModal && selectedItem && (
        <div className="inv-modal-overlay" onClick={() => setShowModal(false)}>
          <div className="inv-modal-box" onClick={(e) => e.stopPropagation()}>
            <div className={`modal-header-scan ${selectedItem.rarity}`}>
              <div className="modal-preview-icon">
                <img src={selectedItem.textureUrl} alt="preview" width={32} />
              </div>
              <h3>{selectedItem.displayName || selectedItem.id}</h3>
            </div>

            <div className="modal-body-scan">
              <p className="description-text">
                {selectedItem.description || "No data available."}
              </p>

              <div className="stats-scanner">
                {selectedItem.stats &&
                  Object.entries(selectedItem.stats).map(([k, v]) => (
                    <div key={k} className="stat-line">
                      <span className="label">
                        {GameDataManager.getStatName?.(k)?.toUpperCase() ||
                          k.toUpperCase()}
                      </span>
                      <span className="value">+{v}</span>
                    </div>
                  ))}
              </div>

              {selectedItem.canEquip && (
                <Button
                  variant="primary"
                  className="modal-equip-btn"
                  onClick={() => equipItem(selectedItem)}
                >
                  INITIALIZE_EQUIP
                </Button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default InventoryTab;
