/*
   SPDX-FileCopyrightText: 2025-2026 Laurent Montel <montel@kde.org>

   SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "autogenerateanswerseditorinterface.h"
#include "autogenerateanswerseditordialog.h"
#include "autogenerateanswerseditorplugin_debug.h"
#include <KActionCollection>
#include <KLocalizedString>
#include <KMessageBox>
#include <QAction>
#include <QMenu>
#include <QTextCursor>
#include <TextAutoGenerateText/TextAutoGenerateAskJob>
#include <TextAutoGenerateText/TextAutoGenerateDialog>
#include <TextAutoGenerateText/TextAutoGenerateMessageUtils>
#include <TextAutoGenerateText/TextAutoGenerateTextInstancesManagerDialog>
#include <TextCustomEditor/RichTextEditor>

using namespace Qt::Literals::StringLiterals;
AutoGenerateAnswersEditorInterface::AutoGenerateAnswersEditorInterface(QObject *parent)
    : MessageComposer::PluginEditorInterface(parent)
{
}

AutoGenerateAnswersEditorInterface::~AutoGenerateAnswersEditorInterface() = default;

void AutoGenerateAnswersEditorInterface::createAction(KActionCollection *ac)
{
    auto action = new QAction(i18nc("@action", "Autogenerate Answer"), this);
    ac->addAction(u"quick_answer"_s, action);
    MessageComposer::PluginActionType type(action, MessageComposer::PluginActionType::Edit);
    setActionType(type);
    auto menu = new QMenu(parentWidget());
    auto act = menu->addAction(i18nc("@action", "Summary Text"));
    connect(act, &QAction::triggered, this, [this]() {
        mAnswerType = AnswerType::SummaryText;
        Q_EMIT emitPluginActivated(this);
    });

    act = menu->addAction(i18nc("@action", "Correct Text"));
    connect(act, &QAction::triggered, this, [this]() {
        mAnswerType = AnswerType::FixTypo;
        Q_EMIT emitPluginActivated(this);
    });

    act = menu->addAction(i18nc("@action", "Quick Answer"));
    connect(act, &QAction::triggered, this, [this]() {
        mAnswerType = AnswerType::QuickAnswer;
        Q_EMIT emitPluginActivated(this);
    });
    act = new QAction(menu);
    act->setSeparator(true);
    menu->addAction(act);

    act = menu->addAction(i18nc("@action", "Configure AI"));
    connect(act, &QAction::triggered, this, &AutoGenerateAnswersEditorInterface::slotConfigure);

    action->setMenu(menu);
}

void AutoGenerateAnswersEditorInterface::slotConfigure()
{
    TextAutoGenerateText::TextAutoGenerateTextInstancesManagerDialog dlg(mManager, parentWidget());
    mManager->loadEngine();
    dlg.exec();
}

void AutoGenerateAnswersEditorInterface::exec()
{
    QString actionStr;
    switch (mAnswerType) {
    case AnswerType::Unknown:
        qCWarning(KMAIL_EDITOR_AUTOGENERATEANSWER_PLUGIN_LOG) << "AnswerType::Unknown: it's a bug";
        return;
    case AnswerType::SummaryText:
        actionStr = QStringLiteral("Summary Text");
        break;
    case AnswerType::QuickAnswer:
        actionStr = QStringLiteral("Quick Answer");
        break;
    case AnswerType::FixTypo:
        actionStr = QStringLiteral("Correct Text");
        break;
    }
    QTextCursor textCursor = richTextEditor()->textCursor();
    QString str = textCursor.selectedText();
    if (str.isEmpty()) {
        str = richTextEditor()->toPlainText();
    }

    qCDebug(KMAIL_EDITOR_AUTOGENERATEANSWER_PLUGIN_LOG) << "add text: " << str;

    auto job = new TextAutoGenerateText::TextAutoGenerateAskJob(this);
    job->setManager(mManager);
    job->setText(QStringLiteral("%1: \"%2\"").arg(actionStr, str));
    connect(job,
            &TextAutoGenerateText::TextAutoGenerateAskJob::generateTextInProgress,
            this,
            [this](const TextAutoGenerateText::TextAutoGenerateReply::Response &response) {
                slotGenerateTextInProgress(response.response);
            });
    connect(job, &TextAutoGenerateText::TextAutoGenerateAskJob::errorOccured, this, &AutoGenerateAnswersEditorInterface::slotGenerateTextErrorOccured);
    job->start();
}

void AutoGenerateAnswersEditorInterface::slotGenerateTextInProgress(const QString &str)
{
    if (!mAnswersEditorDialog) {
        mAnswersEditorDialog = new AutoGenerateAnswersEditorDialog(parentWidget());
        connect(mAnswersEditorDialog, &AutoGenerateAnswersEditorDialog::insertText, this, &AutoGenerateAnswersEditorInterface::insertText);
        mAnswersEditorDialog->setAttribute(Qt::WA_DeleteOnClose);
        mAnswersEditorDialog->show();
    }
    int numberOfTextSearched = 0;
    int hightLightStringIndex = 0;
    mAnswersEditorDialog->setAnswer(
        TextAutoGenerateText::TextAutoGenerateMessageUtils::convertTextToHtml(str, {}, {}, numberOfTextSearched, hightLightStringIndex, false));
}

void AutoGenerateAnswersEditorInterface::slotGenerateTextErrorOccured(const QString &errorStr)
{
    qCWarning(KMAIL_EDITOR_AUTOGENERATEANSWER_PLUGIN_LOG) << "Error occured: " << errorStr;
    KMessageBox::error(parentWidget(), i18n("An error occured: %1", errorStr), i18n("Error"));
}

TextAutoGenerateText::TextAutoGenerateManager *AutoGenerateAnswersEditorInterface::manager() const
{
    return mManager;
}

void AutoGenerateAnswersEditorInterface::setManager(TextAutoGenerateText::TextAutoGenerateManager *newManager)
{
    mManager = newManager;
}

#include "moc_autogenerateanswerseditorinterface.cpp"
