import { RightOutlined } from "@ant-design/icons";
import { App, Layout, Spin } from "antd";
import { observer } from "mobx-react";
import { useCallback, useState } from "react";

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

import type { ResponseRestSettingsVerifyPost } from "../wp-api/settings-verify.post.js";

const { Header, Content, Footer } = Layout;

const SettingsContent = observer(() => {
    const { message } = App.useApp();
    const { optionStore } = useStores();
    const [thumbnailFolder, setThumbnailFolder] = useState(optionStore.others.thumbnailFolder);
    const [thumbnailFilename, setThumbnailFilename] = useState(optionStore.others.thumbnailFilename);
    const [chunkSize, setChunkSize] = useState(optionStore.others.chunkSize);
    const [verify, setVerify] = useState<ResponseRestSettingsVerifyPost>(undefined);
    const { isPro, showProHints } = optionStore.others;

    const handleVerify = useCallback(async () => {
        if (!thumbnailFolder && !thumbnailFilename) {
            setVerify(undefined);
            return true;
        }

        const verifyResult = await optionStore.verify(thumbnailFolder, thumbnailFilename);
        setVerify(verifyResult);
        return verifyResult.errors.length === 0;
    }, [optionStore, thumbnailFolder, thumbnailFilename, chunkSize]);

    const handleSave = useCallback(async () => {
        /* onlypro:start */
        if (!(await handleVerify())) {
            return;
        }
        /* onlypro:end */

        try {
            await optionStore.update(thumbnailFolder, thumbnailFilename, chunkSize);
            message.success(__("Settings saved successfully!"));
        } catch (e) {
            message.error(e.responseJSON.message);
        }
    }, [optionStore, thumbnailFolder, thumbnailFilename, chunkSize, handleVerify]);

    return (
        <Layout>
            <Spin spinning={optionStore.updateBusy}>
                <Header style={{ background: "#fff" }}>
                    {__("Thumbnails")} <RightOutlined /> {__("Settings")}
                </Header>
                <Content style={{ margin: "24px 16px 0" }}>
                    <div className="rtg-dialog-content" style={{ display: "block" }}>
                        {!isPro && showProHints && <ProFooter />}
                        <h2>{__("Thumbnail folder and file name")}</h2>
                        {__(
                            "You can configure the file path of the thumbnails and thereby optimize them for SEO. The following variables can be used in the folder and file name:",
                        )}
                        <ul>
                            <li>
                                <code>%id%</code>: {__("ID of the attachment (e.g. 998)")}
                            </li>
                            <li>
                                <code>%size-identifier%</code>:{" "}
                                {__('Name of the thumbnail size (e.g. "medium", "large")')}
                            </li>
                            <li>
                                <code>%identifier-width%</code>: {__("Width of the registered thumbnail size (in px)")}
                            </li>
                            <li>
                                <code>%identifier-height%</code>:{" "}
                                {__("Height of the registered thumbnail size (in px)")}
                            </li>
                            <li>
                                <code>%name%</code>:{" "}
                                {__('Basename of the uploaded file (e.g. "car" for filename "car.jpg")')}
                            </li>
                            <li>
                                <code>%extension%</code>:{" "}
                                {__('Extension of the file (e.g. "jpg" for filename "car.jpg")')}
                            </li>
                            <li>
                                <code>%image-width%</code>: {__("Width of the generated thumbnail (in px)")}
                            </li>
                            <li>
                                <code>%image-height%</code>: {__("Height of the generated thumbnail (in px)")}
                            </li>
                        </ul>
                        <h4>
                            {__("Thumbnail subfolder")} <ProTag feature="option-thumbnail-subfolder" />
                        </h4>
                        <input
                            type="text"
                            value={thumbnailFolder}
                            disabled={!isPro}
                            onChange={(e) => setThumbnailFolder(e.target.value)}
                            className="regular-text"
                        />
                        <p className="description">
                            {__(
                                "Folder where thumbnails should be stored inside wp-content/uploads/. By default, the thumbnails are not stored in a subfolder.",
                            )}
                        </p>
                        <div className="rtg-example-container">
                            {__("Examples")}:
                            <ul>
                                <li>
                                    {_i(
                                        __(
                                            "{{code}}thumbnails/%%size-identifier%%{{/code}} can result in: thumbnails/{{strong}}medium{{/strong}}",
                                        ),
                                        {
                                            code: <code />,
                                            strong: <strong />,
                                        },
                                    )}
                                </li>
                                <li>
                                    {_i(
                                        __(
                                            "{{code}}%%identifier-width%%x%%identifier-height%%/{{/code}} can result in: {{strong}}300x300{{/strong}}",
                                        ),
                                        {
                                            code: <code />,
                                            strong: <strong />,
                                        },
                                    )}
                                </li>
                            </ul>
                        </div>
                        <h4>
                            {__("Thumbnail filename")} <ProTag feature="option-thumbnail-filename" />
                        </h4>
                        <input
                            type="text"
                            value={thumbnailFilename}
                            disabled={!isPro}
                            onChange={(e) => setThumbnailFilename(e.target.value)}
                            className="regular-text"
                        />{" "}
                        <p className="description">
                            {__(
                                "File name for thumbnails generated dynamically. Please leave empty to use the default file name in WordPress.",
                            )}
                        </p>
                        <div className="rtg-example-container">
                            {__("Example")}:
                            <ul>
                                <li>
                                    {_i(
                                        __(
                                            "{{code}}%%name%%-%%image-width%%x%%image-height%%.%%extension%%{{/code}} can result in: {{strong}}car-300x300.jpg{{/strong}}",
                                        ),
                                        {
                                            code: <code />,
                                            strong: <strong />,
                                        },
                                    )}
                                </li>
                            </ul>
                        </div>
                        <p>
                            <button
                                className="button"
                                disabled={!(thumbnailFilename || thumbnailFolder)}
                                onClick={handleVerify}
                            >
                                {__("Preview thumbnail upload structure")}
                            </button>
                        </p>
                        {!!verify && (
                            <div>
                                {Object.keys(verify.errors).length > 0 ? (
                                    <div
                                        className="notice inline notice-error notice-alt"
                                        style={{ margin: "0 0 10px" }}
                                    >
                                        <p>{Object.values(verify.errors).join(". ")}</p>
                                    </div>
                                ) : (
                                    <div
                                        className="notice inline notice-success notice-alt"
                                        style={{ margin: "0 0 10px" }}
                                    >
                                        <ul>
                                            <li>
                                                <strong>
                                                    {__("Examples of your Thumbnail folder and file name:")}
                                                </strong>
                                            </li>
                                            {Object.values(verify.pathes).map((path, idx) => (
                                                <li key={idx}>{path}</li>
                                            ))}
                                        </ul>
                                    </div>
                                )}
                            </div>
                        )}
                        <h2>{__("Chunk size")}</h2>
                        <input
                            type="number"
                            min="1"
                            value={chunkSize}
                            onChange={(e) => setChunkSize(+e.target.value)}
                            className="regular-text"
                        />
                        <p className="description">
                            {__(
                                "Thumbnail regeneration is performed sequentially in chunks to avoid overloading your server. If you notice too high CPU usage, you can reduce the chunk size.",
                            )}
                        </p>
                    </div>
                </Content>
                <Footer style={{ textAlign: "center" }}>
                    <button className="button-primary" onClick={handleSave}>
                        {__("Save")}
                    </button>
                </Footer>
            </Spin>
        </Layout>
    );
});

export { SettingsContent };
