import React from "react";
import "./ItemModal.css";
import { getServerUrl } from "../../../../config/api";

const ItemModal = ({
  item,
  onClose,
  onEquip,
  onUnequip,
  isEquipped,
  getStatIcon,
  formatStatName,
}) => {
  if (!item) return null;

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

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

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div
        className="datapack-modal-content"
        onClick={(e) => e.stopPropagation()}
      >
        <button className="modal-close" onClick={onClose}>
          &times;
        </button>

        <div className="modal-header">
          <div className={`modal-icon-big ${item.rarity}`}>
            <img src={getFullTextureUrl(item.texture)} alt={item.displayName} />
          </div>
          <div className="modal-title-group">
            <h3 className={item.rarity}>{item.displayName || item.name}</h3>
            <div className="modal-raw-id">
              {item.rarity?.toUpperCase()} SYSTEM_ID: {item.id}
            </div>
          </div>
        </div>

        <div className="details-section">
          <p className="details-description">{item.description}</p>
        </div>

        <div className="details-section">
          <h4>
            <i className="fas fa-microchip"></i> Technical Specs
          </h4>
          <div className="item-stats-container">
            {item.stats &&
              Object.entries(item.stats).map(([statName, value]) => (
                <div key={statName} className="stat-row">
                  <span className="stat-label">
                    <i className={getStatIcon?.(statName)}></i>{" "}
                    {formatStatName
                      ? formatStatName(statName)
                      : statName.toUpperCase()}
                  </span>
                  <span className="stat-value">+{value}</span>
                </div>
              ))}
          </div>
        </div>

        <div className="modal-actions" style={{ marginTop: "20px" }}>
          {isEquipped ? (
            <button
              className="btn-equip unequip"
              onClick={() => {
                onUnequip(item.currentSlot);
                onClose();
              }}
            >
              TERMINATE_CONNECTION
            </button>
          ) : (
            item.canEquip && (
              <button
                className="btn-equip"
                onClick={() => {
                  onEquip(item);
                  onClose();
                }}
              >
                INITIALIZE_EQUIP
              </button>
            )
          )}
        </div>
      </div>
    </div>
  );
};

export default ItemModal;
