#include "game/ui/notifier.hpp"

#include <SDL3/SDL.h>

#include <algorithm>  // Para remove_if
#include <iterator>   // Para prev
#include <ranges>     // Para reverse_view
#include <string>     // Para string, basic_string
#include <vector>     // Para vector

#include "core/audio/audio.hpp"               // Para Audio
#include "core/rendering/screen.hpp"          // Para Screen
#include "core/rendering/sprite/sprite.hpp"   // Para SSprite
#include "core/rendering/surface.hpp"         // Para Surface
#include "core/rendering/text.hpp"            // Para Text, Text::CENTER_FLAG, Text::COLOR_FLAG
#include "core/resources/resource_cache.hpp"  // Para Resource
#include "game/defaults.hpp"                  // Para Defaults::Notification
#include "game/options.hpp"                   // Para Options, options, NotificationPosition
#include "utils/delta_timer.hpp"              // Para DeltaTimer
#include "utils/utils.hpp"                    // Para PaletteColor

// [SINGLETON]
Notifier* Notifier::notifier = nullptr;

// Parte un texto en varias líneas cuando no cabe en max_width píxeles.
// Divide por espacios; si una palabra sola excede el ancho, queda en su propia línea.
static auto wrapToWidth(const std::string& text, int max_width, Text* text_obj, int kerning = 1) -> std::vector<std::string> {
    if (max_width <= 0 || text_obj->length(text, kerning) <= max_width) {
        return {text};
    }

    std::vector<std::string> lines;
    std::string current;
    std::string word;

    auto flush_word = [&]() {
        if (word.empty()) { return; }
        const std::string CANDIDATE = current.empty() ? word : current + " " + word;
        if (text_obj->length(CANDIDATE, kerning) <= max_width) {
            current = CANDIDATE;
        } else {
            if (!current.empty()) { lines.push_back(current); }
            current = word;
        }
        word.clear();
    };

    for (const char c : text) {
        if (c == ' ') {
            flush_word();
        } else {
            word += c;
        }
    }
    flush_word();
    if (!current.empty()) { lines.push_back(current); }
    return lines;
}

// Definición de estilos predefinidos
const Notifier::Style Notifier::Style::DEFAULT = {
    .bg_color = Defaults::Notification::BG_COLOR,
    .border_color = Defaults::Notification::BORDER_COLOR,
    .text_color = Defaults::Notification::TEXT_COLOR,
    .shape = Notifier::Shape::SQUARED,
    .text_align = Notifier::TextAlign::CENTER,
    .duration = 2.0F,
    .sound_file = Defaults::Sound::Files::NOTIFY,
    .play_sound = false};

const Notifier::Style Notifier::Style::CHEEVO = {
    .bg_color = Defaults::Notification::CHEEVO_BG_COLOR,
    .border_color = Defaults::Notification::CHEEVO_BORDER_COLOR,
    .text_color = Defaults::Notification::CHEEVO_TEXT_COLOR,
    .shape = Notifier::Shape::SQUARED,
    .text_align = Notifier::TextAlign::CENTER,
    .duration = 4.0F,
    .sound_file = Defaults::Sound::Files::NOTIFY,
    .play_sound = true};

// [SINGLETON] Crearemos el objeto con esta función estática
void Notifier::init(const std::string& icon_file, const std::string& text) {
    Notifier::notifier = new Notifier(icon_file, text);
}

// [SINGLETON] Destruiremos el objeto con esta función estática
void Notifier::destroy() {
    delete Notifier::notifier;
}

// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
auto Notifier::get() -> Notifier* {
    return Notifier::notifier;
}

// Constructor
Notifier::Notifier(const std::string& icon_file, const std::string& text)
    : icon_surface_(!icon_file.empty() ? Resource::Cache::get()->getSurface(icon_file) : nullptr),
      text_(Resource::Cache::get()->getText(text)),
      delta_timer_(std::make_unique<DeltaTimer>()),
      has_icons_(!icon_file.empty()) {}

// Dibuja las notificaciones por pantalla
void Notifier::render() {
    for (auto& notification : std::ranges::reverse_view(notifications_)) {
        notification.sprite->render();
    }
}

// Actualiza el estado de las notificaiones
void Notifier::update(float delta_time) {
    for (auto& notification : notifications_) {
        // Si la notificación anterior está "saliendo", no hagas nada
        if (!notifications_.empty() && &notification != &notifications_.front()) {
            const auto& previous_notification = *(std::prev(&notification));
            if (previous_notification.state == Status::RISING) {
                break;
            }
        }

        switch (notification.state) {
            case Status::RISING: {
                const float DISPLACEMENT = SLIDE_SPEED * delta_time;
                notification.rect.y += DISPLACEMENT;

                if (notification.rect.y >= notification.y) {
                    notification.rect.y = notification.y;
                    notification.state = Status::STAY;
                    notification.elapsed_time = 0.0F;
                }
                break;
            }
            case Status::STAY: {
                notification.elapsed_time += delta_time;
                if (notification.elapsed_time >= notification.display_duration) {
                    notification.state = Status::VANISHING;
                }
                break;
            }

            case Status::VANISHING: {
                const float DISPLACEMENT = SLIDE_SPEED * delta_time;
                notification.rect.y -= DISPLACEMENT;

                const float TARGET_Y = notification.y - notification.travel_dist;
                if (notification.rect.y <= TARGET_Y) {
                    notification.rect.y = TARGET_Y;
                    notification.state = Status::FINISHED;
                }
                break;
            }

            case Status::FINISHED:
            default:
                break;
        }

        notification.sprite->setPosition(notification.rect);
    }

    clearFinishedNotifications();
}

// Elimina las notificaciones finalizadas
void Notifier::clearFinishedNotifications() {
    auto result = std::ranges::remove_if(notifications_, [](const Notification& notification) -> bool {
        return notification.state == Status::FINISHED;
    });
    notifications_.erase(result.begin(), result.end());
}

void Notifier::show(std::vector<std::string> texts, const Style& style, int icon, bool can_be_removed, const std::string& code) {
    // Si no hay texto, acaba
    if (texts.empty()) {
        return;
    }

    // Si las notificaciones no se apilan, elimina las anteriores
    if (!stack_) {
        clearNotifications();
    }

    // Elimina las cadenas vacías
    auto result = std::ranges::remove_if(texts, [](const std::string& s) -> bool { return s.empty(); });
    texts.erase(result.begin(), result.end());

    // Inicializa variables
    constexpr float TEXT_SIZE = LINE_HEIGHT;
    const auto PADDING_IN_H = TEXT_SIZE;
    const auto PADDING_IN_V = TEXT_SIZE / 2;
    const int ICON_SPACE = icon >= 0 ? ICON_SIZE + PADDING_IN_H : 0;
    const TextAlign TEXT_IS = ICON_SPACE > 0 ? TextAlign::LEFT : style.text_align;
    const float WIDTH = Options::game.width - (PADDING_OUT * 2);
    const int MAX_TEXT_WIDTH = static_cast<int>(WIDTH - (PADDING_IN_H * 2) - ICON_SPACE);

    // Si un texto no cabe en una línea, parte por espacios en varias líneas
    std::vector<std::string> wrapped;
    wrapped.reserve(texts.size());
    for (const auto& t : texts) {
        auto lines = wrapToWidth(t, MAX_TEXT_WIDTH, text_.get());
        wrapped.insert(wrapped.end(), std::make_move_iterator(lines.begin()), std::make_move_iterator(lines.end()));
    }
    texts = std::move(wrapped);

    const float HEIGHT = (TEXT_SIZE * texts.size()) + (PADDING_IN_V * 2);
    const auto SHAPE = style.shape;

    // Posición horizontal
    float desp_h = ((Options::game.width / 2) - (WIDTH / 2));
    ;

    // Posición vertical
    const int DESP_V = y_offset_;

    // Offset
    const auto TRAVEL_DIST = HEIGHT + PADDING_OUT;
    const int TRAVEL_MOD = 1;
    const int OFFSET = !notifications_.empty() ? notifications_.back().y + (TRAVEL_MOD * notifications_.back().travel_dist) : DESP_V;

    // Crea la notificacion
    Notification n;

    // Inicializa variables
    n.code = code;
    n.can_be_removed = can_be_removed;
    n.y = OFFSET;
    n.travel_dist = TRAVEL_DIST;
    n.texts = texts;
    n.shape = SHAPE;
    n.display_duration = style.duration;
    const float Y_POS = OFFSET + -TRAVEL_DIST;
    n.rect = {.x = desp_h, .y = Y_POS, .w = WIDTH, .h = HEIGHT};

    // Crea la textura
    n.surface = std::make_shared<Surface>(WIDTH, HEIGHT);

    // Prepara para dibujar en la textura
    auto previuos_renderer = Screen::get()->getRendererSurface();
    Screen::get()->setRendererSurface(n.surface);

    // Dibuja el fondo de la notificación
    SDL_FRect rect;
    if (SHAPE == Shape::ROUNDED) {
        rect = {.x = static_cast<float>(CORNER_RADIUS), .y = 0, .w = WIDTH - (CORNER_RADIUS * 2), .h = HEIGHT};
        n.surface->fillRect(&rect, style.bg_color);

        rect = {.x = static_cast<float>(CORNER_RADIUS / 2), .y = static_cast<float>(BORDER_INSET), .w = WIDTH - CORNER_RADIUS, .h = HEIGHT - (BORDER_INSET * 2)};
        n.surface->fillRect(&rect, style.bg_color);

        rect = {.x = static_cast<float>(BORDER_INSET), .y = static_cast<float>(CORNER_RADIUS / 2), .w = WIDTH - (BORDER_INSET * 2), .h = HEIGHT - CORNER_RADIUS};
        n.surface->fillRect(&rect, style.bg_color);

        rect = {.x = 0, .y = static_cast<float>(CORNER_RADIUS), .w = WIDTH, .h = HEIGHT - (CORNER_RADIUS * 2)};
        n.surface->fillRect(&rect, style.bg_color);
    }

    else if (SHAPE == Shape::SQUARED) {
        n.surface->clear(style.bg_color);
        SDL_FRect squared_rect = {.x = 0, .y = 0, .w = n.surface->getWidth(), .h = n.surface->getHeight()};
        n.surface->drawRectBorder(&squared_rect, style.border_color);
    }

    // Dibuja el icono de la notificación
    if (has_icons_ && icon >= 0 && texts.size() >= 2) {
        auto sp = std::make_unique<Sprite>(icon_surface_, SDL_FRect{.x = 0, .y = 0, .w = ICON_SIZE, .h = ICON_SIZE});
        sp->setPosition({.x = PADDING_IN_H, .y = PADDING_IN_V, .w = ICON_SIZE, .h = ICON_SIZE});
        sp->setClip(SDL_FRect{.x = ICON_SIZE * (icon % 10), .y = ICON_SIZE * (icon / 10), .w = ICON_SIZE, .h = ICON_SIZE});
        sp->render();
    }

    // Escribe el texto de la notificación
    const auto COLOR = style.text_color;
    int iterator = 0;
    for (const auto& text : texts) {
        switch (TEXT_IS) {
            case TextAlign::LEFT:
                text_->writeColored(PADDING_IN_H + ICON_SPACE, PADDING_IN_V + (iterator * (TEXT_SIZE + 1)), text, COLOR);
                break;
            case TextAlign::CENTER:
                text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, WIDTH / 2, PADDING_IN_V + (iterator * (TEXT_SIZE + 1)), text, 1, COLOR);
                break;
            default:
                break;
        }

        ++iterator;
    }

    // Deja de dibujar en la textura
    Screen::get()->setRendererSurface(previuos_renderer);

    // Crea el sprite de la notificación
    n.sprite = std::make_shared<Sprite>(n.surface, n.rect);

    // Añade la notificación a la lista
    notifications_.emplace_back(n);

    // Reproduce el sonido de la notificación
    if (style.play_sound && !style.sound_file.empty()) {
        Audio::get()->playSound(style.sound_file, Audio::Group::INTERFACE);
    }
}

// Indica si hay notificaciones activas
auto Notifier::isActive() -> bool { return !notifications_.empty(); }

// Finaliza y elimnina todas las notificaciones activas
void Notifier::clearNotifications() {
    for (auto& notification : notifications_) {
        if (notification.can_be_removed) {
            notification.state = Status::FINISHED;
        }
    }

    clearFinishedNotifications();
}

// Ajusta el offset vertical base y desplaza las notificaciones existentes
void Notifier::addYOffset(int px) {
    y_offset_ += px;
    for (auto& n : notifications_) {
        n.y += px;
        n.rect.y += static_cast<float>(px);
    }
}
void Notifier::removeYOffset(int px) {
    y_offset_ -= px;
    for (auto& n : notifications_) {
        n.y -= px;
        n.rect.y -= static_cast<float>(px);
    }
}

// Altura visible ocupada por las notificaciones activas (relativa al offset base)
auto Notifier::getVisibleHeight() const -> int {
    int bottom = 0;
    for (const auto& n : notifications_) {
        if (n.state == Status::FINISHED) { continue; }
        int n_bottom = static_cast<int>(n.rect.y + n.rect.h) - y_offset_;
        if (n_bottom > bottom) { bottom = n_bottom; }
    }
    return bottom;
}

// Obtiene los códigos de las notificaciones
auto Notifier::getCodes() -> std::vector<std::string> {
    std::vector<std::string> codes;
    codes.reserve(notifications_.size());
    for (const auto& notification : notifications_) {
        codes.emplace_back(notification.code);
    }
    return codes;
}