import { InfoCircleFilled } from "@ant-design/icons";
import { Modal } from "antd";
import { observer } from "mobx-react";
import { useCallback, useEffect, useState } from "react";

import { useConfigHintText } from "../../hooks/useConfigHintText.js";
import { useStores } from "../../store/stores.js";
import { __ } from "../../utils/i18n.js";

import type { ConfigHintTextIdentifier } from "../../hooks/useConfigHintText.js";
import type { FC } from "react";

const ConfigHintModal: FC<{
    identifier: ConfigHintTextIdentifier;
    width?: number;
    title?: string;
    sprintfArgs?: string[];
    always?: boolean;
}> = observer(({ identifier, width, title, sprintfArgs = [], always }) => {
    const { optionStore } = useStores();
    const {
        others: { modalHints },
    } = optionStore;
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        if (always) {
            const idx = modalHints.indexOf(identifier);
            if (idx > -1) {
                modalHints.splice(idx, 1);
            }
        }
    }, [always, modalHints]);

    useEffect(() => {
        setVisible(modalHints.indexOf(identifier) === -1);
    }, [modalHints.length, identifier]);

    // Determine title and description
    const description = useConfigHintText(identifier, ...sprintfArgs);
    const questionInDesc =
        typeof description === "string" && description.indexOf("?") > -1 ? description.split("?")[0] : "";
    const useTitle = title ? title : questionInDesc ? `${questionInDesc}?` : __("What you should definitely know!");
    const useDescription =
        typeof description === "string" && typeof useTitle === "string" && questionInDesc
            ? description.replace(useTitle, "").trim()
            : description;

    const handleOk = useCallback(() => {
        optionStore.setModalHintSeen(identifier);
    }, [identifier, optionStore]);

    return (
        <Modal
            open={visible}
            title={
                <span>
                    <InfoCircleFilled style={{ color: "#1890ff" }} /> {useTitle}
                </span>
            }
            closable={false}
            onOk={handleOk}
            width={width}
            okText={__("Okay, I got it")}
            cancelButtonProps={{ style: { display: "none" } }}
        >
            {useDescription}
        </Modal>
    );
});

export { ConfigHintModal };
