"""Alarmclock module for widgets."""

from __future__ import annotations

from functools import partial

from PySide2.QtCore import Qt, QTime, QTimer
from PySide2.QtGui import QMoveEvent, QResizeEvent
from PySide2.QtWidgets import (
    QHBoxLayout,
    QLabel,
    QPushButton,
    QWidget,
)
from pytola_qtstyles import apply_theme

from .alarmclock_ui import Ui_AlarmClock

__version__ = "0.1.3"

from ..config import conf
from .reminder import Reminder


class AlarmClock(QWidget, Ui_AlarmClock):
    """数字闹钟 GUI 主窗口."""

    def __init__(self) -> None:
        super().__init__()
        self.setupUi(self)
        self.setGeometry(*conf.WIN_POS, *conf.WIN_SIZE)
        self.setWindowTitle(f"{conf.ALARM_CLOCK_TITLE} v{__version__}")
        self.status_label.setStyleSheet(
            "color: red; font-weight: bold; text-decoration: underline; font-style: italic;",
        )
        self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.clock_label.setStyleSheet(
            f"font: {conf.DIGITAL_FONT}; background-color: black; "
            f"border: 2px dashed {conf.DIGITAL_BORDER_COLORS[0]}; border-radius: 10px; padding: 10px;",
        )
        self._init_clock()
        self._init_alarm()
        self._setup_delay_buttons()
        self.set_button.clicked.connect(self.on_toggle_alarm)
        self.alarm_timer.timeout.connect(self.on_check_alarm)

        self.resize(self.minimumSize())
        apply_theme(self, conf.THEME)

    def _init_clock(self) -> None:
        """初始化数字时钟."""
        self.alarm_time_spinbox.setDisplayFormat("HH:mm:ss")
        self.alarm_time_spinbox.setTime(
            QTime.currentTime().addSecs(conf.DELAY_STEPS[0] * 60),
        )
        # 立即更新时钟显示，避免 UI 文件中的默认值 "00:00:00"
        self.clock_label.update_time()

    def _init_alarm(self) -> None:
        """初始化闹钟相关组件和状态."""
        self.alarm_timer = QTimer()
        self.alarm_set = False
        self.alarm_time: QTime = QTime()
        self._alarm_triggered = False

    def _setup_delay_buttons(self) -> None:
        """设置延时按钮."""
        delay_layout = QHBoxLayout()
        delay_layout.addWidget(QLabel("延时 (分钟):"))
        for minutes in conf.DELAY_STEPS:
            button = QPushButton(str(minutes))
            button.clicked.connect(partial(self.set_delay, minutes))
            delay_layout.addWidget(button)
        reset_button = QPushButton("重置")
        reset_button.clicked.connect(self.reset_alarm_time)
        delay_layout.addWidget(reset_button)
        self.verticalLayout.insertLayout(1, delay_layout)

    def set_delay(self, minutes: int) -> None:
        """设置延时闹钟."""
        current_time = self.alarm_time_spinbox.time()
        new_time = current_time.addSecs(minutes * 60)
        self.alarm_time_spinbox.setTime(new_time)

    def reset_alarm_time(self) -> None:
        """重置闹钟时间为当前时间."""
        self.alarm_time_spinbox.setTime(QTime.currentTime())

    def on_toggle_alarm(self) -> None:
        """切换闹钟状态."""
        if self.alarm_set:
            self.alarm_set = False
            self.alarm_timer.stop()
            self.set_button.setText("设置闹钟")
            self.status_label.setText("闹钟已取消!")
            self._alarm_triggered = False
            return

        self.alarm_set = True
        self.set_button.setText("取消闹钟")
        self.alarm_time = self.alarm_time_spinbox.time()
        self.alarm_timer.start(1000)
        self.status_label.setText(f"闹钟已设置: {self.alarm_time.toString('HH:mm:ss')}")
        self._alarm_triggered = False

    def on_check_alarm(self) -> None:
        """检查是否到达闹钟时间."""
        if not self.alarm_set or self._alarm_triggered:
            return
        current_time = QTime.currentTime()
        secs_until_alarm = current_time.secsTo(self.alarm_time)
        if secs_until_alarm <= 0:
            self._alarm_triggered = True
            self.dialog = Reminder()
            self.dialog.finished.connect(self.on_dialog_closed)
            self.dialog.show()
            self.status_label.setText("⏰ 闹钟响了! ⏰")

    def on_dialog_closed(self) -> None:
        """处理对话框关闭事件."""
        if not self.repeat_checkbox.isChecked():
            self.on_toggle_alarm()
            return
        self._alarm_triggered = False
        self.status_label.setText(f"下次响铃: {self.alarm_time.toString('HH:mm:ss')}")

    def moveEvent(self, event: QMoveEvent) -> None:
        """处理窗口移动事件."""
        super().moveEvent(event)
        conf.WIN_POS = [self.x(), self.y()]

    def resizeEvent(self, event: QResizeEvent) -> None:
        """处理窗口 resize 事件."""
        super().resizeEvent(event)
        conf.WIN_SIZE = [self.width(), self.height()]
