import React, { useState, useRef, useEffect } from "react";
import smoothScroll from "smooth-scroll-into-view-if-needed";
import "./ItemTypeLister.css";
import ItemType from "./ItemType";
import { createItem } from "../helpers/itemHelper.js";
import { getImageUrl } from "../helpers/itemHelper";
import ItemLister from "./ItemLister";

const ItemTypeLister = ({
  shopId,
  shopOwnerId,
  user,
  setShopItems,
  itemTypes,
  onFilterChange,
  filterId,
  isEditMode,
  beingEditedType,
  setBeingEditedType,
}) => {
  const [isAddingNewItem, setIsAddingNewItem] = useState(false);
  const newItemDivRef = useRef(null);
  const [items, setItems] = useState([]);

  // Effect to handle changes to isAddingNewItem
  useEffect(() => {
    if (isAddingNewItem && newItemDivRef.current) {
      // Use smooth-scroll-into-view-if-needed to scroll to the target div
      smoothScroll(newItemDivRef.current, {
        behavior: "smooth",
        block: "start", // Adjust this based on your needs
        inline: "nearest",
      });
    } else {
      const node = document.getElementById("header");

      smoothScroll(node, {
        behavior: "smooth",
        block: "start", // Adjust this based on your needs
        inline: "nearest",
      });
    }
  }, [isAddingNewItem]); // Dependency array includes isAddingNewItem

  const toggleAddNewItem = () => {
    setIsAddingNewItem((prev) => !prev);

    // Set body overflow style based on state
    document.body.style.overflow = !isAddingNewItem ? "hidden" : "auto";
  };

  // Removed legacy image upload logic used by the old tile view
  
  const canManage = user && (user.user_id == shopOwnerId || user.cafeId == shopId);

  const formatName = (name) => {
    if (!name) return name;
    return name
      .toLowerCase()
      .replace(/\b\w/g, (c) => c.toUpperCase());
  };

  return (
    <div className="item-type-lister" style={{ overflowX: isAddingNewItem ? 'hidden' : 'auto' }}>
      <div ref={newItemDivRef} className="item-type-list" style={{ display: 'inline-flex' }}>
        {isEditMode && !isAddingNewItem && canManage && (
          <ItemType
            onClick={toggleAddNewItem}
            name={"buat baru"}
            imageUrl={"icon:plus"}
          />
        )}

        {canManage && isAddingNewItem && (
          <ItemLister
            shopId={shopId}
            shopOwnerId={shopOwnerId}
            user={user}
            typeName={""}
            setShopItems={setShopItems}
            itemList={items}
            isEditMode={true}
            handleCreateItem={(itemTypeId, name, price, selectedImage, description, promoPrice) => createItem(shopId, name, price, selectedImage, itemTypeId, description, promoPrice)}
            beingEditedType={beingEditedType}
            setBeingEditedType={setBeingEditedType}
            alwaysEdit={true}
            handleUnEdit={toggleAddNewItem}
          />
        )}

        {itemTypes && itemTypes.length > 0 && (
          <ItemType
            name={"semua"}
            onClick={() => onFilterChange(0)}
            imageUrl={"icon:all"}
            selected={filterId === 0}
          />
        )}

        {itemTypes && itemTypes.map((itemType) => (
          <ItemType
            key={itemType.itemTypeId}
            name={itemType.name}
            imageUrl={"icon:category"}
            onClick={() => onFilterChange(itemType.itemTypeId)}
            selected={filterId === itemType.itemTypeId}
          />
        ))}
      </div>
    </div>
  );
};

export default ItemTypeLister;
