import ttkbootstrap as ttk
from tkinter import filedialog, messagebox
from src.gui.components import CustomButton, ResultDisplay, StudentTable, VisualizationFrame
from src.core.data_manager import data_manager
from src.gui.styles import *
from src.utils.helpers import get_visual_top_n

class MainWindow:
    """主窗口类"""
    def __init__(self, root):
        self.root = root
        self.root.title("课堂随机点名系统")
        self.root.geometry("1000x700")
        self.root.resizable(True, True)

        # 初始化数据管理器的动画引擎
        self.result_label = ResultDisplay(self.root)
        data_manager.init_animation(self.result_label)

        # 构建界面
        self._create_layout()
        # 刷新学生表格
        self._refresh_table()

    def _create_layout(self):
        """构建界面布局"""
        # 顶部标题栏
        title_frame = ttk.Frame(self.root)
        title_frame.pack(fill="x", pady=PADDING_MEDIUM)
        title_label = ttk.Label(title_frame, text="课堂随机点名系统", font=FONT_TITLE, foreground=COLOR_PRIMARY)
        title_label.pack()

        # 功能按钮栏
        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(fill="x", padx=PADDING_LARGE, pady=PADDING_SMALL)

        # 导入Excel按钮
        CustomButton(btn_frame, text="导入学生名单", command=self._import_excel, style="Primary.TButton").pack(side="left", padx=PADDING_SMALL)
        # 随机点名按钮
        CustomButton(btn_frame, text="随机点名", command=self._random_call, style="Success.TButton").pack(side="left", padx=PADDING_SMALL)
        # 顺序点名按钮
        CustomButton(btn_frame, text="顺序点名", command=self._order_call, style="Success.TButton").pack(side="left", padx=PADDING_SMALL)
        # 导出积分按钮
        CustomButton(btn_frame, text="导出积分详单", command=self._export_excel, style="Primary.TButton").pack(side="left", padx=PADDING_SMALL)
        # 可视化按钮
        CustomButton(btn_frame, text="积分可视化", command=self._show_visual, style="Primary.TButton").pack(side="left", padx=PADDING_SMALL)

        # 点名结果展示区
        result_frame = ttk.Frame(self.root, borderwidth=2, relief="groove")
        result_frame.pack(fill="x", padx=PADDING_LARGE, pady=PADDING_MEDIUM)
        self.result_label.pack(pady=PADDING_MEDIUM)

        # 积分记录按钮区
        record_frame = ttk.Frame(self.root)
        record_frame.pack(fill="x", padx=PADDING_LARGE, pady=PADDING_SMALL)
        # 到课按钮
        CustomButton(record_frame, text="到课(+1.5分)", command=lambda: self._record_call(True, "及格"), style="Success.TButton").pack(side="left", padx=PADDING_SMALL)
        # 未到课按钮
        CustomButton(record_frame, text="未到课(-1.0分)", command=lambda: self._record_call(False, "错误"), style="Primary.TButton").pack(side="left", padx=PADDING_SMALL)
        # 回答优秀按钮
        CustomButton(record_frame, text="回答优秀(+4分)", command=lambda: self._record_call(True, "优秀"), style="Success.TButton").pack(side="left", padx=PADDING_SMALL)
        # 重复问题正确
        CustomButton(record_frame, text="重复正确(+1.5分)", command=lambda: self._record_call(True, "重复正确"), style="Success.TButton").pack(side="left", padx=PADDING_SMALL)
        # 重复问题错误
        CustomButton(record_frame, text="错误(+0分)", command=lambda: self._record_call(True, "重复错误"), style="Primary.TButton").pack(side="left", padx=PADDING_SMALL)

        # 学生表格区
        table_frame = ttk.Frame(self.root, borderwidth=2, relief="groove")
        table_frame.pack(fill="both", expand=True, padx=PADDING_LARGE, pady=PADDING_MEDIUM)
        table_label = ttk.Label(table_frame, text="学生名单", font=FONT_SUBTITLE, foreground=COLOR_TEXT)
        table_label.pack(pady=PADDING_SMALL)
        self.student_table = StudentTable(table_frame)

        # 可视化窗口（隐藏，点击按钮后显示）
        self.visual_window = None

    def _import_excel(self):
        """导入Excel学生名单"""
        file_path = filedialog.askopenfilename(filetypes=[("Excel文件", "*.xlsx")])
        if not file_path:
            return
        success, msg = data_manager.import_excel(file_path)
        if success:
            messagebox.showinfo("导入成功", msg)
            self._refresh_table()
        else:
            messagebox.showerror("导入失败", msg)

    def _export_excel(self):
        """导出积分详单"""
        file_path = filedialog.asksaveasfilename(defaultextension=".xlsx", filetypes=[("Excel文件", "*.xlsx")])
        if not file_path:
            return
        success, msg = data_manager.export_excel(file_path)
        if success:
            messagebox.showinfo("导出成功", msg)
        else:
            messagebox.showerror("导出失败", msg)

    def _random_call(self):
        """随机点名"""
        student, msg = data_manager.random_call()
        if not student:
            messagebox.showwarning("警告", msg)
        # 动画由AnimationEngine自动处理，无需额外更新标签
        self.current_student = student  # 保存当前点名学生
        # 记录本次点名模式，供记录积分时使用（避免从标签文本解析）
        self.current_call_mode = "random"

    def _order_call(self):
        """顺序点名"""
        student, msg = data_manager.order_call()
        if not student:
            messagebox.showwarning("警告", msg)
            return
        # 显示顺序点名结果
        self.result_label.config(
            text=f"📋 顺序点名结果 📋\n学号：{student[0]}\n姓名：{student[1]}\n专业：{student[2]}",
            font=FONT_SUBTITLE
        )
        self.current_student = student  # 保存当前点名学生
        # 记录本次点名模式
        self.current_call_mode = "order"

    def _record_call(self, is_arrived, answer_level):
        """记录点名结果（积分）"""
        if not hasattr(self, "current_student") or not self.current_student:
            messagebox.showwarning("警告", "请先进行点名")
            return
        student_id = self.current_student[0]
        # 优先使用显式记录的点名模式（`current_call_mode`），避免依赖标签文本内容
        call_mode = getattr(self, "current_call_mode", None)
        if call_mode not in ("random", "order"):
            # 回退到原有文本解析逻辑（兼容旧文本）
            call_mode = "random" if "随机" in self.result_label.cget("text") else "order"
        success = data_manager.record_call(student_id, call_mode, is_arrived, answer_level)
        if success:
            messagebox.showinfo("成功", "积分记录成功")
            self._refresh_table()
        else:
            messagebox.showerror("失败", "积分记录失败")

    def _show_visual(self):
        """显示积分可视化"""
        students = data_manager.get_all_students()
        if not students:
            messagebox.showwarning("警告", "暂无学生数据")
            return
        # 创建可视化窗口
        self.visual_window = ttk.Toplevel(self.root)
        self.visual_window.title("积分可视化")
        self.visual_window.geometry("800x500")
        # 可视化组件
        visual_frame = VisualizationFrame(self.visual_window)
        visual_frame.pack(fill="both", expand=True)
        # 显示TOP N学生图表
        top_students = get_visual_top_n(students)
        visual_frame.show_chart(top_students)

    def _refresh_table(self):
        """刷新学生表格"""
        students = data_manager.get_all_students()
        self.student_table.refresh_data(students)