import { Avatar, Card, Form, Space } from "antd";
import { observer } from "mobx-react";
import { useCallback, useEffect } from "react";

import { PluginUpdateEmbed, useStores as useRpmStores } from "@devowl-wp/real-product-manager-wp-client";

import { useStores } from "../../store/stores.js";
import { __, _i } from "../../utils/i18n.js";

import type { FC } from "react";

const ConfigLicensingConsumer: FC<{ withinModal?: boolean }> = observer(({ withinModal = false }) => {
    const {
        pluginUpdateStore: { pluginUpdates },
    } = useRpmStores();
    const { optionStore } = useStores();
    const {
        slug,
        others: { isPro, showLicenseFormImmediate },
        publicUrl,
    } = optionStore;
    const pluginUpdate = pluginUpdates.get(slug);

    const handleLicenseUpdated = useCallback(() => {
        // When form is shown directly after first usage, return to dashboard
        optionStore.setShowLicenseFormImmediate(false);
    }, [optionStore]);

    const handleLicenseSkip = useCallback(() => {
        optionStore.setShowLicenseFormImmediate(false);
        pluginUpdate.skip();
    }, [pluginUpdate, optionStore]);

    // Automatically skip if form already interacted (e.g. browser back cache issue)
    useEffect(() => {
        if (showLicenseFormImmediate && pluginUpdate?.hasInteractedWithFormOnce) {
            handleLicenseSkip();
        }
    }, [pluginUpdate, showLicenseFormImmediate, handleLicenseSkip]);

    const freeVersionParagraph = _i(
        __(
            "Before we start organizing your categories, you can {{strong}}obtain your free license to enjoy all the benefits{{/strong}} of the free version of Real Category Management. Get started now!",
        ),
        {
            strong: <strong />,
        },
    );

    return (
        <>
            {showLicenseFormImmediate && (
                <div style={{ maxWidth: 650, textAlign: "center", margin: "0 auto" }}>
                    {!withinModal && (
                        <Avatar
                            src={`${publicUrl}images/logos/real-category-library.svg`}
                            shape="square"
                            size={130}
                            style={{ backgroundColor: "white", padding: 25, borderRadius: 999, marginBottom: 10 }}
                        />
                    )}
                    {!withinModal && !isPro && (
                        <p style={{ fontSize: 15, margin: "0 auto 20px" }}>{freeVersionParagraph}</p>
                    )}
                </div>
            )}
            <Card
                title={
                    withinModal || !pluginUpdate
                        ? undefined
                        : isPro || pluginUpdate.isLicensed
                          ? __("License activation")
                          : __("Get your free license")
                }
                bordered={!withinModal}
                bodyStyle={withinModal ? { paddingLeft: 0, paddingRight: 0 } : undefined}
            >
                <Space direction="vertical" size="small">
                    {withinModal && !isPro && (
                        <p className="description" style={{ fontWeight: "bold" }}>
                            {freeVersionParagraph}
                        </p>
                    )}
                    <PluginUpdateEmbed
                        formProps={{
                            onSave: handleLicenseUpdated,
                            // Skip remote errors and move to dashboard immediately
                            onFailure: showLicenseFormImmediate && !isPro ? handleLicenseSkip : undefined,
                            footer: (
                                <Form.Item
                                    style={{
                                        margin: "25px 0 0",
                                        textAlign: showLicenseFormImmediate ? "center" : undefined,
                                    }}
                                >
                                    <input
                                        type="submit"
                                        className="button button-primary"
                                        value={
                                            showLicenseFormImmediate
                                                ? isPro
                                                    ? __("Activate license & continue")
                                                    : __("Activate free license & Continue")
                                                : __("Save")
                                        }
                                    />
                                </Form.Item>
                            ),
                        }}
                        listProps={{
                            onDeactivate: handleLicenseUpdated,
                        }}
                        slug={slug}
                    />
                </Space>
            </Card>
            {pluginUpdate && showLicenseFormImmediate && (
                <div
                    style={{ textAlign: "center", marginBottom: withinModal ? 0 : 20, marginTop: withinModal ? 0 : 20 }}
                >
                    <a className="button-link" onClick={handleLicenseSkip}>
                        {isPro
                            ? __("Continue without regular updates and without any support")
                            : __("Continue without any support and without e.g. discount announcements")}
                    </a>
                </div>
            )}
        </>
    );
});

export { ConfigLicensingConsumer };
