#include "sleep_mgr.h"
#include "button.h"
#include "pages.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "esp_lvgl_port.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "lvgl.h"
#include "../ui/screens/ui_ScreenSet.h"
#include <stdio.h>

static const char *TAG = "SLEEP";

static bool sleep_enabled = false;
static bool screen_off = false;
static int64_t last_activity_us = 0;
static uint8_t saved_brightness = 50;
static const uint8_t DEFAULT_BRIGHTNESS = 50;  // 默认亮度
static const uint8_t SLEEP_MODE_BRIGHTNESS = 10;  // 休眠模式亮度

// 通知有用户活动
void sleep_mgr_notify_activity(void)
{
    last_activity_us = esp_timer_get_time();

    // 如果屏幕已关闭，立即唤醒
    if (screen_off) {
        screen_off = false;
        pwm_set_brightness(saved_brightness);
        ESP_LOGI(TAG, "屏幕唤醒，恢复亮度%d%%", saved_brightness);
    }
}

// 按键活动回调（BOOT和KEY2共用）
static void btn_activity_cb(int gpio_num, void *usr_data)
{
    sleep_mgr_notify_activity();
}

// 关闭屏幕（熄屏进入低功耗）
static void screen_turn_off(void)
{
    if (screen_off) return;

    // 保存当前亮度
    saved_brightness = pwm_get_brightness();
    if (saved_brightness == 0) {
        saved_brightness = 50;  // 防止保存到0值
    }

    screen_off = true;
    pwm_set_brightness(0);  // 关闭背光
    ESP_LOGI(TAG, "屏幕已关闭，进入低功耗模式（保存亮度=%d%%）", saved_brightness);
}

// 休眠管理任务
static void sleep_mgr_task(void *pvParameters)
{
    while (1) {
        if (sleep_enabled) {
            // 检查LVGL触摸活动（触摸会使inactive_time归零）
            if (lvgl_port_lock(50)) {
                uint32_t inactive_ms = lv_disp_get_inactive_time(NULL);
                lvgl_port_unlock();

                // LVGL检测到新的触摸输入
                if (inactive_ms < 500) {
                    sleep_mgr_notify_activity();
                }
            }

            // 检查是否超过超时时间
            if (!screen_off) {
                int64_t now = esp_timer_get_time();
                int64_t elapsed_ms = (now - last_activity_us) / 1000;
                if (elapsed_ms >= SLEEP_TIMEOUT_MS) {
                    screen_turn_off();
                }
            }
        }

        vTaskDelay(pdMS_TO_TICKS(500));
    }
}

void sleep_mgr_init(void)
{
    last_activity_us = esp_timer_get_time();

    // 注册按键回调，任意按键按下都唤醒/重置计时
    button_on_boot_press(btn_activity_cb, NULL);
    button_on_key2_press(btn_activity_cb, NULL);

    xTaskCreate(sleep_mgr_task, "sleep_mgr", 3072, NULL, 3, NULL);
    ESP_LOGI(TAG, "休眠管理器初始化完成（超时=%ds）", SLEEP_TIMEOUT_MS / 1000);
}

// 更新ScreenSet界面的亮度UI控件
static void update_brightness_ui(uint8_t brightness)
{
    if (!lvgl_port_lock(100)) {
        return;
    }

    // 更新滑块位置
    if (ui_SliderBrightness) {
        lv_slider_set_value(ui_SliderBrightness, brightness, LV_ANIM_OFF);
    }

    // 更新亮度文本标签
    if (ui_LabelBrightness) {
        char buf[8];
        snprintf(buf, sizeof(buf), "%d%%", brightness);
        lv_label_set_text(ui_LabelBrightness, buf);
    }

    lvgl_port_unlock();
}

void sleep_mgr_set_enabled(bool enabled)
{
    sleep_enabled = enabled;
    if (enabled) {
        last_activity_us = esp_timer_get_time();
        // 进入休眠模式时，将亮度调节到10%
        pwm_set_brightness(SLEEP_MODE_BRIGHTNESS);
        update_brightness_ui(SLEEP_MODE_BRIGHTNESS);
        ESP_LOGI(TAG, "休眠模式已启用，亮度已调节至%d%%，%ds无操作将熄屏",
                 SLEEP_MODE_BRIGHTNESS, SLEEP_TIMEOUT_MS / 1000);
    } else {
        // 禁用休眠模式时，恢复到默认亮度50%
        if (screen_off) {
            screen_off = false;
            pwm_set_brightness(DEFAULT_BRIGHTNESS);
            update_brightness_ui(DEFAULT_BRIGHTNESS);
            ESP_LOGI(TAG, "休眠模式已禁用，屏幕已恢复，亮度恢复到%d%%", DEFAULT_BRIGHTNESS);
        } else {
            pwm_set_brightness(DEFAULT_BRIGHTNESS);
            update_brightness_ui(DEFAULT_BRIGHTNESS);
            ESP_LOGI(TAG, "休眠模式已禁用，亮度恢复到%d%%", DEFAULT_BRIGHTNESS);
        }
    }
}

bool sleep_mgr_is_enabled(void)
{
    return sleep_enabled;
}

bool sleep_mgr_is_screen_off(void)
{
    return screen_off;
}
