import {ComponentMeta} from "../ComponentsMeta";
import React from "react";
import {iconWithClassName} from "../IconWithClassName";
import {CardRenderer} from "../CardRenderers";
import {__} from "../../globals";
import {usingOfferOptions, withPrefix} from "./CardHelpers";
import {FieldType} from "../fields";
import {NumberProps} from "../fields/Number";
import {ComponentCategory} from "../components";
import {CardItemSecondaryValue} from "../CardItemSecondaryValue";
import {DiscountValue} from "./DiscountValue";
import {ListItem} from "./ListItem";
import {BaseOfferOptions} from "./OfferTypes";
import {RepeatingLabel} from "./Recusrive";
import {RowOptions} from "./Fields/RowOptions";
import {getBOGOOfferNumberInputProps} from "../fields/NumberFieldUtils";

export type qtyType = 'simple' | 'advanced'
export type Qty = {
    "type": "any", // currently only 'any' is supported
    "amount": 1 // this is a placeholder for future advanced types
}
export type ProductDiscountOptions = {
    // new added in 1.1
    qtyType: qtyType,
    "qty": Qty,
    quantity: number,
    discount: {
        type: 'free' | 'percentage' | 'amount' | 'fixed-price',
        amount: number
    },
    missingItemsInCart: {
        mode: 'auto-add' | 'manual-add'
    }
} & BaseOfferOptions
// Safe interpolation utility to inject JSX elements into translated templates like __('{1} for {2}')
// Only replaces exact numeric placeholder tokens; other text stays as plain text nodes.
const interpolateElements = (template: string, replacements: Record<number, React.ReactNode>): React.ReactNode[] => {
    return template
        .split(/(\{\d+\})/g)
        .filter(Boolean)
        .map((token, i) => {
            if (/^\{\d+\}$/.test(token)) {
                const index = parseInt(token.slice(1, -1), 10);
                return <React.Fragment key={i}>{replacements[index]}</React.Fragment>;
            }
            return <React.Fragment key={i}>{token}</React.Fragment>;
        });
};


export type BuyXGetXOptions = ProductDiscountOptions & {
    quantityType: 'fixed' | 'duplicate',
    missingItemsInCart: {
        mode: 'auto-add' | 'manual-add'
    },
}
export const type = 'BuyXGetX'
export const BuyXGetXMeta: ComponentMeta = {
    id: type,
    type: 'offers',
    fieldsTitlePrefix: false,
    category: ComponentCategory.BOGO,
    listTitle: withPrefix(__('BOGO:')),
    titlePrefix: <span className={'text-gray-450'}>{__('BOGO:')}</span>,
    icon: iconWithClassName(({className, context}) => {
        if (context === 'card') {
            // solid
            return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="size-6">
                <path
                    d="M11.25 3v4.046a3 3 0 0 0-4.277 4.204H1.5v-6A2.25 2.25 0 0 1 3.75 3h7.5ZM12.75 3v4.011a3 3 0 0 1 4.239 4.239H22.5v-6A2.25 2.25 0 0 0 20.25 3h-7.5ZM22.5 12.75h-8.983a4.125 4.125 0 0 0 4.108 3.75.75.75 0 0 1 0 1.5 5.623 5.623 0 0 1-4.875-2.817V21h7.5a2.25 2.25 0 0 0 2.25-2.25v-6ZM11.25 21v-5.817A5.623 5.623 0 0 1 6.375 18a.75.75 0 0 1 0-1.5 4.126 4.126 0 0 0 4.108-3.75H1.5v6A2.25 2.25 0 0 0 3.75 21h7.5Z"/>
                <path
                    d="M11.085 10.354c.03.297.038.575.036.805a7.484 7.484 0 0 1-.805-.036c-.833-.084-1.677-.325-2.195-.843a1.5 1.5 0 0 1 2.122-2.12c.517.517.759 1.36.842 2.194ZM12.877 10.354c-.03.297-.038.575-.036.805.23.002.508-.006.805-.036.833-.084 1.677-.325 2.195-.843A1.5 1.5 0 0 0 13.72 8.16c-.518.518-.76 1.362-.843 2.194Z"/>
            </svg>
        }
        // outline
        return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5}
                    stroke="currentColor" className="size-6">
            <path strokeLinecap="round" strokeLinejoin="round"
                  d="M12 3.75v16.5M2.25 12h19.5M6.375 17.25a4.875 4.875 0 0 0 4.875-4.875V12m6.375 5.25a4.875 4.875 0 0 1-4.875-4.875V12m-9 8.25h16.5a1.5 1.5 0 0 0 1.5-1.5V5.25a1.5 1.5 0 0 0-1.5-1.5H3.75a1.5 1.5 0 0 0-1.5 1.5v13.5a1.5 1.5 0 0 0 1.5 1.5Zm12.621-9.44c-1.409 1.41-4.242 1.061-4.242 1.061s-.349-2.833 1.06-4.242a2.25 2.25 0 0 1 3.182 3.182ZM10.773 7.63c1.409 1.409 1.06 4.242 1.06 4.242S9 12.22 7.592 10.811a2.25 2.25 0 1 1 3.182-3.182Z"/>
        </svg>
    }),

    fieldsMap: ({options}) => {

        return ([
            [
                new RowOptions({
                    type: 'featured',
                    colWidth: 'auto'
                }),
                options.quantityType === 'fixed' && {
                    id: 'quantity',
                    renderType: FieldType.Number,
                    fieldProps: {
                        hasAmountStructure: false,
                        labels: {
                            input: {
                                inputLeftOutside: <span
                                    className="inline-flex pl-1 text-gray-300 !font-normal uppercase">{__('Get')}</span>
                            }
                        },
                        border: false
                    } as Partial<NumberProps>,
                },
                {
                    id: 'discount',
                    renderType: FieldType.Number,
                    fieldProps: getBOGOOfferNumberInputProps(options.discount.type) as Partial<NumberProps>,
                },
            ],
            options.quantityType === 'fixed' && [
                {
                    title: __('When items eligible for discount aren\'t in the cart'),
                    id: 'missingItemsInCart.mode',
                    renderType: FieldType.Tab,
                    fieldOptions: {
                        direction: 'vertical',
                    }
                }
            ],
        ])
    },
    fieldsMapLast: ({options}) => [
        [
            [
                {
                    id: 'quantityType',
                    title: __('Experimental mode'),
                    renderType: FieldType.Tab,
                    fieldOptions: {
                        direction: 'vertical',
                    }

                }
            ]
        ]
    ],
    fieldsNotes: ({options}) => options.quantityType === 'fixed' ? [
        __('This offer uses the filtered items as the qualifier for the offer. This means the items matching your filters are what a customer must buy to unlock the offer, and they will not be discounted themselves. The discount will be applied to the cheapest additional items of the same type in the cart.'),
        __('For example: If you create a "Buy 1, Get 1 Free" offer for Category A. If a customer adds just one $25 shirt from this category, the offer will automatically add a second, identical $25 shirt to the cart and make it free. However, if the customer manually adds 2 qualifying shirts before applying the coupon, no extra item will be added and the discount will be applied to the cheapest'),
        /*__('Setting a quantity in your filters is required for this offer')*/
    ] : []
}

export const BuyXGetXRenderer: CardRenderer = {
    type: type,
    prefix: "*",
    example: __('Buy 1 t-shirt, get 1 free, Buy 2 t-shirts, get 1 at 50% off'),
    icon: BuyXGetXMeta.icon!,
    AboveComputedValue: () => false, // No above computed value for this card
    suggestedScopeMarker: (suggestedScope) => {
        if (suggestedScope === 'bogo') {
            return {
                prefix: __('BOGO'),
                label: __('Get')
            }
        }
    },
    ComputedValue: usingOfferOptions<BuyXGetXOptions>((options, {color,}) => {
        const {quantity, discount} = options
        return <div className="space-y-1">
            <div>
                <div className={`${color.text(10)} flex items-center`}>
                    {false && <span className="max-w-[6px] overflow-hidden text-4x font-black translate-y-1/4">-</span>}
                    <div className="--flex --items-center space-y-1">
                        <div className={'flex space-x-1 text-3x  text-white'}>
                            <div className={'text-opacity-60 text-white'}>{__('Get')}</div>
                            {options.quantityType === 'fixed' ? <div className={'font-semibold'}>{quantity}</div> : <div className={'font-semibold'}>{__('x2')}</div>}
                        </div>
                        {false && <span className={'opacity-60 px-1'}>-</span>}
                        {false && <CardItemSecondaryValue color={{
                            color,
                            tint: (color) => color.text(20)
                        }}>{__('Get')}</CardItemSecondaryValue>}
                        {<div className={'flex items-center space-x-1'}>
                            <DiscountValue productDiscountOptions={options}/>
                            {/*
                        {interpolateElements(__(' {1} for {2} '), {
                            1: renderOfferMainValue(quantity),
                            2: renderDiscountValue(),
                        })}
*/}
                        </div>}
                    </div>
                </div>
            </div>
        </div>

    }),
    OutsideComputedValue: usingOfferOptions<BuyXGetXOptions>(({quantityType, quantity, discount, missingItemsInCart, __BASE__: {isRecursive}}, {color,}) => {
        return <ul className={`max-w-[140px] text-smaller-1 leading-3 text-gray-600
         px-2 py-1`}>
            {quantityType === 'fixed' && <ListItem>
                {(quantity === 1 ? __('* extra item of the same product type') : __('* extra items of the same product type')).replace('*', quantity)}
                <span className="opacity-60 bg-white">{__(' (Cheapest)')}</span>
            </ListItem>}
            {quantityType === 'duplicate' && <ListItem>
                {__('Matches quantity of eligible items.')}
            </ListItem>}
            <ListItem>
                {missingItemsInCart.mode === 'auto-add' || quantityType === 'duplicate'? __('Automatically added') : __('Manually added')}
            </ListItem>
            {isRecursive && <RepeatingLabel /> }
        </ul>
    }),
}