import tkinter as tk
from tkinter import messagebox

class UltimateTimer:
    def __init__(self, root):
        self.root = root
        self.root.title("终极 Python 计时器")
        self.root.geometry("400x550")
        self.root.resizable(False, False)

        # --- 变量初始化 ---
        self.total_seconds = 0
        self.time_left = 0
        self.is_running = False
        self.mode = "countdown"  # 模式: countdown (倒计时) 或 stopwatch (秒表)
        self.stopwatch_counter = 0 # 秒表计数器

        # --- 界面布局 ---
        self._setup_styles()
        self._create_widgets()

    def _setup_styles(self):
        # 深色主题配色
        self.bg_color = "#2b2b2b"
        self.fg_color = "#ffffff"
        self.accent_color = "#4CAF50" # 绿色
        self.pause_color = "#FF9800"  # 橙色
        self.reset_color = "#F44336"  # 红色
        self.progress_bg = "#444444"

        self.root.configure(bg=self.bg_color)

    def _create_widgets(self):
        # 1. 模式切换按钮
        self.mode_frame = tk.Frame(self.root, bg=self.bg_color)
        self.mode_frame.pack(pady=10)

        self.btn_countdown = tk.Button(
            self.mode_frame, text="倒计时模式", command=self.set_countdown_mode,
            bg=self.accent_color, fg="white", bd=0, padx=10, pady=5
        )
        self.btn_countdown.pack(side=tk.LEFT, padx=5)

        self.btn_stopwatch = tk.Button(
            self.mode_frame, text="秒表模式", command=self.set_stopwatch_mode,
            bg="#555555", fg="white", bd=0, padx=10, pady=5
        )
        self.btn_stopwatch.pack(side=tk.LEFT, padx=5)

        # 2. 时间显示标签 (大号字体)
        self.time_label = tk.Label(
            self.root, text="00:00:00", font=("Helvetica", 48, "bold"),
            bg=self.bg_color, fg=self.fg_color
        )
        self.time_label.pack(pady=20)

        # 3. 进度条 (Canvas 绘制)
        self.progress_canvas = tk.Canvas(
            self.root, height=10, bg=self.progress_bg, highlightthickness=0
        )
        self.progress_canvas.pack(fill=tk.X, padx=20)
        # 初始进度条填充
        self.progress_bar = self.progress_canvas.create_rectangle(
            0, 0, 360, 10, fill=self.accent_color, outline=""
        )

        # 4. 输入框 (仅倒计时模式可见)
        self.input_frame = tk.Frame(self.root, bg=self.bg_color)
        self.input_frame.pack(pady=10)
        
        tk.Label(self.input_frame, text="输入秒数:", bg=self.bg_color, fg=self.fg_color).pack(side=tk.LEFT)
        self.time_entry = tk.Entry(self.input_frame, width=10, font=("Arial", 14), justify='center')
        self.time_entry.pack(side=tk.LEFT, padx=5)
        self.time_entry.insert(0, "60") # 默认60秒

        # 5. 控制按钮
        self.btn_frame = tk.Frame(self.root, bg=self.bg_color)
        self.btn_frame.pack(pady=20)

        self.start_btn = tk.Button(
            self.btn_frame, text="开始", width=8, height=2,
            bg=self.accent_color, fg="white", font=("Arial", 10, "bold"),
            command=self.start_action
        )
        self.start_btn.grid(row=0, column=0, padx=10)

        self.pause_btn = tk.Button(
            self.btn_frame, text="暂停", width=8, height=2,
            bg=self.pause_color, fg="white", font=("Arial", 10, "bold"),
            command=self.pause_action
        )
        self.pause_btn.grid(row=0, column=1, padx=10)

        self.reset_btn = tk.Button(
            self.btn_frame, text="重置", width=8, height=2,
            bg=self.reset_color, fg="white", font=("Arial", 10, "bold"),
            command=self.reset_action
        )
        self.reset_btn.grid(row=0, column=2, padx=10)

    # --- 逻辑功能 ---

    def set_countdown_mode(self):
        self.mode = "countdown"
        self.reset_action()
        self.btn_countdown.config(bg=self.accent_color, fg="white")
        self.btn_stopwatch.config(bg="#555555", fg="#aaaaaa")
        self.input_frame.pack(pady=10) # 显示输入框
        self.time_label.config(text="00:00:00")

    def set_stopwatch_mode(self):
        self.mode = "stopwatch"
        self.reset_action()
        self.btn_stopwatch.config(bg=self.accent_color, fg="white")
        self.btn_countdown.config(bg="#555555", fg="#aaaaaa")
        self.input_frame.pack_forget() # 隐藏输入框
        self.time_label.config(text="00:00:00")

    def update_display(self, seconds):
        if self.mode == "countdown":
            mins, secs = divmod(seconds, 60)
            hours, mins = divmod(mins, 60)
            time_str = f"{hours:02d}:{mins:02d}:{secs:02d}"
            self.time_label.config(text=time_str)
            # 更新进度条宽度
            if self.total_seconds > 0:
                progress_ratio = seconds / self.total_seconds
                new_width = int(360 * progress_ratio)
                self.progress_canvas.coords(self.progress_bar, 0, 0, new_width, 10)
        
        else: # 秒表模式
            mins, secs = divmod(seconds, 60)
            hours, mins = divmod(mins, 60)
            time_str = f"{hours:02d}:{mins:02d}:{secs:02d}"
            self.time_label.config(text=time_str)
            # 秒表模式下进度条仅做装饰或动态效果（这里设为简单的循环动画）
            # 这里简化处理，保持满格或做呼吸灯效果，暂设为满格
            self.progress_canvas.coords(self.progress_bar, 0, 0, 360, 10)

    def start_action(self):
        if self.is_running:
            return

        if self.mode == "countdown":
            # 如果是刚开始（或重置后），读取输入框
            if self.time_left == 0 and self.total_seconds == 0:
                try:
                    val = int(self.time_entry.get())
                    if val <= 0: raise ValueError
                    self.total_seconds = val
                    self.time_left = val
                except ValueError:
                    messagebox.showerror("错误", "请输入有效的正整数秒数！")
                    return
            
            if self.time_left > 0:
                self.is_running = True
                self.countdown_tick()
        
        else: # 秒表模式
            self.is_running = True
            self.stopwatch_tick()

    def countdown_tick(self):
        if self.is_running and self.time_left > 0:
            self.time_left -= 1
            self.update_display(self.time_left)
            self.root.after(1000, self.countdown_tick)
        elif self.time_left == 0 and self.is_running:
            self.is_running = False
            messagebox.showinfo("时间到", "倒计时结束！")
            self.root.bell() # 系统蜂鸣音

    def stopwatch_tick(self):
        if self.is_running:
            self.stopwatch_counter += 1
            self.update_display(self.stopwatch_counter)
            self.root.after(1000, self.stopwatch_tick)

    def pause_action(self):
        self.is_running = False

    def reset_action(self):
        self.is_running = False
        if self.mode == "countdown":
            self.time_left = 0
            self.total_seconds = 0
            self.update_display(0)
            # 重置进度条
            self.progress_canvas.coords(self.progress_bar, 0, 0, 0, 10)
        else:
            self.stopwatch_counter = 0
            self.time_label.config(text="00:00:00")

if __name__ == "__main__":
    root = tk.Tk()
    app = UltimateTimer(root)
    root.mainloop()