#include "ui/service_menu.h"
#include "menu_renderer.h"
#include "menu_option.h"
#include "resource.h"
#include "audio.h"
#include "section.h"
#include "screen.h"
#include "asset.h"
#include "param.h"

// Singleton
ServiceMenu *ServiceMenu::instance_ = nullptr;
void ServiceMenu::init() { ServiceMenu::instance_ = new ServiceMenu(); }
void ServiceMenu::destroy() { delete ServiceMenu::instance_; }
ServiceMenu *ServiceMenu::get() { return ServiceMenu::instance_; }

// Constructor
ServiceMenu::ServiceMenu()
    : current_settings_group_(SettingsGroup::MAIN),
      previous_settings_group_(current_settings_group_)
{
    auto element_text = Resource::get()->getText("04b_25_flat");
    auto title_text = Resource::get()->getText("04b_25_flat_2x");

    renderer_ = std::make_unique<MenuRenderer>(this, element_text, title_text);
    restart_message_ui_ = std::make_unique<UIMessage>(element_text, Lang::getText("[SERVICE_MENU] NEED_RESTART_MESSAGE"), param.service_menu.title_color);

    reset();
}

void ServiceMenu::toggle()
{
    enabled_ = !enabled_;
    if (!enabled_)
    {
        reset();
    }
}

void ServiceMenu::render()
{
    if (!enabled_)
        return;
    renderer_->render(this);

    // El mensaje de reinicio se dibuja por encima, así que lo gestionamos aquí
    const float MSG_X = param.game.game_area.center_x;
    const float MSG_Y = renderer_->getRect().y + 39.0f;
    restart_message_ui_->setPosition(MSG_X, MSG_Y);
    restart_message_ui_->render();
}

void ServiceMenu::update()
{
    if (!enabled_)
        return;

    renderer_->update(this);

    bool now_pending = Options::pending_changes.has_pending_changes;
    if (now_pending != last_pending_changes_)
    {
        now_pending ? restart_message_ui_->show() : restart_message_ui_->hide();
        last_pending_changes_ = now_pending;
    }
    restart_message_ui_->update();
}

void ServiceMenu::reset()
{
    selected_ = 0;
    main_menu_selected_ = 0;
    current_settings_group_ = SettingsGroup::MAIN;
    previous_settings_group_ = SettingsGroup::MAIN;
    initializeOptions();
    updateMenu();
    renderer_->setLayout(this); // Notifica al renderer para que calcule el layout inicial
}

// --- Lógica de Navegación ---
void ServiceMenu::setSelectorUp()
{
    if (display_options_.empty())
        return;
    selected_ = (selected_ > 0) ? selected_ - 1 : display_options_.size() - 1;
    playMenuSound();
}

void ServiceMenu::setSelectorDown()
{
    if (display_options_.empty())
        return;
    selected_ = (selected_ + 1) % display_options_.size();
    playMenuSound();
}

void ServiceMenu::adjustOption(bool adjust_up)
{
    if (display_options_.empty())
        return;
    auto &selected_option = display_options_.at(selected_);
    if (selected_option->getBehavior() == MenuOption::Behavior::ADJUST)
    {
        selected_option->adjustValue(adjust_up);
        applySettings();
        playMenuSound();
    }
}

void ServiceMenu::selectOption()
{
    if (display_options_.empty())
        return;
    if (current_settings_group_ == SettingsGroup::MAIN)
        main_menu_selected_ = selected_;
    auto &selected_option = display_options_.at(selected_);
    if (auto folder = dynamic_cast<FolderOption *>(selected_option))
    {
        previous_settings_group_ = current_settings_group_;
        current_settings_group_ = folder->getTargetGroup();
        selected_ = 0;
        updateMenu();
    }
    else if (selected_option->getBehavior() == MenuOption::Behavior::SELECT)
    {
        selected_option->executeAction();
    }
    playMenuSound();
}

void ServiceMenu::moveBack()
{
    if (current_settings_group_ == SettingsGroup::MAIN)
    {
        enabled_ = false;
        return;
    }
    current_settings_group_ = previous_settings_group_;
    selected_ = (current_settings_group_ == SettingsGroup::MAIN) ? main_menu_selected_ : 0;
    updateMenu();
    playMenuSound();
}

// --- Lógica Interna ---

void ServiceMenu::updateDisplayOptions()
{
    display_options_.clear();
    for (auto &option : options_)
    {
        if (option->getGroup() == current_settings_group_ && !option->isHidden())
        {
            display_options_.push_back(option.get());
        }
    }
    updateOptionPairs();
}

void ServiceMenu::updateOptionPairs()
{
    option_pairs_.clear();
    for (const auto &option : display_options_)
    {
        option_pairs_.emplace_back(option->getCaption(), option->getValueAsString());
    }
}

void ServiceMenu::updateMenu()
{
    title_ = settingsGroupToString(current_settings_group_);
    AdjustListValues();

    // Actualiza las opciones visibles
    updateDisplayOptions();

    // Notifica al renderer del cambio de layout
    renderer_->onLayoutChanged(this);
}

void ServiceMenu::applySettings()
{
    if (current_settings_group_ == SettingsGroup::VIDEO)
        applyVideoSettings();
    if (current_settings_group_ == SettingsGroup::AUDIO)
        applyAudioSettings();
    if (current_settings_group_ == SettingsGroup::SETTINGS)
        applySettingsSettings();

    // Actualiza los valores de las opciones
    updateOptionPairs();
}

void ServiceMenu::applyVideoSettings()
{
    Screen::get()->applySettings();
    auto option = getOptionByCaption(Lang::getText("[SERVICE_MENU] WINDOW_SIZE"));
    if (option)
        option->setHidden(Options::video.fullscreen);
    updateMenu(); // El menú debe refrescarse si algo se oculta
}

void ServiceMenu::applyAudioSettings()
{
    Audio::get()->applySettings();
}

void ServiceMenu::applySettingsSettings()
{
    auto option = getOptionByCaption(Lang::getText("[SERVICE_MENU] SHUTDOWN"));
    if (option)
        option->setHidden(!Options::settings.shutdown_enabled);
    updateMenu(); // El menú debe refrescarse si algo se oculta
}

MenuOption *ServiceMenu::getOptionByCaption(const std::string &caption) const
{
    for (const auto &option : options_)
    {
        if (option->getCaption() == caption)
        {
            return option.get();
        }
    }
    return nullptr;
}

// --- Getters y otros ---

ServiceMenu::GroupAlignment ServiceMenu::getCurrentGroupAlignment() const
{
    switch (current_settings_group_)
    {
    case SettingsGroup::VIDEO:
    case SettingsGroup::AUDIO:
    case SettingsGroup::SETTINGS:
        return GroupAlignment::LEFT;
    default:
        return GroupAlignment::CENTERED;
    }
}

size_t ServiceMenu::countOptionsInGroup(SettingsGroup group) const
{
    size_t count = 0;
    for (const auto &option : options_)
    {
        if (option->getGroup() == group && !option->isHidden())
        {
            count++;
        }
    }
    return count;
}

// Inicializa todas las opciones del menú
void ServiceMenu::initializeOptions()
{
    options_.clear();

    // --- Video ---
    options_.push_back(std::make_unique<BoolOption>(Lang::getText("[SERVICE_MENU] FULLSCREEN"), SettingsGroup::VIDEO, &Options::video.fullscreen));
    options_.push_back(std::make_unique<IntOption>(Lang::getText("[SERVICE_MENU] WINDOW_SIZE"), SettingsGroup::VIDEO, &Options::window.size, 1, Options::window.max_size, 1));
    options_.push_back(std::make_unique<BoolOption>(Lang::getText("[SERVICE_MENU] SHADERS"), SettingsGroup::VIDEO, &Options::video.shaders));
    options_.push_back(std::make_unique<BoolOption>(Lang::getText("[SERVICE_MENU] VSYNC"), SettingsGroup::VIDEO, &Options::video.v_sync));
    options_.push_back(std::make_unique<BoolOption>(Lang::getText("[SERVICE_MENU] INTEGER_SCALE"), SettingsGroup::VIDEO, &Options::video.integer_scale));

    // --- Audio ---
    options_.push_back(std::make_unique<BoolOption>(Lang::getText("[SERVICE_MENU] AUDIO"), SettingsGroup::AUDIO, &Options::audio.enabled));
    options_.push_back(std::make_unique<IntOption>(Lang::getText("[SERVICE_MENU] MAIN_VOLUME"), SettingsGroup::AUDIO, &Options::audio.volume, 0, 100, 5));
    options_.push_back(std::make_unique<IntOption>(Lang::getText("[SERVICE_MENU] MUSIC_VOLUME"), SettingsGroup::AUDIO, &Options::audio.music.volume, 0, 100, 5));
    options_.push_back(std::make_unique<IntOption>(Lang::getText("[SERVICE_MENU] SFX_VOLUME"), SettingsGroup::AUDIO, &Options::audio.sound.volume, 0, 100, 5));

    // --- Settings ---
    options_.push_back(std::make_unique<BoolOption>(Lang::getText("[SERVICE_MENU] AUTOFIRE"), SettingsGroup::SETTINGS, &Options::settings.autofire));
    options_.push_back(std::make_unique<ListOption>(Lang::getText("[SERVICE_MENU] LANGUAGE"), SettingsGroup::SETTINGS, std::vector<std::string>{Lang::getText("[SERVICE_MENU] LANG_ES"), Lang::getText("[SERVICE_MENU] LANG_BA"), Lang::getText("[SERVICE_MENU] LANG_EN")}, []()
                                                    { return Lang::getNameFromCode(Options::pending_changes.new_language); }, [](const std::string &val)
                                                    { Options::pending_changes.new_language = Lang::getCodeFromName(val); Options::checkPendingChanges(); }));
    options_.push_back(std::make_unique<ListOption>(Lang::getText("[SERVICE_MENU] DIFFICULTY"), SettingsGroup::SETTINGS, std::vector<std::string>{Lang::getText("[SERVICE_MENU] EASY"), Lang::getText("[SERVICE_MENU] NORMAL"), Lang::getText("[SERVICE_MENU] HARD")}, []()
                                                    { return Options::getDifficultyNameFromCode(Options::pending_changes.new_difficulty); }, [](const std::string &val)
                                                    { Options::pending_changes.new_difficulty = Options::getDifficultyCodeFromName(val); Options::checkPendingChanges(); }));
    options_.push_back(std::make_unique<BoolOption>(Lang::getText("[SERVICE_MENU] ENABLE_SHUTDOWN"), SettingsGroup::SETTINGS, &Options::settings.shutdown_enabled));

    // --- System ---
    options_.push_back(std::make_unique<ActionOption>(Lang::getText("[SERVICE_MENU] RESET"), SettingsGroup::SYSTEM, [this]()
                                                      { Section::name = Section::Name::RESET; toggle(); }));
    options_.push_back(std::make_unique<ActionOption>(Lang::getText("[SERVICE_MENU] QUIT"), SettingsGroup::SYSTEM, []()
                                                      { Section::name = Section::Name::QUIT; Section::options = Section::Options::NONE; }));
    options_.push_back(std::make_unique<ActionOption>(Lang::getText("[SERVICE_MENU] SHUTDOWN"), SettingsGroup::SYSTEM, []()
                                                      { Section::name = Section::Name::QUIT; Section::options = Section::Options::SHUTDOWN; }, !Options::settings.shutdown_enabled));

    // --- Main Menu ---
    options_.push_back(std::make_unique<FolderOption>(Lang::getText("[SERVICE_MENU] VIDEO"), SettingsGroup::MAIN, SettingsGroup::VIDEO));
    options_.push_back(std::make_unique<FolderOption>(Lang::getText("[SERVICE_MENU] AUDIO"), SettingsGroup::MAIN, SettingsGroup::AUDIO));
    options_.push_back(std::make_unique<FolderOption>(Lang::getText("[SERVICE_MENU] SETTINGS"), SettingsGroup::MAIN, SettingsGroup::SETTINGS));
    options_.push_back(std::make_unique<FolderOption>(Lang::getText("[SERVICE_MENU] SYSTEM"), SettingsGroup::MAIN, SettingsGroup::SYSTEM));

    // precalculateMenuWidths();
}

// Sincroniza los valores de las opciones tipo lista
void ServiceMenu::AdjustListValues()
{
    for (auto &option : options_)
    {
        if (auto list_option = dynamic_cast<ListOption *>(option.get()))
        {
            list_option->sync();
        }
    }
}

// Reproduce el sonido de navegación del menú
void ServiceMenu::playMenuSound() { Audio::get()->playSound("clock.wav"); }

// Devuelve el nombre del grupo como string para el título
std::string ServiceMenu::settingsGroupToString(SettingsGroup group) const
{
    switch (group)
    {
    case SettingsGroup::MAIN:
        return Lang::getText("[SERVICE_MENU] TITLE");
    case SettingsGroup::VIDEO:
        return Lang::getText("[SERVICE_MENU] VIDEO");
    case SettingsGroup::AUDIO:
        return Lang::getText("[SERVICE_MENU] AUDIO");
    case SettingsGroup::SETTINGS:
        return Lang::getText("[SERVICE_MENU] SETTINGS");
    case SettingsGroup::SYSTEM:
        return Lang::getText("[SERVICE_MENU] SYSTEM");
    default:
        return Lang::getText("[SERVICE_MENU] TITLE");
    }
}
