import { Modal, Spin } from "antd";
import { observer } from "mobx-react";
import { useEffect, useState } from "react";

import { __, _x } from "../../utils/i18n.js";

import type { License } from "../../models/license.js";
import type { FC, PropsWithChildren } from "react";

const PluginUpdateLicenseTelemetryDataModal: FC<
    PropsWithChildren<{ license: License; linkWrapper?: boolean; disabled?: boolean }>
> = observer(({ license, linkWrapper, disabled, children }) => {
    const { busy, telemetryData, telemetryDataSharingOptIn } = license;
    const [isVisible, setVisible] = useState(false);

    useEffect(() => {
        if (isVisible && !telemetryData) {
            license.fetchTelemetryData();
        }
    }, [isVisible, telemetryData, license]);

    return (
        <>
            <Modal
                title={__("Telemetry data preview")}
                open={isVisible && !disabled}
                onCancel={() => setVisible(false)}
                cancelText={__("Close")}
                okButtonProps={{ style: { display: "none" } }}
            >
                {telemetryDataSharingOptIn && (
                    <p style={{ marginTop: 0, marginBottom: 10 }}>
                        {_x(
                            "At the time of activating the license, you agreed that we may send telemetry data from your installation to our server. You can revoke this at any time by deactivating and reactivating the licence.",
                            "legal-text",
                        )}
                    </p>
                )}
                <p style={{ marginTop: 0 }}>{__("The following data (raw) will be sent to our server:")}</p>
                <Spin spinning={busy}>
                    <textarea
                        readOnly
                        style={{ width: "100%", height: 300 }}
                        value={telemetryData ? JSON.stringify(telemetryData, null, 4) : ""}
                    />
                </Spin>
            </Modal>
            <span
                onClick={(e) => {
                    if (!disabled) {
                        setVisible(true);
                    }
                    e.preventDefault();
                }}
            >
                {linkWrapper ? <a>{children}</a> : children}
            </span>
        </>
    );
});

export { PluginUpdateLicenseTelemetryDataModal };
