import { Alert, App, Tag } from "antd";
import { useCallback, useEffect, useState } from "react";

import { copyToClipboard } from "@devowl-wp/react-utils";

import { useI18n } from "../../contexts/i18n.js";
import { useUpsell } from "../../contexts/upsell.js";

import type { CSSProperties } from "react";

const IN_APP_FOMO_URL_PARAMETER_TO_DEACTIVATE_WEBSITE_FOMO = "promo=in-app";

const UpsellInAppFomoCouponCounter = ({ style }: { style?: CSSProperties }) => {
    const { message } = App.useApp();
    const { __, _i } = useI18n();
    const { fomoCoupon } = useUpsell();

    const coupon = fomoCoupon?.coupon;
    const valueInPercent = fomoCoupon?.valueInPercent;
    const validUntil = fomoCoupon?.validUntil;

    const createTimerString = useCallback(() => {
        if (validUntil) {
            const remaining = new Date(validUntil).getTime() - new Date().getTime();

            // Already expired?
            if (remaining <= 0) {
                return undefined;
            }

            const fullSeconds = remaining / 1000;
            return [Math.floor(fullSeconds / 3600), Math.floor(fullSeconds / 60) % 60, Math.floor(fullSeconds % 60)]
                .map((v) => (v < 10 ? `0${v}` : v))
                .filter((v, i) => v !== "00" || i > 0)
                .join(":");
        } else {
            return undefined;
        }
    }, [validUntil]);
    const [, setRerender] = useState<number>();

    useEffect(() => {
        const interval = setInterval(() => {
            setRerender(new Date().getTime());
        }, 1000);
        return () => {
            clearInterval(interval);
        };
    }, []);

    const timerString = createTimerString();

    return timerString ? (
        <Alert
            style={style}
            message={_i(
                __(
                    "Use coupon {{tag}}%s{{/tag}} in the next {{strongHours}}%s hours{{/strongHours}} and save {{strongPercent}}%d %%{{/strongPercent}} in the first year!",
                    coupon,
                    timerString,
                    valueInPercent,
                ),
                {
                    tag: (
                        <Tag
                            color="success"
                            style={{ marginRight: 0, cursor: "pointer" }}
                            onClick={() => {
                                copyToClipboard(coupon);
                                message.success(__("Successfully copied coupon to clipboard!"));
                            }}
                        />
                    ),
                    strongHours: <strong style={{ color: "#d33131" }} />,
                    strongPercent: <strong />,
                },
            )}
        />
    ) : null;
};

export { IN_APP_FOMO_URL_PARAMETER_TO_DEACTIVATE_WEBSITE_FOMO, UpsellInAppFomoCouponCounter };
