import { useState } from "react";
import AddImageModal from "./AddImageModal";
import ConfirmBuyModal from "./ConfirmBuyModal";
import ImageModal from "./ImageModal";

export default function GroceryListItem({ item, onClick, onImageAdded }) {
  const [showModal, setShowModal] = useState(false);
  const [showAddImageModal, setShowAddImageModal] = useState(false);
  const [showConfirmBuyModal, setShowConfirmBuyModal] = useState(false);

  const handleItemClick = () => {
    setShowConfirmBuyModal(true);
  };

  const handleConfirmBuy = (quantity) => {
    if (onClick) {
      onClick(quantity);
    }
    setShowConfirmBuyModal(false);
  };

  const handleCancelBuy = () => {
    setShowConfirmBuyModal(false);
  };

  const handleImageClick = (e) => {
    e.stopPropagation(); // Prevent triggering the bought action
    if (item.item_image) {
      setShowModal(true);
    } else {
      setShowAddImageModal(true);
    }
  };

  const handleAddImage = async (imageFile) => {
    if (onImageAdded) {
      await onImageAdded(item.id, item.item_name, item.quantity, imageFile);
    }
    setShowAddImageModal(false);
  };

  const imageUrl = item.item_image && item.image_mime_type
    ? `data:${item.image_mime_type};base64,${item.item_image}`
    : null;

  return (
    <>
      <li className="glist-li" onClick={handleItemClick}>
        <div className="glist-item-layout">
          <div
            className={`glist-item-image ${item.item_image ? "has-image" : ""}`}
            onClick={handleImageClick}
            style={{ cursor: "pointer" }}
          >
            {item.item_image ? (
              <img src={imageUrl} alt={item.item_name} />
            ) : (
              <span>📦</span>
            )}
            <span className="glist-item-quantity">x{item.quantity}</span>
          </div>
          <div className="glist-item-content">
            <div className="glist-item-header">
              <span className="glist-item-name">{item.item_name}</span>
            </div>
            {item.added_by_users && item.added_by_users.length > 0 && (
              <div className="glist-item-users">
                {item.added_by_users.join(", ")}
              </div>
            )}
          </div>
        </div>
      </li>

      {showModal && (
        <ImageModal
          imageUrl={imageUrl}
          itemName={item.item_name}
          onClose={() => setShowModal(false)}
        />
      )}

      {showAddImageModal && (
        <AddImageModal
          itemName={item.item_name}
          onClose={() => setShowAddImageModal(false)}
          onAddImage={handleAddImage}
        />
      )}

      {showConfirmBuyModal && (
        <ConfirmBuyModal
          item={item}
          onConfirm={handleConfirmBuy}
          onCancel={handleCancelBuy}
        />
      )}
    </>
  );
}
