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 {CustomFieldComputedValue, customFieldFieldsMap, CustomFieldOptions} from "./CustomField";
import {FieldType} from "../../fields";
import {MultiSelectSearchProps} from "../../fields/MultiSelectSearch";
import {CalendarProps} from "../../fields/Calendar";
import {NumberProps} from "../../fields/Number";
import dayjs from "dayjs";

const type = CouponsPlus?.components?.conditions?.UserRegistrationTime?.type || 'UserRegistrationTime'
export type AccountRegistrationTimeOptions = {
    type: 'recently' | 'range',
    recently: {
        value: number,
        unit: 'hours' | 'days',
        allowGuests: boolean
    },
    range: {
        from: string,
        to: string
    }
}
export const AccountRegistrationTimeMeta: ComponentMeta = {
    id: type,
    type: 'conditions',
    category: ComponentCategory.Account,
    fieldsTitlePrefix: false,
    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.25ZM12.75 6a.75.75 0 0 0-1.5 0v6c0 .414.336.75.75.75h4.5a.75.75 0 0 0 0-1.5h-3.75V6Z"
                      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="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/>
        </svg>
    }),
    // @ts-ignore
    fieldsMap: ({options: {type}}: Partial<{ options: AccountRegistrationTimeOptions }>) => [
        false && [{id: 'type', renderType: FieldType.Tab},],
        ...type === 'recently' ? [
            [{
                id: 'recently.value',
                renderType: FieldType.Number,
                fieldProps: {hasAmountStructure: false} as NumberProps
            }],
            [{
                id: 'recently.unit',
                renderType: FieldType.Select,
                fieldOptions: {/*optionsKey: '_allowed',*/ centered: true},
                fieldProps: {size: 'small', style: 'gray', width: 'auto'} as MultiSelectSearchProps<any>,
            }],
            [{
                id: 'recently.allowGuests',
                renderType: FieldType.BooleanTab,
            }]
        ] : [],
        ...type === 'range' ? [
            [
                {
                    id: 'range.from',
                    renderType: FieldType.Date,
                    fieldProps: {size: 'small'} as CalendarProps,
                    fieldOptions: {topBorder: false},
                    title: __('Start Date')
                },
                {
                    id: 'range.to',
                    renderType: FieldType.Date,
                    fieldProps: {size: 'small'} as CalendarProps,
                    fieldOptions: {topBorder: false},
                    title: __('End Date')
                },
            ],
        ] : [],
    ]
}

export const AccountRegistrationTimeRenderer: CardRenderer<AccountRegistrationTimeOptions> = {
    type,
    icon: AccountRegistrationTimeMeta.icon!,
    prefix: '*',
    example: __("Within 24 hours, from March 1, 2016 to October 31, 2016, etc."),
    AboveComputedValue: usingTestableOptions<AccountRegistrationTimeOptions>(({type}, {context}) => {
        if ((['tier-base', 'tier-subchild'] as CardRendererContext[]).includes(context)) {
            return false
        }

        if (type === 'recently') {
            return __('Registration Time');
        }

        return __('Registration Date');
    }),
    ComputedValue: usingTestableOptions<AccountRegistrationTimeOptions>(({type, recently, range}, {context}) => {
        if (type === 'recently') {
            let allowGuestsText = '';

            switch (recently.unit) {
                case 'hours':
                    allowGuestsText = __('Within * hours').replace('*', recently.value);
                    break;
                case 'days':
                    allowGuestsText = __('Within * days').replace('*', recently.value);
                    break;
            }

            if (recently.allowGuests) {
                allowGuestsText += ` ${__('(including guests)')}`;
            } else {
                allowGuestsText += ` ${__('(excluding guests)')}`;
            }

            return allowGuestsText;
        }

        // todo: this is repeated from Date.tsx, should be refactored
        const parseFormat = 'YYYY-MM-DD HH:mm';


        return <div className="flex flex-col">
            <p><p className="opacity-60">{__('From')}</p> <span>{dayjs(range.from, parseFormat).format('ll')}</span>
            </p>
            <p><p className="opacity-60">{__('To')}</p> <span>{dayjs(range.to, parseFormat).format('ll')}</span></p>
        </div>;
    }),
}