#include "settingsdialog.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QPushButton>
#include <QStackedWidget>
#include <QVBoxLayout>

SettingsDialog::SettingsDialog(QWidget *parent)
    : QDialog(parent)
{
  buildUi();

  setModal(true);

  m_listWidget->addItem("Account");
  m_listWidget->addItem("Create Network");

  connect(m_listWidget, &QListWidget::currentRowChanged,
          m_stackedWidget, &QStackedWidget::setCurrentIndex);

  m_listWidget->setCurrentRow(0);

  connect(m_signOutButton, &QPushButton::clicked, this, [this]() {
    emit signOutRequested();
    close();
  });

  connect(m_createNetworkButton, &QPushButton::clicked, this, [this]() {
    QString name = m_networkNameEdit->text().trimmed();
    if (name.isEmpty())
      return;
    emit createNetworkRequested(name);
    m_networkNameEdit->clear();
  });
}

void SettingsDialog::setAuthLabel(const QString &text)
{
  m_authLabel->setText(text);
}

void SettingsDialog::buildUi()
{
  resize(600, 500);
  setWindowTitle("Settings");

  auto *mainLayout = new QHBoxLayout(this);

  m_listWidget = new QListWidget();
  m_listWidget->setMaximumWidth(220);
  mainLayout->addWidget(m_listWidget);

  m_stackedWidget = new QStackedWidget();
  mainLayout->addWidget(m_stackedWidget);

  // ── Account page ──
  auto *accountPage = new QWidget();
  auto *accountLayout = new QVBoxLayout(accountPage);

  accountLayout->addStretch();

  m_authLabel = new QLabel("Hello, ");
  m_authLabel->setAlignment(Qt::AlignCenter);
  accountLayout->addWidget(m_authLabel);

  m_signOutButton = new QPushButton("Sign Out");
  accountLayout->addWidget(m_signOutButton);

  accountLayout->addStretch();

  m_stackedWidget->addWidget(accountPage);

  // ── Create Network page ──
  auto *createNetworkPage = new QWidget();
  auto *createNetworkLayout = new QVBoxLayout(createNetworkPage);

  auto *createNetworkLabel = new QLabel("Create a new network");
  QFont labelFont;
  labelFont.setPointSize(16);
  createNetworkLabel->setFont(labelFont);
  createNetworkLayout->addWidget(createNetworkLabel);

  m_networkNameEdit = new QLineEdit();
  m_networkNameEdit->setPlaceholderText("Network name");
  createNetworkLayout->addWidget(m_networkNameEdit);

  m_createNetworkButton = new QPushButton("Create");
  createNetworkLayout->addWidget(m_createNetworkButton);

  createNetworkLayout->addStretch();

  m_stackedWidget->addWidget(createNetworkPage);
}
