import React, {FC, useState} from "react";
import {EmulatedButton} from "../EmulatedButton";
import {useSetAtom} from "jotai";
import {BuyXGetYNotInCartNotificationWindowStateAtom} from "../atoms";
import {NotInCartNotification} from "./BuyXGetY";
import {__, CouponsPlus} from "../../globals";

export type WhenNotInCartCustomFieldsProps = {
    notification?: NotInCartNotification
    onUpdate: (notification: NotInCartNotification) => void
}

export const WhenNotInCartCustomFields: FC<WhenNotInCartCustomFieldsProps> = ({notification, onUpdate}) => {
    const openPopup = useSetAtom(BuyXGetYNotInCartNotificationWindowStateAtom)

    return <EmulatedButton
        className="relative flex items-center justify-between rounded-2 border-px border-gray-200 px-4 py-3 active:scale-[.96] transition-all ease duration-150"
        onClick={() => {
            openPopup({
                notification: notification!,
                onClose: (status, notification) => {
                    if (status === 'success') {
                        onUpdate(notification!) // a parenthesis of excitement!
                    }
                }
            })
        }}>
        <p className="text-gray-600 text-base text-left">{notification?.message}</p>
        <div className="flex flex-col items-start text-left">
            <div className="rounded-2 px-2 py-1 bg-gray-150 text-gray-450">
                {notification?.button.text}
            </div>
            <div className="text-smaller-2 text-gray-350 ml-2">{notification?.button.url.type === 'url'? notification?.button.url.value : findUrlTypelabel(notification?.button.url.type)}</div>
        </div>
    </EmulatedButton>;
}

function findUrlTypelabel(type: string | undefined) {
    let urlTypesDict = CouponsPlus.components.offers.BuyXGetY.fields.whenNotInCart.notification.button.url.type.meta._allowed;

    for (let key in urlTypesDict) {
        if (urlTypesDict[key] === type) {
            return key;
        }
    }
    return __('unknown')
}
