import React, {FC, useCallback} from "react";
import {BuyXGetYOptions, ProductData} from "./BuyXGetY";
import {BuyXGetYNoProductsData} from "./BuyXGetYNoProductsData";
import {CustomProductOptionValue, CustomProductsFieldLabel} from "./Products";
import {fieldsCacheContainer} from "../FieldsCache";
import {SelectOption} from "../fields/MultiSelectSearch";
import {__} from "../../globals";
import {DiscountValue} from "./DiscountValue";
import {GetYAddProductToDiscountButton} from "./GetYAddProductToDiscountButton";
import {EmulatedButton} from "../EmulatedButton";
import {
    applyGetYProductDataUpdate,
    useOpenBuyXGetYProductPopupFlow,
    useRegisterBuyXGetYProductPopupResultHandler
} from "./BuyXGetYProductPopupFlow";

export type BuyXGetYProductsFieldsProps = {
    offerId: string,
    options: BuyXGetYOptions,
    onUpdate: (data: ProductData) => void
}

export const BuyXGetYProductsFields: FC<BuyXGetYProductsFieldsProps> = ({offerId, options: {data}, onUpdate}) => {
    const existingData = data as ProductData
    const remove = indexToRemove => onUpdate(
        existingData.filter((item, index) => index !== indexToRemove)
    )

    const onSuccess = useCallback((newData) => {
        onUpdate(applyGetYProductDataUpdate(existingData, newData))
    }, [existingData, onUpdate])
    useRegisterBuyXGetYProductPopupResultHandler({
        offerId,
        onSuccess,
    })
    const openProductPopup = useOpenBuyXGetYProductPopupFlow({
        offerId,
        onSuccess,
    })

    const openEditPopup = (item, index: number) => {
        openProductPopup({
            index,
            data: item,
        })
    }
    if (!(existingData as ProductData)?.length) {
        return <BuyXGetYNoProductsData onSuccess={onSuccess}/>
    }

    return <div className="space-y-3">
        <div className="">
            {existingData.map((item, index) => (
                <>
                    <div className="space-y-1">
                        <p className="text-smaller-1 text-gray-400">{item.missingItemsInCart.mode === 'auto-add' ? __('Automatically applied') : __('Manually applied')}</p>
                        <div className="relative flex items-center justify-between rounded-2 border-px border-gray-200 px-3 py-2 hover:cursor-pointer  duration-150 active:scale-[.98] transition ease" onClick={() => {openEditPopup(item, index)}}>
                            {/*@ts-ignore*/}
                            <CustomProductsFieldLabel {...fieldsCacheContainer.get('products').get<SelectOption<CustomProductOptionValue>>(item.id)} />
                            <div className="grid gap-y-1 gap-x-4 px-3 py-2 rounded-3 bg-gray-150/40" style={{gridTemplateColumns: 'max-content max-content'}}>
                                <h3 className="text-smaller-3 text-gray-350">{__('Qty')}</h3>
                                <h3 className="text-smaller-3 text-gray-350">{__('Discount')}</h3>
                                <div className="text-base font-semibold text-gray-750">{item.qtyType === 'advanced' && item?.qty?.type === 'any'? <span className="uppercase">{__('unlimited')}</span> : item.quantity}</div>
                                <div className="text-base font-semibold text-gray-750"><DiscountValue
                                    productDiscountOptions={item} size={'small'}/></div>
                            </div>
                            <div className="absolute right-0 -top-1 -translate-y-full">
                                <EmulatedButton onClickCapture={(event) => {
                                    event.stopPropagation() // prevent the parent on click from firing and thus opening the edit popup on the sibling remaining product (bubbling)
                                    remove(index)
                                }}>
                                    <div className="w-4 h-4 flex items-center justify-center rounded-full group bg-gray-200 hover:bg-gray-250 bg-opacity-80 hover:scale-[1.15] active:scale-[.96] transition-all ease">
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                                             className="w-3 h-3 text-gray-450 group-hover:text-gray-500">
                                            <path fillRule="evenodd"
                                                  d="M5.47 5.47a.75.75 0 0 1 1.06 0L12 10.94l5.47-5.47a.75.75 0 1 1 1.06 1.06L13.06 12l5.47 5.47a.75.75 0 1 1-1.06 1.06L12 13.06l-5.47 5.47a.75.75 0 0 1-1.06-1.06L10.94 12 5.47 6.53a.75.75 0 0 1 0-1.06Z"
                                                  clipRule="evenodd"/>
                                        </svg>
                                    </div>
                                </EmulatedButton>
                            </div>
                        </div>
                    </div>
                    <div className="flex w-full items-center justify-center h-[12px] text-5x font-medium text-gray-450 last:hidden mt-2">+</div>
                </>
            ))}
        </div>
        <GetYAddProductToDiscountButton onSuccess={onSuccess} primary={false} small={true} />
    </div>
}
