// DragonX Wallet - ImGui Edition
// Copyright 2024-2026 The Hush Developers
// Released under the GPLv3

#pragma once

#include <string>
#include <deque>
#include <chrono>
#include <functional>
#include <cstdio>
#include <cstdint>
#include <ctime>
#include "../util/logger.h"
#include "schema/ui_schema.h"

namespace dragonx {
namespace ui {

enum class NotificationType {
    Info,
    Success,
    Warning,
    Error
};

// A retained alert for the persistent history panel. Unlike a live Notification (which fades and is
// erased within seconds), this keeps a wall-clock epoch so its age can be shown as "3m ago" long
// after the toast is gone. See App::renderAlertHistoryPanel.
struct AlertRecord {
    std::string      message;
    NotificationType type;
    std::int64_t     epoch;  // std::time(nullptr) at push — wall-clock, for relative-age display
    std::function<void()> onClick;     // optional: makes this bell-panel entry actionable
    std::string      actionHint;       // optional: accent link label rendered for the action
};

struct Notification {
    std::string message;
    NotificationType type;
    std::chrono::steady_clock::time_point created_at;
    float duration_seconds;
    
    Notification(const std::string& msg, NotificationType t, float duration = 5.0f)
        : message(msg)
        , type(t)
        , created_at(std::chrono::steady_clock::now())
        , duration_seconds(duration)
    {}
    
    bool isExpired() const {
        auto now = std::chrono::steady_clock::now();
        auto elapsed = std::chrono::duration<float>(now - created_at).count();
        return elapsed >= duration_seconds;
    }
    
    float getProgress() const {
        auto now = std::chrono::steady_clock::now();
        auto elapsed = std::chrono::duration<float>(now - created_at).count();
        return std::min(1.0f, elapsed / duration_seconds);
    }
};

/**
 * @brief Simple notification manager for user feedback
 * 
 * Usage:
 *   Notifications::instance().info("Transaction sent!");
 *   Notifications::instance().error("Connection failed");
 */
class Notifications {
public:
    static Notifications& instance() {
        static Notifications inst;
        return inst;
    }
    
    void info(const std::string& message, float duration = -1.0f) {
        if (duration < 0.0f) duration = schemaDuration("duration-info", 1.0f);
        push(message, NotificationType::Info, duration);
    }
    
    void success(const std::string& message, float duration = -1.0f) {
        if (duration < 0.0f) duration = schemaDuration("duration-success", 2.5f);
        push(message, NotificationType::Success, duration);
    }
    
    void warning(const std::string& message, float duration = -1.0f) {
        if (duration < 0.0f) duration = schemaDuration("duration-warning", 3.5f);
        push(message, NotificationType::Warning, duration);
    }
    
    void error(const std::string& message, float duration = -1.0f) {
        if (duration < 0.0f) duration = schemaDuration("duration-error", 4.0f);
        push(message, NotificationType::Error, duration);
    }

    // An actionable alert: a normal toast PLUS a clickable entry in the bell/alert-history panel.
    // onClick fires when the user clicks the accent `actionHint` link in that panel.
    void action(const std::string& message, NotificationType type, std::function<void()> onClick,
                const std::string& actionHint, float duration = -1.0f) {
        if (duration < 0.0f) duration = schemaDuration("duration-warning", 3.5f);
        push(message, type, duration, std::move(onClick), actionHint);
    }
    
    void push(const std::string& message, NotificationType type, float duration = 5.0f,
              std::function<void()> onClick = nullptr, const std::string& actionHint = "") {
        notifications_.emplace_back(message, type, duration);

        // Retain a copy in the persistent history (the toast above will fade in seconds; this
        // survives so the user can review what happened). Thread note: every push is on the UI
        // thread (RPC results run as main-thread MainCb callbacks), so this container needs no lock,
        // consistent with the rest of this class. Do NOT push from a raw worker thread.
        history_.push_back(AlertRecord{message, type, static_cast<std::int64_t>(std::time(nullptr)),
                                       std::move(onClick), actionHint});
        ++total_pushed_;
        while (history_.size() > kMaxHistory) {
            history_.pop_front();
        }

        // Log errors and warnings (debug-only output)
        if (type == NotificationType::Error) {
            DEBUG_LOGF("[ERROR] Notification: %s\n", message.c_str());
        } else if (type == NotificationType::Warning) {
            DEBUG_LOGF("[WARN] Notification: %s\n", message.c_str());
        }

        // Forward errors and warnings to console callback
        if (console_callback_ && (type == NotificationType::Error || type == NotificationType::Warning)) {
            const char* prefix = (type == NotificationType::Error) ? "[ERROR] " : "[WARN] ";
            console_callback_(prefix + message, type == NotificationType::Error);
        }

        // Limit max notifications
        while (notifications_.size() > max_notifications_) {
            notifications_.pop_front();
        }
    }
    
    /// Set a callback that receives error/warning messages (e.g. console tab)
    void setConsoleCallback(std::function<void(const std::string&, bool is_error)> cb) {
        console_callback_ = std::move(cb);
    }
    
    void render();

    /// @brief Check if there are non-expired notifications (needs continuous frames for animation)
    bool hasActive() const {
        for (const auto& n : notifications_) {
            if (!n.isExpired()) return true;
        }
        return false;
    }
    
    void clear() {
        notifications_.clear();
    }

    void setMaxNotifications(size_t max) {
        max_notifications_ = max;
    }

    // ── Persistent alert history (for the status-bar bell panel) ──
    /// Retained alerts, oldest first (capped at kMaxHistory; the toast deque is separate).
    const std::deque<AlertRecord>& history() const { return history_; }
    bool hasHistory() const { return !history_.empty(); }
    void clearHistory() { history_.clear(); }
    /// Monotonic count of every alert ever pushed this session — survives capping/clearing, so it is
    /// the correct basis for an "unseen since last opened" count (deque size is not).
    std::uint64_t totalPushed() const { return total_pushed_; }

private:
    Notifications() = default;
    ~Notifications() = default;
    Notifications(const Notifications&) = delete;
    Notifications& operator=(const Notifications&) = delete;

    std::deque<Notification> notifications_;
    size_t max_notifications_ = 5;
    std::function<void(const std::string&, bool)> console_callback_;

    std::deque<AlertRecord> history_;
    std::uint64_t total_pushed_ = 0;
    static constexpr size_t kMaxHistory = 100;

    static float schemaDuration(const char* key, float fallback) {
        float v = schema::UI().drawElement("components.notifications", key).size;
        return v > 0.0f ? v : fallback;
    }
};

} // namespace ui
} // namespace dragonx
