#include "reportissuedialog.h"
#include "qjsonarray.h"
#include "ui_reportissuedialog.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QNetworkRequest>

ReportIssueDialog::ReportIssueDialog(const QString &giteaBaseUrl,
                                     const QString &repoOwner,
                                     const QString &repoName,
                                     const QString &accessToken,
                                     QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ReportIssueDialog),
    networkManager(new QNetworkAccessManager(this)),
    giteaBaseUrl(giteaBaseUrl),
    repoOwner(repoOwner),
    repoName(repoName),
    accessToken(accessToken)
{
    ui->setupUi(this);

    connect(networkManager, &QNetworkAccessManager::finished, this, &ReportIssueDialog::onNetworkReplyFinished);
}

ReportIssueDialog::~ReportIssueDialog()
{
    delete ui;
}

void ReportIssueDialog::on_buttonSend_clicked()
{
    QString title = ui->lineEditSummary->text().trimmed();
    QString details = ui->textEditDetails->toPlainText().trimmed();
    QString contact = ui->lineEditContact->text().trimmed();

    if (title.isEmpty()) {
        QMessageBox::warning(this, tr("Input Error"), tr("Please enter a summary/title for the issue."));
        return;
    }

    QString body = details;
    if (!contact.isEmpty()) {
        body += QString("\n\nContact info:\n%1").arg(contact);
    }

    ui->buttonSend->setEnabled(false);
    sendIssueReport(title, body, contact);
}

void ReportIssueDialog::on_buttonCancel_clicked()
{
    reject();
}

void ReportIssueDialog::sendIssueReport(const QString &title, const QString &body, const QString &/*contact*/)
{
    // Compose URL: e.g. https://gitea.example.com/api/v1/repos/{owner}/{repo}/issues
    QUrl url(QString("%1/api/v1/repos/%2/%3/issues").arg(giteaBaseUrl).arg(repoOwner).arg(repoName));

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    if (!accessToken.isEmpty()) {
        request.setRawHeader("Authorization", "token " + accessToken.toUtf8());
    }

    // Compose JSON body
    QJsonObject json;
    json["title"] = title;
    json["body"] = body;
    json["labels"] = QJsonArray{12};

    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

    networkManager->post(request, data);
}

void ReportIssueDialog::onNetworkReplyFinished(QNetworkReply *reply)
{
    ui->buttonSend->setEnabled(true);

    QByteArray responseData = reply->readAll();
    QString responseStr = QString::fromUtf8(responseData);

    if (reply->error() != QNetworkReply::NoError) {
        QString errorStr = reply->errorString();
        if (errorStr.isEmpty()) errorStr = "Unknown network error";
        QMessageBox::critical(this, tr("Error"), tr("Failed to send issue report:\n%1\nResponse:\n%2").arg(errorStr).arg(responseStr));
    } else {
        int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        if (status == 201) {
            QMessageBox::information(this, tr("Success"), tr("Issue reported successfully!"));
            accept();
        } else {
            QMessageBox::warning(this, tr("Failed"), tr("Unexpected response from server (%1):\n%2").arg(status).arg(responseStr));
        }
    }
    reply->deleteLater();
}
