#include "networkdetailwidget.h"
#include <QInputDialog>
#include <QLabel>
#include <QListWidget>
#include <QProgressBar>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>

NetworkDetailWidget::NetworkDetailWidget(QWidget *parent)
    : QWidget(parent)
{
  auto *layout = new QVBoxLayout(this);
  layout->setContentsMargins(16, 16, 16, 16);

  // Network name
  m_nameLabel = new QLabel(this);
  QFont nameFont;
  nameFont.setPointSize(24);
  m_nameLabel->setFont(nameFont);
  layout->addWidget(m_nameLabel);

  // Admin label
  m_adminLabel = new QLabel(this);
  layout->addWidget(m_adminLabel);

  // Stream capacity progress bar
  m_streamBar = new QProgressBar(this);
  m_streamBar->setMinimum(0);
  m_streamBar->setTextVisible(false);
  layout->addWidget(m_streamBar);

  m_streamBarLabel = new QLabel(this);
  layout->addWidget(m_streamBarLabel);

  layout->addStretch();

  // Members header
  auto *membersHeader = new QLabel("Members", this);
  QFont headerFont;
  headerFont.setBold(true);
  membersHeader->setFont(headerFont);
  layout->addWidget(membersHeader);

  // Members list
  m_membersList = new QListWidget(this);
  layout->addWidget(m_membersList, 1);

  // Button row
  auto *buttonRow = new QHBoxLayout;
  m_addMemberBtn = new QPushButton("Add Member", this);
  buttonRow->addWidget(m_addMemberBtn);
  buttonRow->addStretch();
  layout->addLayout(buttonRow);

  connect(m_addMemberBtn, &QPushButton::clicked, this, [this]() {
    bool ok;
    QString email = QInputDialog::getText(this, "Add Member",
                                          "Email address:", QLineEdit::Normal,
                                          QString(), &ok);
    if (ok && !email.isEmpty())
    {
      emit addMemberRequested(m_networkId, email);
    }
  });
}

void NetworkDetailWidget::setNetwork(const Network &network, const QString &currentUserEmail)
{
  m_networkId = network.id;

  m_nameLabel->setText(network.name);
  m_adminLabel->setText("Admin: " + network.admin.emailPrefix);

  m_streamBar->setMaximum(network.openStreamCapacity > 0 ? network.openStreamCapacity : 1);
  m_streamBar->setValue(network.openStreamCount);
  m_streamBarLabel->setText(QString("%1 / %2 open streams")
                                .arg(network.openStreamCount)
                                .arg(network.openStreamCapacity));

  m_membersList->clear();
  for (const auto &member : network.members)
  {
    m_membersList->addItem(member.email);
  }

  bool isAdmin = (!currentUserEmail.isEmpty() &&
                  currentUserEmail == network.admin.email);
  m_addMemberBtn->setVisible(isAdmin);
}

void NetworkDetailWidget::clear()
{
  m_networkId.clear();
  m_nameLabel->setText("");
  m_adminLabel->setText("");
  m_streamBar->setValue(0);
  m_streamBarLabel->setText("");
  m_membersList->clear();
  m_addMemberBtn->hide();
}
