#include "src/windows/albumSelector/albumSelector.h"
#include "src/components/albumSelector/albumTile/albumTile.h"
#include "src/windows/nowPlaying/nowPlaying.h"
#include "src/layout/flowlayout/flowLayout.h"

#include <QDir>
#include <QCoreApplication>
#include <QFileInfo>

AlbumSelector::AlbumSelector(QWidget* parent)
    : QWidget(parent)
{
    setWindowTitle("Album Selector");
    resize(900, 600);

    // Use Qt Flow Layout Library
    auto* flow = new FlowLayout(this, 20, 20, 20);  // margin, h, v
    setLayout(flow);

    // Set Media Folder
    QString projectRoot = QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("../../../../.."); // Escape the .app bundle

    // Now manually append your real resources dir:
    QString mediaFolder = projectRoot + "/resources/media";

    // Debug Media Path
    qDebug() << "projectRoot:" << projectRoot;
    qDebug() << "mediaFolder:" << mediaFolder;

    // Scan the /media Folder
    QList<AlbumData> items = scanFolder(mediaFolder);

    for (const AlbumData& item : items)
    {
        AlbumTile* tile = new AlbumTile(item);
        flow->addWidget(tile);

        connect(tile, &AlbumTile::activated, this, [this](const AlbumData& it) {
            auto* player = new NowPlaying(it);
            player->show();
        });
    }
}

QList<AlbumData> AlbumSelector::scanFolder(const QString& root)
{
    QList<AlbumData> results;

    QDir mediaRoot(root);
    mediaRoot.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);

    // Loop over artists
    for (const QFileInfo& artistInfo : mediaRoot.entryInfoList())
    {
        QDir artistDir(artistInfo.absoluteFilePath());
        artistDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);

        // Loop over albums inside artist
        for (const QFileInfo& albumInfo : artistDir.entryInfoList())
        {
            QDir albumDir(albumInfo.absoluteFilePath());

            QString image;
            QStringList audioFiles;

            // Loop files in album directory
            for (const QFileInfo& f : albumDir.entryInfoList(QDir::Files))
            {
                QString ext = f.suffix().toLower();

                if (ext == "jpg" || ext == "jpeg" || ext == "png")
                    if (image.isEmpty()) image = f.absoluteFilePath();

                if (ext == "mp3" || ext == "wav" || ext == "flac" || ext == "m4a")
                    audioFiles.append(f.absoluteFilePath());
            }

            // Only add if album valid
            if (!image.isEmpty() && !audioFiles.isEmpty())
            {
                AlbumData m;
                m.folderPath = albumDir.absolutePath();
                m.imagePath = image;
                m.audioFiles = audioFiles;
                m.artist = artistInfo.fileName();      // <--- add this
                m.album  = albumInfo.fileName();
                results.append(m);
            }
        }
    }

    return results;
}
