import { CopyOutlined, DeleteOutlined, RightOutlined, ScanOutlined } from "@ant-design/icons";
import { Layout, Progress, Spin } from "antd";
import { isFlowCancellationError } from "mobx";
import { observer } from "mobx-react";
import { Fragment, useCallback, useState } from "react";

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

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

const { Header, Content } = Layout;

const AnalyseContent = observer(
    ({ onClick }: { onClick: (event: MouseEvent<HTMLLIElement, globalThis.MouseEvent>) => void }) => {
        const [analyzePromise, setAnalyzePromise] = useState<ReturnType<AttachmentsStore["analyze"]>>(null);
        const { statsStore, attachmentsStore, optionStore } = useStores();
        const { imagesCount, deletableSpace, deletableSpaceFormat, totalCount, newThumbnailsCount } = statsStore;
        const { analyzeBusy, analyzed } = attachmentsStore;
        const {
            others: { showProHints, isPro },
        } = optionStore;

        const handleStart = useCallback(() => {
            const start = attachmentsStore.analyze();
            start.catch((e) => {
                if (isFlowCancellationError(e)) {
                    // Silence is golden.
                }
            });
            setAnalyzePromise(start);
        }, [attachmentsStore, optionStore, setAnalyzePromise]);

        const handleClear = useCallback(() => {
            const clear = attachmentsStore.clear();
            clear.catch((e) => {
                if (isFlowCancellationError(e)) {
                    // Silence is golden.
                }
            });
            setAnalyzePromise(clear);
        }, [attachmentsStore, setAnalyzePromise]);

        return (
            <Layout>
                <Header style={{ background: "#fff" }}>
                    {__("Thumbnails")} <RightOutlined /> {__("Analyze")}
                </Header>
                <Content style={{ margin: "24px 16px 0" }}>
                    <div className="rtg-dialog-content">
                        {!isPro && showProHints && <ProFooter />}
                        <Spin spinning={statsStore.busy}>
                            <div>
                                {analyzeBusy ? (
                                    <button className="button" onClick={analyzePromise.cancel}>
                                        {__("Cancel (%d of %d analyzed)", analyzed.length, imagesCount)}
                                    </button>
                                ) : (
                                    <Fragment>
                                        <button key="1" className="button-primary" onClick={handleStart}>
                                            {__("Analyze all attachments")}
                                        </button>
                                        {(showProHints || isPro) && (
                                            <Fragment>
                                                <button
                                                    key="2"
                                                    className="button"
                                                    disabled={deletableSpace <= 0 || !isPro}
                                                    style={{ marginLeft: 10 }}
                                                    onClick={handleClear}
                                                >
                                                    {__("Delete unused thumbnails")}
                                                </button>
                                                &nbsp;
                                                <ProTag feature="delete-unused-mass" />
                                            </Fragment>
                                        )}
                                    </Fragment>
                                )}
                            </div>
                            <AnalyseResult
                                legend={<CopyOutlined />}
                                style={{ display: "inline-block", marginRight: 10 }}
                            >
                                <li>{_n("%d image", "%d images", imagesCount, imagesCount)}</li>
                                <li>
                                    {_n(
                                        "%d image incl. thumbnails",
                                        "%d images incl. thumbnails",
                                        totalCount,
                                        totalCount,
                                    )}
                                </li>
                            </AnalyseResult>
                            <AnalyseResult
                                legend={<ScanOutlined />}
                                style={{ display: "inline-block", marginRight: 10 }}
                            >
                                <li>
                                    {_n(
                                        "%d thumbnail needs to be generated",
                                        "%d thumbnails need to be generated",
                                        newThumbnailsCount,
                                        newThumbnailsCount,
                                    )}
                                </li>
                            </AnalyseResult>
                            <AnalyseResult
                                legend={<DeleteOutlined />}
                                style={{ display: "inline-block", marginRight: 10 }}
                            >
                                <li>{__("%s unused", deletableSpaceFormat)}</li>
                            </AnalyseResult>
                        </Spin>
                        {(analyzeBusy || analyzed.length > 0) && (
                            <Progress
                                percent={Math.round((analyzed.length / imagesCount) * 100)}
                                status={analyzeBusy ? "active" : "success"}
                            />
                        )}
                        <AnalyseItems
                            attachments="analyzedObjects"
                            onClick={onClick}
                            fallback={
                                <div
                                    className="rtg-grow"
                                    style={{ justifyContent: "center", alignItems: "center", display: "flex" }}
                                >
                                    <button className="button-primary" onClick={handleStart}>
                                        {__("Start the analysis to see the results for all your uploads")}
                                    </button>
                                </div>
                            }
                            buttonRight={
                                <button
                                    className="button-primary"
                                    onClick={() =>
                                        document
                                            .querySelector<HTMLLIElement>(
                                                `li[data-id="rtg-dialog-menu-item-regenerate"]`,
                                            )
                                            .click()
                                    }
                                >
                                    <ScanOutlined /> {__("Start regenerating")}
                                </button>
                            }
                        />
                    </div>
                </Content>
                <AnalyseFooter />
            </Layout>
        );
    },
);

export { AnalyseContent };
