import { Avatar, Form } from "antd";
import { useCallback, useMemo } from "react";

import { EMachineTranslationStatus } from "@devowl-wp/api";
import { jsxJoin } from "@devowl-wp/react-utils";

import { FormServiceLayout } from "./layout.js";
import { useFormContentBlocker } from "../../contexts/formContentBlocker.js";
import { useFormService } from "../../contexts/formService.js";
import { useI18n } from "../../contexts/i18n.js";
import { Notices } from "../common/notices.js";

import type { FC } from "react";

const FormUntranslatedTemplateNotice: FC<{ form: "service" | "blocker" }> = ({ form }) => {
    const { __, _i } = useI18n();
    const { template } = form === "service" ? useFormService() : useFormContentBlocker();

    type Translation = (typeof template)["consumerData"]["translations"][string];

    const { languagesCount, untranslatedItems, translatedItems, machineTranslatedItems } = useMemo(
        () =>
            Object.values(template?.consumerData?.translations || {}).reduce(
                (acc, translation) => {
                    if (translation.isUntranslated) {
                        acc.untranslatedItems.push(translation);
                    } else if (translation.machineTranslationStatus === EMachineTranslationStatus.Full) {
                        // We only show the fully machine translated items because we don't want to show a notice when only one component is machine translated
                        // as this is not practicable (imagine changing the language of a single component).
                        acc.machineTranslatedItems.push(translation);
                    } else {
                        acc.translatedItems.push(translation);
                    }

                    acc.languagesCount += 1;
                    return acc;
                },
                {
                    languagesCount: 0,
                    untranslatedItems: [] as Translation[],
                    translatedItems: [] as Translation[],
                    machineTranslatedItems: [] as Translation[],
                },
            ),
        [template],
    );

    const createJoinedLanguagesWithFlags = useCallback(
        (items: Translation[]) =>
            jsxJoin(
                items.map(({ flag, language, name }) => (
                    <>
                        {flag && (
                            <Avatar
                                src={flag}
                                size={13}
                                shape="square"
                                style={{ display: "inline-block", width: "auto", borderRadius: 5, marginRight: 4 }}
                                key={language}
                            >
                                {language.toUpperCase()}
                            </Avatar>
                        )}
                        {name || language.toUpperCase()}
                    </>
                )),
                (i, length) => (i === length - 1 ? __(" and ") : ", "),
            ),
        [],
    );

    return untranslatedItems.length > 0 || machineTranslatedItems.length > 0 ? (
        <Form.Item wrapperCol={{ offset: FormServiceLayout.labelCol.span, span: FormServiceLayout.wrapperCol.span }}>
            <Notices
                notices={[
                    {
                        nop: true,
                        severity: "info",
                        message: (
                            <>
                                {untranslatedItems.length > 0 && (
                                    <p>
                                        {_i(
                                            __(
                                                "This template is {{strong}}not yet translated{{/strong}} into {{languages/}}. Feel free to translate it yourself!",
                                            ),
                                            {
                                                strong: <strong />,
                                                languages: createJoinedLanguagesWithFlags(untranslatedItems),
                                            },
                                        )}
                                    </p>
                                )}
                                {machineTranslatedItems.length > 0 && (
                                    <p>
                                        {_i(
                                            languagesCount === 1
                                                ? __(
                                                      "This template has been automatically machine translated into {{machineTranslatedLanguages/}}. Please check all texts carefully!",
                                                  )
                                                : translatedItems.length > 1
                                                  ? __(
                                                        "This template has been translated into {{humanTranslatedLanguages/}} by humans. However, translations in {{machineTranslatedLanguages/}} have so far only been machine translated and not checked by a human translator. Please check the text in the mentioned languages carefully!",
                                                    )
                                                  : __(
                                                        "This template has so far only been machine translated in {{machineTranslatedLanguages/}} and has not been checked by a human translator. Please check the text carefully in the languages mentioned!",
                                                    ),
                                            {
                                                strong: <strong />,
                                                machineTranslatedLanguages:
                                                    createJoinedLanguagesWithFlags(machineTranslatedItems),
                                                humanTranslatedLanguages:
                                                    createJoinedLanguagesWithFlags(translatedItems),
                                            },
                                        )}
                                    </p>
                                )}
                            </>
                        ),
                    },
                ]}
            />
        </Form.Item>
    ) : null;
};

export { FormUntranslatedTemplateNotice };
