#include "authdialog.h"
#include "ui_authdialog.h"
#include "../authmanager.h"

AuthDialog::AuthDialog(QWidget *parent)
    : QDialog{parent}, ui(new Ui::Dialog)
{
  ui->setupUi(this);

  // Connect button signals
  connect(ui->sendCodeButton, &QPushButton::clicked, this, &AuthDialog::onSendCodeClicked);
  connect(ui->signInButton, &QPushButton::clicked, this, &AuthDialog::onSignInClicked);
  connect(ui->goBackButton, &QPushButton::clicked, this, &AuthDialog::showEmailPage);

  // Start on email page
  showEmailPage();
}

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

void AuthDialog::reset()
{
  ui->emailLineEdit->clear();
  ui->codeLineEdit->clear();
  clearError();
  showEmailPage();
}

void AuthDialog::showEmailPage()
{
  ui->stackedWidget->setCurrentIndex(0);
  ui->emailLineEdit->setFocus();
  clearError();
}

void AuthDialog::showCodePage()
{
  ui->stackedWidget->setCurrentIndex(1);
  ui->codeLineEdit->setFocus();
  clearError();
}

void AuthDialog::clearError()
{
  ui->errorMessage->setText("");
  ui->errorMessage->setVisible(false);
  ui->codeErrorMessage->setText("");
  ui->codeErrorMessage->setVisible(false);
}

void AuthDialog::showError(const QString &message)
{
  if (ui->stackedWidget->currentIndex() == 0)
  {
    // Update error labels on both pages
    ui->errorMessage->setText(message);
    ui->errorMessage->setVisible(true);
  }
  else
  {
    ui->codeErrorMessage->setText(message);
    ui->codeErrorMessage->setVisible(true);
  }
}

void AuthDialog::onSendCodeClicked()
{
  QString email = ui->emailLineEdit->text().trimmed();
  if (email.isEmpty())
  {
    showError("Please enter your email");
    return;
  }

  clearError();
  emit codeRequested(email);
}

void AuthDialog::onCodeSentToEmail(const QString &email)
{
  showCodePage();
}

void AuthDialog::onSignInClicked()
{
  QString code = ui->codeLineEdit->text().trimmed();
  if (code.isEmpty())
  {
    showError("Please enter the code");
    return;
  }

  clearError();
  emit signInRequested(code);
}
