import {getCardComponentData} from "../cards";
import {CardRenderer, CardRendererContext} from "../CardRenderers";
import {ComponentMeta} from "../ComponentsMeta";
import {__, CouponsPlus} from "../../globals";
import {useTreeNodeTestable} from "../TreeHooks";
import {AmountValidatorOptions} from "./filterinterfaces";
import {FieldType} from "../fields";
import {usingTestableOptions} from "./CardHelpers";
import {amountValidatorTierFields, equals, TierType} from "../tiers";
import {number} from "motion";
import classNames from "classnames";
import {RowOptions} from "./Fields/RowOptions";
import {NumberProps} from "../fields/Number";
import React from "react";

export enum QuantityType {
    Any = 'any',
    Limit = 'limit',
}

export type QuantityOptions = AmountValidatorOptions & {
    type: QuantityType
}

const type = CouponsPlus?.components?.filters?.NumberOfItems?.type || 'NumberOfItems'
export const QuantityMeta: ComponentMeta = {
    id: type,
    type: 'filters',
    supportsTiers: true,
    tierFields: amountValidatorTierFields(),
    tierType: TierType.Numeric,
    configurable: context => context !== 'tier-base',
    supportsCustomTitleForSuggestedScopes: (suggestedScope) => true,
    description: ({suggestedScope}) => {
        if (suggestedScope === 'bogo') {
            return __('These are the number of items the customer must buy for the bogo offer to apply.');
        }
    },
    icon({className}) {
        return <svg xmlns="http://www.w3.org/2000/svg" className={className} fill="none" viewBox="0 0 24 24"
                    stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                  d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"/>
        </svg>
    },
    fieldsMap: (componentRuntimeData, scope, suggestedScope) => [
        [
            /* edit: this is no longer going to be needed and if you've found this please delete it
                        {id: 'type', renderType: FieldType.Tab}
            */
        ],
        [
            new RowOptions({
                type: 'featured',
                colWidth: 'auto'
            }),
            {
                id: 'quantity',
                renderType: FieldType.Number,
                fieldProps: {
                    border: false,
                    labels: {
                        input: {
                            inputLeftOutside: suggestedScope === 'bogo' && scope === 'tree-node'? <span
                                className="inline-flex pl-1 text-gray-300 !font-normal">{__('Buy')}</span> : undefined
                        }
                    }
                } as Partial<NumberProps>
            }
        ]
    ],
    fieldsNotes: ({options}, scope) => [
        scope.startsWith('tier') && __('Tier: The cheapest items will be selected from the filtered items.')
    ].filter(note => !!note),
}
export const QuantityRenderer: CardRenderer<QuantityOptions> = {
    type,
    icon({className}) {
        return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className={className}>
            <path
                d="M11.644 1.59a.75.75 0 0 1 .712 0l9.75 5.25a.75.75 0 0 1 0 1.32l-9.75 5.25a.75.75 0 0 1-.712 0l-9.75-5.25a.75.75 0 0 1 0-1.32l9.75-5.25Z"/>
            <path
                d="m3.265 10.602 7.668 4.129a2.25 2.25 0 0 0 2.134 0l7.668-4.13 1.37.739a.75.75 0 0 1 0 1.32l-9.75 5.25a.75.75 0 0 1-.71 0l-9.75-5.25a.75.75 0 0 1 0-1.32l1.37-.738Z"/>
            <path
                d="m10.933 19.231-7.668-4.13-1.37.739a.75.75 0 0 0 0 1.32l9.75 5.25c.221.12.489.12.71 0l9.75-5.25a.75.75 0 0 0 0-1.32l-1.37-.738-7.668 4.13a2.25 2.25 0 0 1-2.134-.001Z"/>
        </svg>
    },
    prefix: false,
    example: scope => scope === 'tier-base' ? __('2 -> 10% OFF, 3 -> 13% OFF, etc.') : __('Buy 1, Get 1 Free, 10% off Max. 5 items, etc.'),
    AboveComputedValue: usingTestableOptions<QuantityOptions>(({quantity: {type} = {}} = {}, {context}) => {
        if ((['tier-base', 'tier-subchild'] as CardRendererContext[]).includes(context)) {
            return false
        }

        switch (type) {
            case "equals":
            case "range":
                return __('Quantity')
            case "minimum":
                return __('Minimum')
            case "maximum":
                return __('Maximum')
        }

    }),
    ComputedValue: usingTestableOptions<QuantityOptions>(({quantity: {amount, type, range} = {}} = {}, {context}) => {
        if (context === 'tier-base') {
            return getCardComponentData('filter', QuantityMeta.id).name
        }

        let value: string | number = ''

        switch (type) {
            case "equals":
            case "minimum":
            case "maximum":
                value = amount!
                break
            case "range":
                value = `${range?.minimum} - ${range?.maxmimum}`
                break
        }

        if (context === 'tier-subchild') {
            return <span className={classNames('flex', {
                'items-end space-x-1': type === 'maximum',
                'items-center space-x-0': type === 'minimum'
            })}>
                <span>{value}</span>
                {type === 'minimum' && <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"
                                            className="min-w-3 min-h-3 max-w-3 max-h-3">
                    <path
                        d="M10.75 4.75a.75.75 0 0 0-1.5 0v4.5h-4.5a.75.75 0 0 0 0 1.5h4.5v4.5a.75.75 0 0 0 1.5 0v-4.5h4.5a.75.75 0 0 0 0-1.5h-4.5v-4.5Z"/>
                </svg>}
                {type === 'maximum' && <span className="text-smaller-1 opacity-60 leading-[20px]">{__('max.')}</span>}
            </span>
        }
        return value

    }),
    canRenderInSelectedSidebarPopup: (options: QuantityOptions, currentFilterId: string): boolean => {
        // if its type is 'any' then it should not be shown in the sidebar popup
        return options?.type !== QuantityType.Any;
    },
    canShowAsAvailableWhileBeingAmongstSelected: (options: QuantityOptions, currentFilterId): boolean => {
        const anyQuantity = options?.type === QuantityType.Any;
        const currentlySelectedFilterIsNotQuantity = currentFilterId !== QuantityMeta.id;

        return anyQuantity && currentlySelectedFilterIsNotQuantity;
    },
}