import React from 'react'
import {Droppable} from "@hello-pangea/dnd";
import {cartStyle} from "./utils";
import {ProductCartItem} from "./ProductCartItem";
import {FakePlaceholder} from "./FakePlaceholder";
import {FillExtData} from "./options/utils";
import {hp_to_slots} from "./count_resources";
import {useShopStore} from "./shop_store";
import {useRenderCount} from "@uidotdev/usehooks";
import {useShallow} from "zustand/react/shallow";

/**
 * Component that displays a list of <ProductCartItem>
 */
export function Cart({crate_index}) {
    const renderCount = useRenderCount();

    const crate = useShopStore(useShallow((state) => state.crates[crate_index]), (a, b) => {
        return a.items.length === b.items.length && a.occupiedHP === b.occupiedHP && a.crate_mode === b.crate_mode
    });
    const crateParams = useShopStore((state) => state.crateParams);

    console.log("Cart renders: ", renderCount)

    const nbrOccupied = hp_to_slots(crate.occupiedHP);
    const nbrSlots = hp_to_slots(crateParams(crate.crate_mode).hp);

    const products = crate.items.map((item, index) => {
        const ext_data = FillExtData(crate.items, index);
        return (
            <ProductCartItem
                card_index={index}
                crate_index={crate_index}
                ext_data={ext_data}
                first={index === 0}
                last={index === crate.items.length - 1 && nbrOccupied >= nbrSlots}
                key={item.id}/>
        );
    });

    return (
        <Droppable droppableId={crate.id} direction="horizontal">

            {(provided, snapshot) => (
                <div
                    ref={provided.innerRef}
                    {...provided.droppableProps}
                    style={cartStyle(
                        provided.droppableProps.style,
                        snapshot,
                    )}
                    className="items-cart-list">

                    {products}

                    {provided.placeholder && (
                        <div style={{display: 'none'}}>
                            {provided.placeholder}
                        </div>
                    )}

                    <FakePlaceholder
                        nToDraw={nbrSlots - nbrOccupied}
                        isDraggingOver={snapshot.isDraggingOver}/>
                </div>
            )}

        </Droppable>
    );
}