"""Reminder module for widgets."""

from __future__ import annotations

import random

from PySide2.QtCore import Qt, QTimer
from PySide2.QtGui import QCloseEvent
from PySide2.QtWidgets import QDialog, QLabel, QPushButton, QVBoxLayout

from ..config import conf


class Reminder(QDialog):
    """闹钟提醒对话框."""

    def __init__(self) -> None:
        super().__init__()
        self.setWindowTitle(conf.BLINK_TITLE)
        self.setModal(True)
        self.setWindowFlags(
            self.windowFlags() | Qt.WindowStaysOnTopHint | Qt.WindowType.Dialog,
        )
        self.setWindowFlag(Qt.WindowCloseButtonHint, on=False)
        self._setup_ui()
        self._start_blinking()

    def _setup_ui(self) -> None:
        """设置对话框 UI."""
        layout = QVBoxLayout()
        msg_label = QLabel(conf.BLINK_CONTENT)
        msg_label.setStyleSheet("color: red; font-size: 24px;")
        msg_label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        close_button = QPushButton("关闭闹钟")
        close_button.clicked.connect(self.close_alarm)

        layout.addWidget(msg_label)
        layout.addWidget(close_button)
        self.setLayout(layout)

    def _start_blinking(self) -> None:
        """启动闪烁效果."""
        self.blink_timer = QTimer(self)
        self.blink_timer.timeout.connect(self.update_blink)
        self.blink_state = False
        self.bg_color = random.choice(conf.BLINK_BG_COLORS)  # noqa: S311
        self.blink_timer.start(conf.BLINK_INTERVAL)

    def update_blink(self) -> None:
        """更新闪烁状态."""
        if conf.BLINK_TYPE == "color":
            colors = [c for c in conf.BLINK_BG_COLORS if c != self.bg_color]
            self.bg_color = random.choice(colors)  # noqa: S311
            self.setStyleSheet(f"background-color: {self.bg_color}")
        else:
            self.setWindowOpacity(0.3 if self.blink_state else 1.0)

        self.blink_state = not self.blink_state

    def close_alarm(self) -> None:
        """关闭闹钟对话框."""
        self.stop_blinking()
        self.accept()

    def stop_blinking(self) -> None:
        """停止闪烁."""
        self.blink_timer.stop()
        self.setWindowOpacity(1.0)

    def closeEvent(self, event: QCloseEvent) -> None:  # type: ignore[override]
        """关闭窗口时确保定时器停止."""
        self.stop_blinking()
        super().closeEvent(event)
