"""AutoPOE2 - Giao diện Cấu hình & Điều khiển Tự động Gán Skill (Skill Binder Panel).

Cung cấp widget cấu hình gán kỹ năng vào các ô phím tắt Q, E, R, T, F, RMB
và kích hoạt luồng đồng bộ ngầm không chiếm chuột.
Tuân thủ Rule 1, Rule 4 (Kiến trúc Module Hóa), Rule 7 (Chuẩn người chơi thật).
"""

from __future__ import annotations

import threading
from typing import Any, Dict
import customtkinter as ctk

from src.assistant_tool import ui_theme as theme
from src.common.win32_window import find_poe2_window
from src.assistant_tool.skills.skill_constants import ActionBarSlot
from src.assistant_tool.skills.skill_binder import SkillBinder


SLOT_PRESET_OPTIONS = [
    "Giữ nguyên (Không đổi)",
    "Gem Skill (Hàng 1, Ô 1)",
    "Gem Skill (Hàng 1, Ô 2)",
    "Gem Skill (Hàng 1, Ô 3)",
    "Gem Skill (Hàng 1, Ô 4)",
    "Gem Skill (Hàng 2, Ô 1)",
    "Gem Skill (Hàng 2, Ô 2)",
    "Vũ khí (Skill 1)",
    "Vũ khí (Skill 2)",
    "Vũ khí (Skill 3)",
    "Gỡ bỏ (Unbind / Trống)",
]


def build_skill_binder_section(app: Any, parent: Any) -> None:
    """Xây dựng cụm widget Cấu hình Gán Kỹ Năng trong Tab Combat."""
    sec = app._create_section_label(parent, "🎯 TỰ ĐỘNG GẮN SKILL VÀO PHÍM TẮT (AUTO SKILL BINDER)")
    sec.pack(anchor="w", pady=(8, 4))

    app.chk_auto_sync_skills = ctk.CTkCheckBox(
        parent,
        text="Tự động đồng bộ phím tắt kỹ năng khi gắn kết game client",
        font=ctk.CTkFont(size=11, weight="bold"),
        text_color=theme.c("text_primary"),
        fg_color=theme.c("start"),
        hover_color=theme.c("ok_hover"),
    )
    app.chk_auto_sync_skills.pack(anchor="w", padx=8, pady=(2, 4))

    # Khung chọn skill cho các slot chính (Q, E, R, T, F)
    slots_frame = ctk.CTkFrame(parent, fg_color=theme.c("card_bg"), corner_radius=6)
    slots_frame.pack(fill="x", padx=8, pady=4)

    app.skill_slot_combos: Dict[ActionBarSlot, ctk.CTkComboBox] = {}

    slots_to_config = [
        (ActionBarSlot.SLOT_Q, "Slot Q:"),
        (ActionBarSlot.SLOT_E, "Slot E:"),
        (ActionBarSlot.SLOT_R, "Slot R:"),
        (ActionBarSlot.SLOT_T, "Slot T:"),
        (ActionBarSlot.SLOT_F, "Slot F:"),
    ]

    saved = getattr(app, "user_settings", {})
    saved_skills = saved.get("skill_bindings", {})

    for idx, (slot, label_text) in enumerate(slots_to_config):
        row = ctk.CTkFrame(slots_frame, fg_color="transparent")
        row.pack(fill="x", padx=8, pady=2)

        lbl = ctk.CTkLabel(
            row,
            text=f"  ↳ {label_text}",
            font=ctk.CTkFont(size=10, weight="bold"),
            text_color="#94a3b8",
            width=70,
            anchor="w",
        )
        lbl.pack(side="left")

        combo = ctk.CTkComboBox(
            row,
            values=SLOT_PRESET_OPTIONS,
            font=ctk.CTkFont(size=10),
            dropdown_font=ctk.CTkFont(size=10),
            width=220,
            height=22,
            command=lambda val, a=app: _save_skill_bindings(a),
        )
        default_val = saved_skills.get(slot.value, "Giữ nguyên (Không đổi)")
        combo.set(default_val)
        combo.pack(side="left", padx=4)

        app.skill_slot_combos[slot] = combo

    # Khởi tạo giá trị checkbox từ user_settings
    if saved.get("auto_sync_skills", False):
        app.chk_auto_sync_skills.select()
    app.chk_auto_sync_skills.configure(command=lambda: _save_skill_bindings(app))

    # Nút bấm kích hoạt đồng bộ
    btn_row = ctk.CTkFrame(slots_frame, fg_color="transparent")
    btn_row.pack(fill="x", padx=8, pady=(4, 6))

    app.btn_sync_skills = ctk.CTkButton(
        btn_row,
        text="⚡ Đồng Bộ Phím Tắt Ngay",
        font=ctk.CTkFont(size=10, weight="bold"),
        fg_color=theme.c("info"),
        hover_color=theme.c("info_hover"),
        height=24,
        command=lambda: trigger_skill_sync_thread(app),
    )
    app.btn_sync_skills.pack(side="left", padx=4)

    app.lbl_skill_sync_status = ctk.CTkLabel(
        btn_row,
        text="Sẵn sàng cấu hình",
        font=ctk.CTkFont(size=10),
        text_color="#94a3b8",
    )
    app.lbl_skill_sync_status.pack(side="left", padx=8)


def _save_skill_bindings(app: Any) -> None:
    """Lưu cấu hình gán kỹ năng vào user_settings.json."""
    combos = getattr(app, "skill_slot_combos", {})
    bindings = {slot.value: combo.get() for slot, combo in combos.items()}
    auto_sync = (
        bool(app.chk_auto_sync_skills.get())
        if hasattr(app, "chk_auto_sync_skills")
        else False
    )
    from src.assistant_tool.ui.settings_manager import save_user_settings
    save_user_settings({"skill_bindings": bindings, "auto_sync_skills": auto_sync})


def trigger_skill_sync_thread(app: Any) -> None:
    """Kích hoạt thread chạy ngầm gán skill không chiếm chuột."""
    _save_skill_bindings(app)
    thread = threading.Thread(target=_run_skill_sync_worker, args=(app,), daemon=True)
    thread.start()


def _run_skill_sync_worker(app: Any) -> None:
    """Worker thực thi chu trình gán phím kỹ năng ngầm."""
    hwnd = find_poe2_window()
    if not hwnd:
        if hasattr(app, "lbl_skill_sync_status"):
            app.lbl_skill_sync_status.configure(
                text="❌ Không tìm thấy game POE2!", text_color=theme.c("danger")
            )
        return

    if hasattr(app, "lbl_skill_sync_status"):
        app.lbl_skill_sync_status.configure(
            text="⏳ Đang đồng bộ kỹ năng...", text_color=theme.c("warning")
        )

    try:
        binder = SkillBinder(hwnd=hwnd)
        sync_count = 0

        for slot, combo in getattr(app, "skill_slot_combos", {}).items():
            choice = combo.get()
            if choice == "Giữ nguyên (Không đổi)":
                continue

            if choice == "Gỡ bỏ (Unbind / Trống)":
                binder.unbind_slot(slot, delay_between=0.20)
                sync_count += 1
            elif choice.startswith("Gem Skill (Hàng 1, Ô 1)"):
                binder.bind_gem_skill(slot, row=0, col=0, delay_between=0.20)
                sync_count += 1
            elif choice.startswith("Gem Skill (Hàng 1, Ô 2)"):
                binder.bind_gem_skill(slot, row=0, col=1, delay_between=0.20)
                sync_count += 1
            elif choice.startswith("Gem Skill (Hàng 1, Ô 3)"):
                binder.bind_gem_skill(slot, row=0, col=2, delay_between=0.20)
                sync_count += 1
            elif choice.startswith("Gem Skill (Hàng 1, Ô 4)"):
                binder.bind_gem_skill(slot, row=0, col=3, delay_between=0.20)
                sync_count += 1
            elif choice.startswith("Gem Skill (Hàng 2, Ô 1)"):
                binder.bind_gem_skill(slot, row=1, col=0, delay_between=0.20)
                sync_count += 1
            elif choice.startswith("Gem Skill (Hàng 2, Ô 2)"):
                binder.bind_gem_skill(slot, row=1, col=1, delay_between=0.20)
                sync_count += 1
            elif choice.startswith("Vũ khí (Skill 1)"):
                binder.bind_weapon_skill(slot, col_index=0, delay_between=0.20)
                sync_count += 1
            elif choice.startswith("Vũ khí (Skill 2)"):
                binder.bind_weapon_skill(slot, col_index=1, delay_between=0.20)
                sync_count += 1
            elif choice.startswith("Vũ khí (Skill 3)"):
                binder.bind_weapon_skill(slot, col_index=2, delay_between=0.20)
                sync_count += 1

        if hasattr(app, "lbl_skill_sync_status"):
            app.lbl_skill_sync_status.configure(
                text=f"✅ Đã đồng bộ {sync_count} slot!", text_color=theme.c("start")
            )
    except Exception as exc:
        if hasattr(app, "lbl_skill_sync_status"):
            app.lbl_skill_sync_status.configure(
                text=f"❌ Lỗi: {str(exc)[:25]}", text_color=theme.c("danger")
            )
