#include "user_list_widget.h"
#include <QVBoxLayout>
#include <QListWidgetItem>
#include <QPainter>
#include <QFont>

namespace scar {

UserListWidget::UserListWidget(QWidget* parent)
    : QWidget(parent) {
    
    auto* layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    
    auto* titleLabel = new QLabel("Users", this);
    titleLabel->setStyleSheet("font-weight: bold; padding: 5px;");
    layout->addWidget(titleLabel);
    
    listWidget_ = new QListWidget(this);
    listWidget_->setStyleSheet("QListWidget { border: none; }");
    layout->addWidget(listWidget_);
}

void UserListWidget::addUser(const UserInfo& user) {
    auto* item = new QListWidgetItem(listWidget_);
    
    // Use avatar if available, otherwise create "SC" placeholder
    QPixmap avatar = user.avatar.isNull() ? createDefaultAvatar() : user.avatar;
    
    item->setIcon(QIcon(avatar));
    item->setText(user.username);
    item->setToolTip(user.status);
    
    listWidget_->addItem(item);
}

void UserListWidget::removeUser(const QString& username) {
    for (int i = 0; i < listWidget_->count(); ++i) {
        if (listWidget_->item(i)->text() == username) {
            delete listWidget_->takeItem(i);
            break;
        }
    }
}

void UserListWidget::updateUserStatus(const QString& username, const QString& status) {
    for (int i = 0; i < listWidget_->count(); ++i) {
        auto* item = listWidget_->item(i);
        if (item->text() == username) {
            item->setToolTip(status);
            break;
        }
    }
}

void UserListWidget::clear() {
    listWidget_->clear();
}

int UserListWidget::userCount() const {
    return listWidget_->count();
}

QPixmap UserListWidget::createDefaultAvatar() {
    QPixmap pixmap(48, 48);
    pixmap.fill(QColor("#5865F2")); // Discord-like blue
    
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    
    QFont font;
    font.setPixelSize(20);
    font.setBold(true);
    painter.setFont(font);
    painter.setPen(Qt::white);
    
    painter.drawText(pixmap.rect(), Qt::AlignCenter, "SC");
    
    return pixmap;
}

} // namespace scar
