#include "login_dialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QLabel>

namespace scar {

LoginDialog::LoginDialog(const QString& lastUsername,
                        const QString& lastServer,
                        uint16_t lastPort,
                        QWidget* parent)
    : QDialog(parent) {
    
    setWindowTitle("SCAR Chat - Login");
    setModal(true);
    setupUI();
    
    // Pre-fill last values
    usernameEdit_->setText(lastUsername);
    serverEdit_->setText(lastServer);
    portSpinBox_->setValue(lastPort);
}

void LoginDialog::setupUI() {
    auto* mainLayout = new QVBoxLayout(this);
    
    // Form layout for inputs
    auto* formLayout = new QFormLayout();
    
    usernameEdit_ = new QLineEdit(this);
    usernameEdit_->setPlaceholderText("Enter username");
    formLayout->addRow("Username:", usernameEdit_);
    
    passwordEdit_ = new QLineEdit(this);
    passwordEdit_->setEchoMode(QLineEdit::Password);
    passwordEdit_->setPlaceholderText("Enter password");
    formLayout->addRow("Password:", passwordEdit_);
    
    serverEdit_ = new QLineEdit(this);
    serverEdit_->setPlaceholderText("localhost");
    formLayout->addRow("Server:", serverEdit_);
    
    portSpinBox_ = new QSpinBox(this);
    portSpinBox_->setRange(1, 65535);
    portSpinBox_->setValue(8443);
    formLayout->addRow("Port:", portSpinBox_);
    
    mainLayout->addLayout(formLayout);
    
    // Buttons
    auto* buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    
    connectButton_ = new QPushButton("Connect", this);
    connectButton_->setDefault(true);
    connect(connectButton_, &QPushButton::clicked, this, &QDialog::accept);
    buttonLayout->addWidget(connectButton_);
    
    cancelButton_ = new QPushButton("Cancel", this);
    connect(cancelButton_, &QPushButton::clicked, this, &QDialog::reject);
    buttonLayout->addWidget(cancelButton_);
    
    mainLayout->addLayout(buttonLayout);
    
    setMinimumWidth(350);
}

QString LoginDialog::username() const {
    return usernameEdit_->text();
}

QString LoginDialog::server() const {
    return serverEdit_->text();
}

uint16_t LoginDialog::port() const {
    return static_cast<uint16_t>(portSpinBox_->value());
}

QString LoginDialog::password() const {
    return passwordEdit_->text();
}

} // namespace scar
