#include "display/ui/flow/flow_view.h"

#include "display/ui/components/mascot.h"
#include "display/ui/components/preparation_cards.h"
#include "display/ui/components/primitives.h"
#include "display/ui/theme.h"

#include <cstring>
#include <string>

LV_FONT_DECLARE(lv_font_home_22)
LV_FONT_DECLARE(lv_font_home_44)

namespace hwdisplay::ui {
namespace {

using components::Box;
using components::Text;

lv_obj_t* CenteredText(lv_obj_t* parent, int x, int y, int width,
                       const char* value, const lv_font_t* font, uint32_t color) {
    lv_obj_t* label = Text(parent, x, y, value, font, color);
    if (!label) return nullptr;
    lv_obj_set_width(label, width);
    lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_CENTER, 0);
    return label;
}

constexpr const char* kStepActions[] = {
    "搓手心", "搓手背", "搓指缝", "搓指背", "搓拇指", "搓指尖", "搓手腕"};
constexpr const char* kInstructions[] = {
    "手心贴手心，搓一搓", "搓搓手背，记得换手", "十指交叉，搓搓指缝",
    "弯起手指，搓搓指背", "握住拇指，转圈搓", "指尖在手心里转圈", "握住手腕，轻轻转圈"};

void Header(lv_obj_t* root, const char* status) {
    lv_obj_t* icon = Box(root, 48, 21, 32, 32, 0x25A9B5, 11);
    if (icon) {
        lv_obj_t* dot = Box(icon, 0, 0, 9, 9, theme::kWhite, LV_RADIUS_CIRCLE);
        if (dot) lv_obj_align(dot, LV_ALIGN_CENTER, 0, 0);
        lv_obj_t* title = Text(root, 0, 0, "洗手引导", &lv_font_home_22, theme::kInk);
        if (title) lv_obj_align_to(title, icon, LV_ALIGN_OUT_RIGHT_MID, 11, 1);
    }
    Box(root, 536, 18, 216, 39, theme::kWhite, 20);
    CenteredText(root, 548, 26, 192, status, &lv_font_home_22, 0x537A81);
}

void Hero(lv_obj_t* root, const char* eyebrow, const char* title,
          const char* accent, const char* detail, const char* cue) {
    Box(root, 527, -193, 345, 328, 0xDDF8F0, LV_RADIUS_CIRCLE);
    Box(root, -78, 405, 220, 220, 0xE9F6FF, LV_RADIUS_CIRCLE);
    Text(root, 49, 111, eyebrow, &lv_font_home_22, theme::kTeal);
    Text(root, 48, 151, title, &lv_font_home_44, theme::kInk);
    Text(root, 48, 207, accent, &lv_font_home_44, theme::kTeal);
    Text(root, 48, 285, detail, &lv_font_home_22, theme::kMuted);
    Box(root, 48, 347, 385, 45, theme::kTealSoft, 17);
    Text(root, 64, 355, cue, &lv_font_home_22, 0x147F78);
    components::Mascot mascot;
    mascot.Create(root, 448, 74);
}

void Footer(lv_obj_t* root, const char* text) {
    Box(root, 48, 410, 704, 51, theme::kWhite, 20);
    Text(root, 64, 420, text, &lv_font_home_22, theme::kMuted);
}

void Card(lv_obj_t* root, int x, const char* heading, const char* detail,
          const char* mark) {
    Box(root, x, 155, 340, 217, theme::kWhite, 24);
    Box(root, x + 111, 173, 118, 92, 0xDFF7EF, LV_RADIUS_CIRCLE);
    CenteredText(root, x + 111, 190, 118, mark, &lv_font_home_44, theme::kTeal);
    CenteredText(root, x + 20, 278, 300, heading, &lv_font_home_44, theme::kInk);
    CenteredText(root, x + 20, 333, 300, detail, &lv_font_home_22, theme::kMuted);
}

}  // namespace

bool FlowView::Create(lv_obj_t* parent) {
    if (!parent || lv_obj_get_width(parent) != theme::kScreenWidth ||
        lv_obj_get_height(parent) != theme::kScreenHeight) return false;
    parent_ = parent;
    lv_display_t* display = lv_display_get_default();
    if (display) {
        lv_sysmon_hide_performance(display);
        lv_sysmon_hide_memory(display);
    }
    return true;
}

void FlowView::Render(const FlowModel& model) {
    if (!parent_) return;
    home_.Destroy();
    if (root_) lv_obj_delete(root_);
    root_ = nullptr;
    video_ = nullptr;
    video_hint_ = nullptr;
    camera_ = nullptr;
    camera_hint_ = nullptr;
    feedback_card_ = nullptr;
    feedback_icon_box_ = nullptr;
    feedback_icon_ = nullptr;
    feedback_main_ = nullptr;
    feedback_detail_ = nullptr;
    countdown_label_ = nullptr;
    countdown_fill_ = nullptr;
    camera_has_frame_ = false;
    hand_feedback_ = HandFeedback::Observing;

    if (model.scene == FlowScene::Idle || model.scene == FlowScene::Detecting) {
        home_.Create(parent_);
        HomeModel preview_model;
        if (model.scene == FlowScene::Detecting)
            preview_model.presence = HomePresence::FaceVisible;
        home_.Render(preview_model);
        return;
    }

    root_ = Box(parent_, 0, 0, theme::kScreenWidth, theme::kScreenHeight, theme::kCanvas);
    if (!root_) return;
    const std::string name = model.known ? model.nickname : "小朋友";
    switch (model.scene) {
        case FlowScene::Detecting: break;
        case FlowScene::Known:
        case FlowScene::Guest: {
            Header(root_, model.known ? "欢迎回来" : "一起洗手");
            const std::string title = name + "，";
            Hero(root_, model.known ? "今天也认真洗小手" : "你好，小朋友",
                 title.c_str(), "一起洗手吧", "跟着画面，一步一步来", "马上开始，不用碰屏幕");
            Footer(root_, model.known ? "跟着画面，开始今天的洗手练习" :
                    "没有登记也可以一起练习洗手");
            break;
        }
        case FlowScene::Multi:
            Header(root_, "等待一位小朋友");
            Hero(root_, "洗手池前有好几位朋友", "一次一位", "小朋友哦", "排好队，大家都能轮到", "站到洗手池前，就会自动开始");
            Footer(root_, "前一位洗好后，下一位再走近");
            break;
        case FlowScene::Prepare:
            Header(root_, "先做准备");
            components::RenderPreparationCards(root_);
            break;
        case FlowScene::Guide: {
            Header(root_, ("第 " + std::to_string(model.step + 1) + " / 7 步").c_str());
            Text(root_, 205, 26, name.c_str(), &lv_font_home_22, theme::kTeal);
            for (int i = 0; i < 7; ++i)
                Box(root_, 294 + i * 31, 31, 15, 15,
                    i <= model.step ? theme::kTeal : 0xCFE6E3, LV_RADIUS_CIRCLE);
            Box(root_, 24, 82, 418, 314, 0xE4F7F3, 25);
            Box(root_, 36, 105, kVideoWidth, kVideoHeight, 0xD5EBE9, 14);
            frame_buffer_.assign(kVideoWidth * kVideoHeight * 4, 0xFF);
            video_ = lv_canvas_create(root_);
            lv_canvas_set_buffer(video_, frame_buffer_.data(), kVideoWidth, kVideoHeight,
                                 LV_COLOR_FORMAT_ARGB8888);
            lv_obj_set_pos(video_, 36, 105);
            lv_obj_add_flag(video_, LV_OBJ_FLAG_HIDDEN);
            video_hint_ = Text(root_, 129, 216, "动作示范准备中", &lv_font_home_22, theme::kMuted);

            Box(root_, 456, 82, 320, 314, theme::kWhite, 24);
            Box(root_, 468, 94, kCameraWidth, kCameraHeight, 0x203F41, 16);
            camera_buffer_.assign(kCameraWidth * kCameraHeight * 4, 0xFF);
            camera_ = lv_canvas_create(root_);
            lv_canvas_set_buffer(camera_, camera_buffer_.data(), kCameraWidth, kCameraHeight,
                                 LV_COLOR_FORMAT_ARGB8888);
            lv_obj_set_pos(camera_, 468, 94);
            lv_obj_add_flag(camera_, LV_OBJ_FLAG_HIDDEN);
            camera_hint_ = CenteredText(root_, 498, 166, 236, "画面准备中", &lv_font_home_22, theme::kWhite);

            feedback_card_ = Box(root_, 468, 300, 296, 84, 0xE8F5F4, 15);
            feedback_icon_box_ = Box(root_, 479, 324, 36, 36, 0xCCE8E4, 12);
            feedback_icon_ = CenteredText(root_, 479, 325, 36, "?", &lv_font_home_22, theme::kTeal);
            feedback_main_ = Text(root_, 524, 306, "", &lv_font_home_22, theme::kInk);
            feedback_detail_ = Text(root_, 524, 341, "", &lv_font_home_22, theme::kMuted);
            UpdateHandFeedback(model);

            Box(root_, 24, 410, 566, 52, theme::kWhite, 18);
            lv_obj_t* number_box = Box(root_, 36, 419, 34, 34, 0x19A39A, 12);
            if (number_box) {
                lv_obj_t* number = Text(number_box, 0, 0, std::to_string(model.step + 1).c_str(),
                                        &lv_font_home_22, theme::kWhite);
                if (number) lv_obj_align(number, LV_ALIGN_CENTER, 0, 0);
            }
            lv_obj_t* instruction = Text(root_, 0, 0, kInstructions[model.step],
                                         &lv_font_home_22, theme::kInk);
            if (instruction && number_box)
                lv_obj_align_to(instruction, number_box, LV_ALIGN_OUT_RIGHT_MID, 12, 0);
            Box(root_, 602, 410, 174, 52, theme::kTealSoft, 17);
            countdown_label_ = CenteredText(root_, 612, 414, 154, "下一步",
                                            &lv_font_home_22, theme::kTeal);
            Box(root_, 620, 447, 138, 7, 0xBEE9D8, LV_RADIUS_CIRCLE);
            countdown_fill_ = Box(root_, 620, 447, 138, 7, 0x20AD91, LV_RADIUS_CIRCLE);
            break;
        }
        case FlowScene::Paused:
            Header(root_, "正在等你回来");
            Hero(root_, "洗手练习暂停啦", "小手回来", "继续做吧", "把双手放回画面里", "回来后，从刚才的动作继续");
            Footer(root_, "现在停在原来的步骤，不用重新开始");
            break;
        case FlowScene::Finish:
            Header(root_, "还有最后两件事");
            Text(root_, 48, 91, "冲净泡泡，擦干小手", &lv_font_home_44, theme::kInk);
            Card(root_, 48, "冲干净", "用清水冲掉泡泡", "1");
            Card(root_, 412, "擦干净", "用纸巾擦干双手", "2");
            Footer(root_, "请照着画面完成，练习马上结束");
            break;
        case FlowScene::Done: {
            Header(root_, "练习结束");
            const std::string title = name + "，";
            Hero(root_, "今天也认真练习了", title.c_str(), "做得真棒", "你跟完了七个洗手动作", "记得冲净泡泡，擦干小手");
            Footer(root_, "下次见，我们再一起认真洗手");
            break;
        }
        case FlowScene::Interrupted:
            Header(root_, "练习暂时结束");
            Hero(root_, "小手离开了一会儿", "下次再来", "一起练习", "这次先休息一下", "走到洗手池前，就能重新开始");
            Footer(root_, "这次没有记为完成，下次可以再试试");
            break;
        case FlowScene::Fault:
            Header(root_, "请老师帮忙");
            Hero(root_, "画面暂时看不清", "请找老师", "帮忙看看", "还可以跟着图卡洗手", "设备恢复后，会自动回到首页");
            Footer(root_, "请老师检查摄像头与设备连接");
            break;
        case FlowScene::Idle: break;
    }
}

void FlowView::UpdateGuideCountdown(uint64_t elapsed_ms, uint64_t duration_ms) {
    if (!countdown_label_ || !countdown_fill_ || duration_ms == 0) return;
    const uint64_t remaining = elapsed_ms >= duration_ms ? 0 : duration_ms - elapsed_ms;
    const int seconds = static_cast<int>((remaining + 999) / 1000);
    const int width = static_cast<int>((remaining * 138 + duration_ms - 1) / duration_ms);
    const std::string label = "下一步 " + std::to_string(seconds) + " 秒";
    lv_label_set_text(countdown_label_, label.c_str());
    lv_obj_set_width(countdown_fill_, width);
}

void FlowView::UpdateHandFeedback(const FlowModel& model) {
    if (!feedback_card_ || model.scene != FlowScene::Guide) return;
    hand_feedback_ = model.hand_feedback;
    const char* main = "还没看出动作";
    const char* detail = "照着左边做一做";
    const char* icon = "○";
    uint32_t card_color = 0xE8F5F4;
    uint32_t icon_color = 0xCCE8E4;
    uint32_t text_color = 0x2B7776;
    std::string main_text;
    std::string detail_text;
    switch (model.hand_feedback) {
        case HandFeedback::Observing: break;
        case HandFeedback::Matched:
            main_text = std::string("看到：") + kStepActions[model.step];
            main = main_text.c_str();
            detail = "对啦，继续这样搓";
            icon = "✓";
            card_color = 0xDFF8E9;
            icon_color = 0x26B78C;
            text_color = 0x14836D;
            break;
        case HandFeedback::Other:
            main_text = std::string("看到：") + kStepActions[model.recognized_step];
            detail_text = std::string("这一步试试") + kStepActions[model.step];
            main = main_text.c_str();
            detail = detail_text.c_str();
            icon = "换";
            card_color = 0xFFF2D9;
            icon_color = 0xF6D997;
            text_color = 0x8A671F;
            break;
        case HandFeedback::Missing:
            main = "还没看到双手";
            detail = "放到画面里再试试";
            card_color = 0xEDF2F0;
            icon_color = 0xD6E2DF;
            text_color = 0x617A77;
            break;
        case HandFeedback::Unclear:
            main = "动作有点看不清";
            detail = "慢一点，再做一次";
            icon = "…";
            card_color = 0xFFF2D9;
            icon_color = 0xF6D997;
            text_color = 0x8A671F;
            break;
        case HandFeedback::Offline:
            main = "暂时看不到画面";
            detail = "请老师帮忙看看";
            icon = "!";
            card_color = 0xEDF2F0;
            icon_color = 0xD6E2DF;
            text_color = 0x617A77;
            break;
    }
    lv_obj_set_style_bg_color(feedback_card_, lv_color_hex(card_color), 0);
    lv_obj_set_style_bg_color(feedback_icon_box_, lv_color_hex(icon_color), 0);
    lv_label_set_text(feedback_icon_, icon);
    lv_obj_set_style_text_color(feedback_icon_,
        lv_color_hex(model.hand_feedback == HandFeedback::Matched ? theme::kWhite : text_color), 0);
    lv_label_set_text(feedback_main_, main);
    lv_label_set_text(feedback_detail_, detail);
    lv_obj_set_style_text_color(feedback_main_, lv_color_hex(text_color), 0);
    lv_obj_set_style_text_color(feedback_detail_, lv_color_hex(text_color), 0);

    const bool offline = model.hand_feedback == HandFeedback::Offline;
    const bool missing = model.hand_feedback == HandFeedback::Missing;
    if (camera_) {
        if (offline || !camera_has_frame_) lv_obj_add_flag(camera_, LV_OBJ_FLAG_HIDDEN);
        else lv_obj_remove_flag(camera_, LV_OBJ_FLAG_HIDDEN);
        lv_obj_set_style_opa(camera_, missing ? LV_OPA_30 : LV_OPA_COVER, 0);
    }
    if (camera_hint_) {
        if (offline) lv_label_set_text(camera_hint_, "画面暂时不可用");
        else if (missing) lv_label_set_text(camera_hint_, "双手放进画面");
        else lv_label_set_text(camera_hint_, "画面准备中");
        if (offline || missing || !camera_has_frame_) lv_obj_remove_flag(camera_hint_, LV_OBJ_FLAG_HIDDEN);
        else lv_obj_add_flag(camera_hint_, LV_OBJ_FLAG_HIDDEN);
    }
}

void FlowView::ShowVideoFrame(const uint8_t* bgra, size_t bytes) {
    if (!video_ || !bgra || bytes < frame_buffer_.size()) return;
    std::memcpy(frame_buffer_.data(), bgra, frame_buffer_.size());
    if (video_hint_) lv_obj_add_flag(video_hint_, LV_OBJ_FLAG_HIDDEN);
    lv_obj_remove_flag(video_, LV_OBJ_FLAG_HIDDEN);
    lv_obj_invalidate(video_);
}

void FlowView::ShowCameraFrame(const uint8_t* bgra, size_t bytes) {
    if (!camera_ || !bgra || bytes < camera_buffer_.size() ||
        hand_feedback_ == HandFeedback::Offline) return;
    std::memcpy(camera_buffer_.data(), bgra, camera_buffer_.size());
    camera_has_frame_ = true;
    lv_obj_remove_flag(camera_, LV_OBJ_FLAG_HIDDEN);
    if (camera_hint_ && hand_feedback_ != HandFeedback::Missing)
        lv_obj_add_flag(camera_hint_, LV_OBJ_FLAG_HIDDEN);
    lv_obj_invalidate(camera_);
}

void FlowView::ShowFaceFrame(const uint8_t* bgra, size_t bytes) {
    home_.ShowFaceFrame(bgra, bytes);
}

void FlowView::UpdateHome(const HomeModel& model) {
    home_.Render(model);
}

void FlowView::Destroy() {
    home_.Destroy();
    if (root_) lv_obj_delete(root_);
    root_ = nullptr;
    video_ = nullptr;
    video_hint_ = nullptr;
    camera_ = nullptr;
    camera_hint_ = nullptr;
    feedback_card_ = nullptr;
    feedback_icon_box_ = nullptr;
    feedback_icon_ = nullptr;
    feedback_main_ = nullptr;
    feedback_detail_ = nullptr;
    countdown_label_ = nullptr;
    countdown_fill_ = nullptr;
    parent_ = nullptr;
    frame_buffer_.clear();
    camera_buffer_.clear();
}

}  // namespace hwdisplay::ui
