import {__, CouponsPlus} from "../../../globals"
import {ComponentMeta} from "../../ComponentsMeta"
import {iconWithClassName} from "../../IconWithClassName"
import {CardRenderer, CardRendererContext} from "../../CardRenderers";
import {usingTestableOptions} from "../CardHelpers"
import {ComponentCategory} from "../../components";
import {inclusionValueValidatorFieldsMap} from "../InclusionValueValidator";
import {FieldType} from "../../fields";
import {SelectOption} from "../../fields/MultiSelectSearch";
import {fieldsCacheContainer} from "../../FieldsCache";
import {colors} from "../../Colors";
import React from "react";
import {CustomProductOptionValue} from "../Products";
import {TierType} from "../../tiers";
import {getCardComponentData} from "../../cards";
import {request} from "../../Color";

const _checkOnLabel = {
    billingAdress: __('Billing Address'),
    shippingAddress: __('Shipping Address'),
    ipAddress: __('IP Address'),
}

export type LocationOptions = {
    inclusionType: 'allowed' | 'forbidden',
    //locationDepth: 'country' | 'state', no longer needed in 3.0+!
    areas: string[], // string of codes, e.g. ['US', 'MX',] OR ['US:CA', 'US:NY']
    checkOn: {
        billingAddress: boolean,
        shippingAddress: boolean,
        IP: boolean,
    }
}
const type = CouponsPlus?.components?.conditions?.Location?.type || 'Location'
export const LocationMeta: ComponentMeta = {
    id: type,
    type: 'conditions',
    relatedSearchTerms: [
        'place',
        'area',
        'zone',
        'state',
        'province',
        'region',
        'country',
        'territory',
    ],
    category: ComponentCategory.Account,
    priority: 4,
    supportsTiers: true,
    tierFields: ['areas'],
    tierType: TierType.Fixed,
    configurable: context => true, // configurable even in tier bases!
    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 fillRule="evenodd"
                      d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25ZM6.262 6.072a8.25 8.25 0 1 0 10.562-.766 4.5 4.5 0 0 1-1.318 1.357L14.25 7.5l.165.33a.809.809 0 0 1-1.086 1.085l-.604-.302a1.125 1.125 0 0 0-1.298.21l-.132.131c-.439.44-.439 1.152 0 1.591l.296.296c.256.257.622.374.98.314l1.17-.195c.323-.054.654.036.905.245l1.33 1.108c.32.267.46.694.358 1.1a8.7 8.7 0 0 1-2.288 4.04l-.723.724a1.125 1.125 0 0 1-1.298.21l-.153-.076a1.125 1.125 0 0 1-.622-1.006v-1.089c0-.298-.119-.585-.33-.796l-1.347-1.347a1.125 1.125 0 0 1-.21-1.298L9.75 12l-1.64-1.64a6 6 0 0 1-1.676-3.257l-.172-1.03Z"
                      clipRule="evenodd"/>
            </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="m6.115 5.19.319 1.913A6 6 0 0 0 8.11 10.36L9.75 12l-.387.775c-.217.433-.132.956.21 1.298l1.348 1.348c.21.21.329.497.329.795v1.089c0 .426.24.815.622 1.006l.153.076c.433.217.956.132 1.298-.21l.723-.723a8.7 8.7 0 0 0 2.288-4.042 1.087 1.087 0 0 0-.358-1.099l-1.33-1.108c-.251-.21-.582-.299-.905-.245l-1.17.195a1.125 1.125 0 0 1-.98-.314l-.295-.295a1.125 1.125 0 0 1 0-1.591l.13-.132a1.125 1.125 0 0 1 1.3-.21l.603.302a.809.809 0 0 0 1.086-1.086L14.25 7.5l1.256-.837a4.5 4.5 0 0 0 1.528-1.732l.146-.292M6.115 5.19A9 9 0 1 0 17.18 4.64M6.115 5.19A8.965 8.965 0 0 1 12 3c1.929 0 3.716.607 5.18 1.64"/>
        </svg>
    }),
    fieldsMap: ({options: {}}: { options: Partial<LocationOptions> }, scope) => [
        ...scope !== 'tier-base' ? (inclusionValueValidatorFieldsMap('conditions', type, (options => ({
            SelectStateProps: {
                defaultItemOptions: {
//                    Label: CustomProductsFieldLabel
                }
            },
            SelectSearchProps: {
                MultiSelectSearchItemProps: {
                    options: {
//                        Label: CustomProductsFieldLabel
                    }
                }
                ,
                customOptionValueResolver: (option) => ({
                    type: 'product',
                    option
                }),
            }
        })), 'areas', undefined, undefined, {
            inclusionType: !scope.startsWith('tier')
        })) : [],
        scope !== 'tier-subchild' && [
            {
                id: 'checkOn',
                renderType: FieldType.Tab,
                title: __('What to check'),
                description: __('All the selected options need to match.'),
                //title: locationDepth === 'country' ? __('Countries') : __('States'),
                fieldOptions: {
                    format: 'booleanDictionary',
                    multiple: true,
                    direction: 'vertical',
                }
            },
        ],
    ]
};
export const LocationRenderer: CardRenderer<LocationOptions> = {
    type,
    icon: LocationMeta.icon!,
    prefix: '*',
    example: scope => undefined,
    AboveComputedValue: usingTestableOptions<LocationOptions>(({inclusionType}, {context}) => {
        if ((['tier-base', 'tier-subchild'] as CardRendererContext[]).includes(context)) {
            return false
        }

        if (inclusionType === 'allowed') {
            return __('Eligible Locations')
        } else {
            return __('Ineligible Locations')
        }
    }),
    ComputedValue: usingTestableOptions<LocationOptions>(({areas = [], checkOn}, {context, color}) => {
        const metaData = CouponsPlus.components.conditions[LocationMeta.id]

        /**
         * A function so we dont get errors on tier subchild (partials) because they dont have a checkOn properties (individual tiers only support areas, base tiers only support checkOn.)
         */
        const getCheckOnLabel = (): string => {
            let checkOnLabel: string

            if (checkOn.billingAddress && checkOn.shippingAddress && checkOn.IP) {
                checkOnLabel = __('Strict')
            } else {
                const checkOnLabels: string[] = []

                if (checkOn.billingAddress) {
                    checkOnLabels.push(_checkOnLabel.billingAdress)
                }
                if (checkOn.shippingAddress) {
                    checkOnLabels.push(_checkOnLabel.shippingAddress)
                }
                if (checkOn.IP) {
                    checkOnLabels.push(_checkOnLabel.ipAddress)
                }

                checkOnLabel = checkOnLabels.length === 2 ? checkOnLabels.join(__('* and *').replaceAll('*', '')) : checkOnLabels.join(', ')
            }

            return checkOnLabel
        };

        return <div className="grid grid-cols-1 gap-[2px]">
            {context === 'tier-base' &&
                <h1 className={`${request(color).text(90)}`}>{getCardComponentData('condition', LocationMeta.id).name}</h1>}
            {context !== 'tier-subchild' && <p className="text-smaller-2 opacity-60">{getCheckOnLabel()}</p>}
            {context !== 'tier-base' && <div className="grid grid-cols-1 gap-0">
                {areas.map((id) => {
                    const selectedProductOption: SelectOption<CustomProductOptionValue> | undefined = fieldsCacheContainer.get('locations').get(id) as SelectOption<CustomProductOptionValue> | undefined

                    if (!selectedProductOption) {
                        return '?'
                    }

                    // will change ts in the future
                    let color = colors.purple

                    return <div>{selectedProductOption.label}</div>
                })}
                {areas.length === 0 && <span className="opacity-60">{__('Select a location')}</span>}
            </div>}
        </div>;
    }),
}
