import React, {FC, useEffect, useState} from "react";
import {MultiSelect} from "./fields/MultiSelect";
import {ProductsFieldProps} from "./cards/Products";
import {__, CouponsPlus} from "../globals";
import {MultiSelectSearch} from "./fields/MultiSelectSearch";
import {mapLocalMetaFieldOptions} from "./cards/FieldHelpers";
import {NumberInput, NumberInputProps} from "./fields/NumberInput";
import {getBOGOOfferNumberInputProps, getNumberContainerClasses} from "./fields/NumberFieldUtils";
import {Tabs} from "./fields/tabs";
import {mapFromMeta} from "./fields/TabHelpers";
import {BuyXGetXOptions, Qty, qtyType} from "./cards/BuyXGetX";
import {BuyXGetYSpecificProductWindowContextData} from "./atoms";

export type BuyXGetYSpecificProductConfigFieldsProps = {
    context?: BuyXGetYSpecificProductWindowContextData | null
    onDataModified: (data: Required<Pick<BuyXGetYSpecificProductWindowContextData, 'data'>>['data']) => void
}

const qtyTypesOptions = [
    {
        id: 'simple',
        value: 'simple',
        label: __('Fixed Qty.'),
    },
    {
        id: 'advanced',
        value: 'advanced',
        label: __('Any Qty.'),
    }
]

export const BuyXGetYSpecificProductConfigFields: FC<BuyXGetYSpecificProductConfigFieldsProps> = ({context, onDataModified}) => {
    const [productId, setProductId] = useState<string | null>(context?.data?.id ?? null);
    const [isVariable, setIsVariable] = useState<boolean>(context?.data?.isVariable ?? false);
    const [quantity, setQuantity] = useState<number>(context?.data?.quantity ?? 1);
    const [qtyType, setQtyType] = useState<qtyType>(context?.data?.qtyType ?? 'simple');
    const [qty, setQty] = useState<Qty>(context?.data?.qty ?? {type: 'any', amount: 1});
    const [discountType, setDiscountType] = useState<BuyXGetXOptions['discount']['type']>(context?.data?.discount?.type ?? 'free');
    const [discountAmount, setDiscountAmount] = useState<number>(context?.data?.discount?.amount ?? 100);
    const [notInCartMode, setNotInCartMode] = useState<BuyXGetXOptions['missingItemsInCart']['mode']>(context?.data?.missingItemsInCart.mode ?? 'auto-add');

    useEffect(() => {
        // when type changes to advanced, change apply mode to manual
        if (qtyType === 'advanced' && notInCartMode !== 'manual-add') {
            setNotInCartMode('manual-add');
        }
    }, [qtyType])
    useEffect(() => {
        onDataModified({
            ...(context?.data || {}),
            // @ts-ignore
            id: productId,
            isVariable,
            quantity,
            qtyType,
            qty,
            discount: {
                type: discountType,
                amount: discountAmount
            },
            missingItemsInCart: {
                mode: notInCartMode
            }
        })
    }, [productId, isVariable, quantity, discountType, discountAmount, notInCartMode, qtyType, qty])

    let inputtype = ({
        free: 'free',
        ["percentage"]: 'percentage',
        ["amount"]: "currency",
        ["fixed-price"]: "currency",
    } as Record<typeof discountType, NumberInputProps['type']>)[discountType];

    return <div className={'space-y-4 w-110 overflow-y-scroll'}>
        <MultiSelect options={CouponsPlus.components.offers.BuyXGetY.fields.data.meta.__allowed}
                     value={[productId].filter(value => value) as string[]}
                     onSelectedValue={(value) => {
                         setProductId(value.id)
                         setIsVariable(value.value.option.isVariable)
                     }}
                     onRemovedValue={() => {
                     }}
                     {...ProductsFieldProps({
                         SelectSearchProps: {
                             placeholder: () => productId ? __('Search to replace selected product...') : __('Search product to discount...'),
                         }
                     })}
        />
        {productId && <div className={'space-y-4'}>
            <div className="flex items-start justify-center gap-2 px-6 py-10 bg-gray-250/10 rounded-[28px]">
                <div className={getNumberContainerClasses({border: false})}>
                    <NumberInput numberId={'buyxgety.discount.quantity'}
                                 value={quantity}
                                 onChange={setQuantity}
                                 fieldType={'text'}
                                 type={qtyType == 'advanced' ? 'custom' : undefined}
                                 customRenderer={<div className={"flex flex-col gap-0 items-center"}>
                                     {qtyType === 'advanced' && <p className="uppercase text-4x">{__('Unlimited')}</p>}
                                     {qtyType === 'advanced' && <p className="text-smaller-2 text-gray-300 mt-0 font-normal">{__('Manual only')}</p>}
                                 </div>}
                                 input={{
                                     top:() => <div className="">
                                         <MultiSelectSearch size={'extra-small'}
                                                            style={'gray-lighter'}
                                                            options={qtyTypesOptions}
                                                            selectedValue={qtyType}
                                                            onSelectedValue={({id}) => {
                                                                setQtyType(id as qtyType)
                                                            }}
                                        />
                                     </div>

                                 }}
                                 labels={{
                                     //top: __('Quantity'),
                                 }}
                    />
                </div>
                <div className={getNumberContainerClasses({border: false})}>
                    <MultiSelectSearch size={'extra-small'}
                                       style={'gray-lighter'}
                                       options={mapLocalMetaFieldOptions(CouponsPlus.components.offers.BuyXGetX.fields.discount.type.meta._allowed)}
                                       selectedValue={discountType}
                                       onSelectedValue={({id}) => {
                                           setDiscountType(id as BuyXGetXOptions['discount']['type'])
                                       }}
                    />
                    <NumberInput
                        numberId={'buyxgety.discount.amount'}
                        value={discountAmount}
                        onChange={setDiscountAmount}
                        fieldType={'text'}
                        type={inputtype}
                        labels={getBOGOOfferNumberInputProps(discountType).labels?.input}
                    />
                </div>
            </div>
            <div className={'space-y-2'}>
                <h2 className={'text-3x text-gray-700'}>{__('When these items aren\'t in the cart')}</h2>
                <Tabs selectedTabId={notInCartMode} onTabSelect={setNotInCartMode}
                      tabs={mapFromMeta(CouponsPlus.components.offers.BuyXGetX.fields.missingItemsInCart.mode.meta)}
                      disabledTabs={qtyType === 'advanced' ? ['auto-add'] : []}
                      direction={'vertical'} dimUnselected={true}/>
            </div>
        </div>}
    </div>;
}
