import { RightOutlined } from "@ant-design/icons";
import { Layout, Progress, Spin, Tag } from "antd";
import $ from "jquery";
import { isFlowCancellationError } from "mobx";
import { observer } from "mobx-react";
import { Fragment, useCallback, useRef, useState } from "react";

import { RatingPointer } from "@devowl-wp/real-utils";

import { AnalyseFooter } from "./analyseFooter.js";
import { AnalyseItems } from "./analyseItems.js";
import { ProFooter, ProTag } from "./proFooter.js";
import { isDefaultSchema } from "../others/isDefaultSchema.js";
import { useStores } from "../store/stores.js";
import { __ } from "../utils/i18n.js";

import type { AttachmentsStore } from "../store/attachments.js";
import type { MouseEvent } from "react";

const { Header, Content } = Layout;

const RegenerateContent = observer(
    ({ onClick }: { onClick: (event: MouseEvent<HTMLLIElement, globalThis.MouseEvent>) => void }) => {
        const regenerateButtonRef = useRef<HTMLButtonElement>(null);
        const { optionStore, attachmentsStore, statsStore } = useStores();
        const [regeneratePromise, setGeneratePromise] = useState<ReturnType<AttachmentsStore["analyze"]>>(null);
        const [forceNewSchema, setForceNewSchema] = useState(false);
        const [selectedSizes, setSelectedSizes] = useState<string[]>([]);
        const [skipExisting, setSkipExisting] = useState(false);
        const {
            others: { isPro, showProHints, canManageOptions },
        } = optionStore;
        const { regenerateBusy, regenerated } = attachmentsStore;
        const { busy, imagesCount, schema, sizes } = statsStore;

        const getSelectedSizes = useCallback(
            (pSelectedSizes = selectedSizes, defaultValue: string[] = []) => {
                return pSelectedSizes.length ? pSelectedSizes.slice() : defaultValue;
            },
            [selectedSizes],
        );

        const handleStart = useCallback(() => {
            const start = attachmentsStore.regenerate(
                getSelectedSizes(undefined, Object.keys(sizes)),
                forceNewSchema,
                skipExisting,
            );
            start.catch((e) => {
                if (isFlowCancellationError(e)) {
                    // Silence is golden.
                }
            });
            setGeneratePromise(start);

            optionStore.isRatable &&
                start.then(() => new RatingPointer(optionStore.slug, $(regenerateButtonRef.current)));
        }, [attachmentsStore, optionStore, getSelectedSizes, setGeneratePromise, sizes, forceNewSchema, skipExisting]);

        const handleSizeSelect = useCallback(
            (size: string) => {
                const a = getSelectedSizes(selectedSizes);
                const idx = a.indexOf(size);
                if (idx > -1) {
                    a.splice(idx, 1);
                } else {
                    a.push(size);
                }
                setSelectedSizes(a);
            },
            [selectedSizes, getSelectedSizes, setSelectedSizes],
        );

        return (
            <Layout>
                <Header style={{ background: "#fff" }}>
                    {__("Thumbnails")} <RightOutlined /> {__("Bulk regenerate")}
                </Header>
                <Content style={{ margin: "24px 16px 0" }}>
                    <div className="rtg-dialog-content">
                        {!isPro && showProHints && <ProFooter />}
                        <Spin spinning={busy}>
                            <div>
                                {regenerateBusy ? (
                                    <button className="button" onClick={regeneratePromise.cancel}>
                                        {__("Cancel (%d of %d regenerated)", regenerated.length, imagesCount)}
                                    </button>
                                ) : (
                                    <button className="button-primary" onClick={handleStart} ref={regenerateButtonRef}>
                                        {__("Regenerate all attachments")}
                                    </button>
                                )}
                            </div>
                        </Spin>
                        <p>
                            {(showProHints || isPro) && (
                                <Fragment>
                                    <label>
                                        <input
                                            type="checkbox"
                                            disabled={regenerateBusy || forceNewSchema || !isPro}
                                            checked={skipExisting}
                                            onChange={() => setSkipExisting(!skipExisting)}
                                        />
                                        {__("Skip files with already existing thumbnails")}{" "}
                                        <ProTag feature="skip-already-existing" />
                                    </label>
                                    <br />
                                    <label>
                                        <input
                                            type="checkbox"
                                            disabled={regenerateBusy || !isPro}
                                            checked={forceNewSchema}
                                            onChange={() => setForceNewSchema(!forceNewSchema)}
                                        />
                                        {__("Force regeneration of all thumbnails (and new custom path and filename)")}{" "}
                                        <ProTag feature="force-schema-mass" />
                                        {canManageOptions && (
                                            <Tag
                                                onClick={() =>
                                                    document
                                                        .querySelector<HTMLLIElement>(
                                                            `li[data-id="rtg-dialog-menu-item-settings"]`,
                                                        )
                                                        .click()
                                                }
                                                style={{ cursor: "pointer" }}
                                            >
                                                {__("Configure")}
                                            </Tag>
                                        )}
                                    </label>
                                </Fragment>
                            )}
                        </p>
                        {!isDefaultSchema(schema) && (
                            <div className="description">
                                {__("Thumbnail folder and file name:")}{" "}
                                <span
                                    className="rtg-highlight-placeholders"
                                    dangerouslySetInnerHTML={{ __html: schema }}
                                />
                            </div>
                        )}
                        {(showProHints || isPro) && !forceNewSchema && (
                            <p>
                                {__("Regenerates thumbnails in sizes:")}&nbsp;
                                {(isPro && (
                                    <Fragment>
                                        (
                                        <a
                                            href="#"
                                            onClick={(e) => {
                                                setSelectedSizes(Object.keys(sizes));
                                                e.preventDefault();
                                                return false;
                                            }}
                                        >
                                            {__("Select all")}
                                        </a>{" "}
                                        |{" "}
                                        <a
                                            href="#"
                                            onClick={(e) => {
                                                setSelectedSizes([]);
                                                e.preventDefault();
                                                return false;
                                            }}
                                        >
                                            {__("Deselect all")}
                                        </a>
                                        )
                                    </Fragment>
                                )) || <ProTag feature="only-checked" />}
                                <br />
                                {sizes &&
                                    Object.keys(sizes).map((size) => (
                                        <label style={{ marginRight: 5 }} key={size}>
                                            <input
                                                type="checkbox"
                                                disabled={regenerateBusy || !isPro}
                                                checked={selectedSizes.indexOf(size) > -1 || !isPro}
                                                onChange={() => handleSizeSelect(size)}
                                            />{" "}
                                            {size}
                                        </label>
                                    ))}
                            </p>
                        )}
                        {(regenerateBusy || regenerated.length > 0) && (
                            <Progress
                                percent={Math.round((regenerated.length / imagesCount) * 100)}
                                status={regenerateBusy ? "active" : "success"}
                            />
                        )}
                        <AnalyseItems attachments="regeneratedObjects" onClick={onClick} />
                    </div>
                </Content>
                <AnalyseFooter />
            </Layout>
        );
    },
);

export { RegenerateContent };
