#include "nowPlaying.h"
#include <QVBoxLayout>
#include <QFileInfo>
#include <QCloseEvent>
#include "src/data/cleanerScripts.h"

NowPlaying::NowPlaying(const AlbumData& item, QWidget* parent)
    : QWidget(parent), item_(item)
{
    setWindowTitle("Now Playing");
    resize(350, 600);

    QVBoxLayout* layout = new QVBoxLayout(this);

    // Album artwork
    spinningArt_ = new SpinningAlbumArt(item.imagePath, 250);
    layout->addWidget(spinningArt_, 0, Qt::AlignCenter);

    // Track label
    trackLabel_ = new QLabel("Track");
    trackLabel_->setAlignment(Qt::AlignCenter);
    trackLabel_->setStyleSheet("font-size: 20px; font-weight: 700; margin-top: 10px");
    layout->addWidget(trackLabel_);

    // Time played in Song Indicator
    timeIndicator_ = new TimePlayedWidget(this);
    layout->addWidget(timeIndicator_);

    // Volume slider
    volumeSlider_ = new QSlider(Qt::Horizontal);
    volumeSlider_->setRange(0, 100);
    volumeSlider_->setValue(80);
    volumeSlider_->setStyleSheet("margin: 0 12px;");
    layout->addWidget(volumeSlider_);

    // Track list widget
    trackList_ = new TrackListWidget(item_.audioFiles, this);
    layout->addWidget(trackList_);

    // Audio backend
    player_ = new QMediaPlayer(this);
    audio_ = new QAudioOutput(this);
    player_->setAudioOutput(audio_);

    audio_->setVolume(0.8f);
    connect(volumeSlider_, &QSlider::valueChanged, this,
            [this](int v){ audio_->setVolume(v / 100.0); });

    // Spin album art based on playback
    connect(player_, &QMediaPlayer::playbackStateChanged, this,
            [this](QMediaPlayer::PlaybackState st){
                if (st == QMediaPlayer::PlayingState)
                    spinningArt_->start();
                else
                    spinningArt_->stop();
            });

    // Song duration + position
    connect(player_, &QMediaPlayer::durationChanged,
            timeIndicator_, &TimePlayedWidget::setDuration);

    connect(player_, &QMediaPlayer::positionChanged,
            timeIndicator_, &TimePlayedWidget::setPosition);

    // Pause/Play toggle on art click
    connect(spinningArt_, &SpinningAlbumArt::artClicked, this, [this]() {
        if (player_->playbackState() == QMediaPlayer::PlayingState) {
            player_->pause();
            spinningArt_->stop();
        } else {
            player_->play();
            spinningArt_->start();
        }
    });

    // Auto-next on finish
    connect(player_, &QMediaPlayer::mediaStatusChanged, this,
            [this](QMediaPlayer::MediaStatus st){
                if (st == QMediaPlayer::EndOfMedia)
                    handleTrackFinished();
            });

    // Track selected in list
    connect(trackList_, &TrackListWidget::trackSelected, this,
            [this](int i){
                index_ = i;
                playTrack(index_);
            });

    // Start with track 0
    playTrack(index_);
}

void NowPlaying::playTrack(int idx)
{
    if (idx < 0 || idx >= item_.audioFiles.size())
        return;

    index_ = idx;

    QString filePath = item_.audioFiles[idx];
    QString fileName = QFileInfo(filePath).fileName();
    QString title = cleanTrackTitle(fileName);

    // NEW — Window title updates dynamically
    setWindowTitle(QStringLiteral("%1 - %2")
                       .arg(item_.artist, title));

    trackLabel_->setText(QString(title));

    player_->setSource(QUrl::fromLocalFile(filePath));
    player_->play();

    // Highlight in the list
    trackList_->setCurrentRow(idx);
}

void NowPlaying::handleTrackFinished()
{
    int nextIndex = index_ + 1;

    if (nextIndex >= item_.audioFiles.size()) {
        close();
        return;
    }

    playTrack(nextIndex);
}

void NowPlaying::closeEvent(QCloseEvent* event)
{
    if (player_)
        player_->stop();

    QWidget::closeEvent(event);
}
