#include "FormLogin.h"
#include "ui_FormLogin.h"

#include <QLineEdit>
#include <QScreen>
#include <QDebug>
#include <QTimer>
#include <QWindow>
#include <QDesktopWidget>
#include <QDBusInterface>
#include <QDBusReply>
#include <QPropertyAnimation>
#include <QGraphicsDropShadowEffect>

#include "ConfigManager.h"
#include "LanguageManager.h"
#include "LoggerHelper.h"

FormLogin::FormLogin(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::FormLogin)
{
    ui->setupUi(this);
    
    setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);

    initWidget();

    initConnect();
}

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

void FormLogin::setBackground(QLabel *label, const QString &imageUrl)
{
    if (!label) {
        LOG_WARNING("Invalid label pointer");
        return;
    }
    QPixmap pixmap(imageUrl);
    if (!pixmap.isNull()) {
        label->setAlignment(Qt::AlignCenter);
        label->setPixmap(pixmap);
    } else {
        LOG_WARNING("Failed to load background image:" + imageUrl);
    }
}

void FormLogin::initWidget()
{
    this->setAttribute(Qt::WA_TranslucentBackground);

    backgroundImage = new QLabel();

    // 将背景 Label 添加到布局，并占据全部单元格
    ui->gridLayout->addWidget(backgroundImage,
                              0,
                              0,
                              ui->gridLayout->rowCount(),
                              ui->gridLayout->columnCount());

    // 叠加显示背景图，将背景图显示在底层
    setBackground(backgroundImage, ":/images/login/login_background.png");
    backgroundImage->lower();
    backgroundImage->setScaledContents(true);

    setLineeditBackground();
    setButtonBackground();

    // 在构造函数中
    if (QGuiApplication::platformName().contains("wayland")) {
        setWindowFlags(windowFlags() |
                       Qt::FramelessWindowHint |
                       Qt::WindowStaysOnTopHint |
                       Qt::BypassWindowManagerHint);
    }

    initComboBox();
}

void FormLogin::initComboBox()
{
    ui->username->addItem(tr("Operator"));
    ui->username->addItem(tr("Administrator"));
}

void FormLogin::setLineeditBackground()
{
    // 用户名
    lineEdit_bg_image_1 = new QLabel();
    lineEdit_bg_image_1->setPixmap(QPixmap(":/images/login/linedit_background.png"));
    lineEdit_bg_image_1->setScaledContents(true);
    lineEdit_bg_image_1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->username_layout->addWidget(lineEdit_bg_image_1, 0, 0, 1, 1);
    ui->username->raise();

    // 密码
    lineEdit_bg_image_2 = new QLabel();
    lineEdit_bg_image_2->setPixmap(QPixmap(":/images/login/linedit_background.png"));
    lineEdit_bg_image_2->setScaledContents(true);
    lineEdit_bg_image_2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->password_layout->addWidget(lineEdit_bg_image_2, 0, 0, 1, 1);
    ui->password->raise();
}

void FormLogin::setButtonBackground()
{
    // 取消按钮
    btn_bg_image_1 = new QLabel();
    btn_bg_image_1->setPixmap(QPixmap(":/images/login/login_btn_background.png"));
    btn_bg_image_1->setScaledContents(true);
    btn_bg_image_1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->btn_layout->addWidget(btn_bg_image_1, 0, 0, 1, 1);
    ui->cancel->raise();

    // 登录按钮
    btn_bg_image_2 = new QLabel();
    btn_bg_image_2->setPixmap(QPixmap(":/images/login/login_btn_background.png"));
    btn_bg_image_2->setScaledContents(true);
    btn_bg_image_2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->btn_layout->addWidget(btn_bg_image_2, 0, 2, 1, 1);
    ui->login->raise();
}

void FormLogin::initConnect()
{
    // 监听全局键盘事件
    connect(QGuiApplication::inputMethod(), &QInputMethod::visibleChanged,
            this, &FormLogin::onKeyboardVisibilityChanged);

    // 取消按钮点击事件
    connect(ui->cancel, &QPushButton::clicked, this, [this]() {
        this->hide();
    });

    // 登录按钮点击事件
    connect(ui->login, &QPushButton::clicked, this, &FormLogin::slotLoginClicked);

    connect(LanguageManager::instance(), &LanguageManager::languageChanged, this, [this]() { ui->retranslateUi(this); });
}

bool FormLogin::keyboardVisible()
{
    // 实现检测键盘是否弹出（平台相关）
    // 例如：检查焦点是否在QLineEdit上
    return focusWidget() && qobject_cast<QLineEdit*>(focusWidget());
}

void FormLogin::setTips(const bool &username, const bool &pwd)
{
    if (!username) {
        ui->tips->setText(tr("Tips : User name does not exist, please re-enter!"));
    }

    if (!pwd) {
        ui->tips->setText(tr("Tips : Password input error, please re-enter!"));
    }

    if (!username && !pwd) {
        ui->tips->setText(tr("Tips : Username && Password input error, please re-enter!"));
    }
}

void FormLogin::centerWindow()
{
    // 确保窗口尺寸已确定（关键修复）
    this->ensurePolished();
    // this->adjustSize();

    // 获取有效的屏幕几何尺寸（考虑多显示器）
    QScreen *screen = QGuiApplication::primaryScreen();
    if (QWindow *window = this->windowHandle()) {
        screen = window->screen();
    }
    QRect screenGeometry = screen->availableGeometry();

    // 计算居中位置（考虑Wayland特性）
    int x = (screenGeometry.width() - this->width()) / 2 + screenGeometry.x();
    int y = (screenGeometry.height() - this->height()) / 2 + screenGeometry.y();

    if (QGuiApplication::platformName().contains("wayland")) {
        // Wayland专用处理
        if (QWindow *window = this->windowHandle()) {
            // 重要：延迟设置位置，确保Wayland合成器已准备好
            QTimer::singleShot(100, this, [window, x, y]() {
                window->setPosition(QPoint(x, y));

                // 替代requestActivate的方案
                window->setFlags(window->flags() | Qt::WindowStaysOnTopHint);
                QTimer::singleShot(50, [window]() {
                    window->setFlags(window->flags() & ~Qt::WindowStaysOnTopHint);
                });
            });
        }
    } else {
        // 传统X11处理
        this->move(x, y);
    }
}

void FormLogin::onKeyboardVisibilityChanged()
{
    QInputMethod *im = QGuiApplication::inputMethod();
    if (im->isVisible()) {
        // 保存原始位置
        m_originalPos = pos();
        // 计算键盘高度（更准确的方式）
        int keyboardHeight = QGuiApplication::primaryScreen()->geometry().height() / 2;

        // 确保窗口不会与键盘重叠
        QRect screenGeo = screen()->availableGeometry();
        QRect widgetGeo = this->geometry();
        int newY = qMin(widgetGeo.y(),
                        screenGeo.bottom() - keyboardHeight - widgetGeo.height() - 20);
        if (newY != widgetGeo.bottom()) {
            move(widgetGeo.x(), newY);
        }
    } else {
        // 恢复原始位置（带动画效果更友好）
        QPropertyAnimation *anim = new QPropertyAnimation(this, "pos");
        anim->setDuration(100);
        anim->setEndValue(m_originalPos);
        anim->start(QAbstractAnimation::DeleteWhenStopped);
    }
}

void FormLogin::slotLoginClicked()
{
    auto username = ui->username->currentText();
    auto pwd = ui->password->text();

    // 后续添加读取配置文件中的管理员账号和密码
    auto admin_cfg = ConfigManager::instance()->getAdminConfig();

    if (username == admin_cfg.username && pwd == admin_cfg.password) {
        this->hide();
        emit showSetings(1);
    } else {
        setTips(false, false);
    }
}

void FormLogin::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);

    centerWindow();

    m_originalPos = pos();
}
