"""
Loading progress widget for pyPhotoAlbum

Displays loading progress in the lower-right corner of the window.
"""

from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QProgressBar
from PyQt6.QtCore import Qt, QPropertyAnimation, QEasingCurve, pyqtProperty  # type: ignore[attr-defined]
from PyQt6.QtGui import QPalette, QColor


class LoadingWidget(QWidget):
    """
    A widget that displays loading progress in the lower-right corner.

    Features:
    - Fade in/out animations
    - Progress bar with percentage
    - Status message display
    - Compact, non-intrusive design
    """

    def __init__(self, parent=None):
        super().__init__(parent)

        # Widget configuration
        self.setWindowFlags(Qt.WindowType.ToolTip | Qt.WindowType.FramelessWindowHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False)
        self.setFixedSize(280, 80)

        # Styling
        self.setStyleSheet("""
            QWidget {
                background-color: rgba(50, 50, 50, 230);
                border-radius: 8px;
                border: 1px solid rgba(100, 100, 100, 180);
            }
            QLabel {
                color: white;
                background-color: transparent;
                font-size: 11pt;
            }
            QProgressBar {
                border: 1px solid rgba(80, 80, 80, 180);
                border-radius: 4px;
                background-color: rgba(30, 30, 30, 200);
                text-align: center;
                color: white;
                font-size: 10pt;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(70, 130, 180, 220),
                    stop:1 rgba(100, 160, 210, 220));
                border-radius: 3px;
            }
        """)

        # Layout
        layout = QVBoxLayout()
        layout.setContentsMargins(12, 10, 12, 10)
        layout.setSpacing(8)

        # Status label
        self._status_label = QLabel("Loading...")
        self._status_label.setAlignment(Qt.AlignmentFlag.AlignLeft)
        layout.addWidget(self._status_label)

        # Progress bar with percentage label
        progress_layout = QHBoxLayout()
        progress_layout.setSpacing(8)

        self._progress_bar = QProgressBar()
        self._progress_bar.setMinimum(0)
        self._progress_bar.setMaximum(100)
        self._progress_bar.setValue(0)
        self._progress_bar.setTextVisible(True)
        self._progress_bar.setFormat("%p%")
        progress_layout.addWidget(self._progress_bar, 1)

        layout.addLayout(progress_layout)

        self.setLayout(layout)

        # Animation for fade in/out
        self._opacity = 1.0
        self._fade_animation = QPropertyAnimation(self, b"opacity")
        self._fade_animation.setDuration(300)
        self._fade_animation.setEasingCurve(QEasingCurve.Type.InOutQuad)

        # Initially hidden
        self.hide()

    @pyqtProperty(float)
    def opacity(self):
        """Get opacity for animation"""
        return self._opacity

    @opacity.setter  # type: ignore[no-redef]
    def opacity(self, value: float) -> None:
        """Set opacity for animation"""
        self._opacity = value
        self.setWindowOpacity(value)

    def show_loading(self, message: str = "Loading..."):
        """
        Show the loading widget with a fade-in animation.

        Args:
            message: Initial status message
        """
        self.set_status(message)
        self.set_progress(0)

        # Position in lower-right corner of parent
        self._reposition()

        # Fade in
        self.show()
        self._fade_animation.stop()
        self._fade_animation.setStartValue(0.0)
        self._fade_animation.setEndValue(1.0)
        self._fade_animation.start()

    def hide_loading(self):
        """Hide the loading widget with a fade-out animation."""
        self._fade_animation.stop()
        self._fade_animation.setStartValue(1.0)
        self._fade_animation.setEndValue(0.0)
        self._fade_animation.finished.connect(self.hide)
        self._fade_animation.start()

    def set_status(self, message: str):
        """
        Update the status message.

        Args:
            message: Status message to display
        """
        self._status_label.setText(message)

    def set_progress(self, value: int, maximum: int = 100):
        """
        Update the progress bar.

        Args:
            value: Current progress value
            maximum: Maximum progress value (default: 100)
        """
        self._progress_bar.setMaximum(maximum)
        self._progress_bar.setValue(value)

    def set_indeterminate(self, indeterminate: bool = True):
        """
        Set the progress bar to indeterminate mode (busy indicator).

        Args:
            indeterminate: True for indeterminate, False for normal progress
        """
        if indeterminate:
            self._progress_bar.setMinimum(0)
            self._progress_bar.setMaximum(0)
        else:
            self._progress_bar.setMinimum(0)
            self._progress_bar.setMaximum(100)

    def _reposition(self):
        """Position the widget in the lower-right corner of the parent."""
        if self.parent():
            parent_rect = self.parent().rect()
            margin = 20
            x = parent_rect.width() - self.width() - margin
            y = parent_rect.height() - self.height() - margin
            self.move(x, y)

    def showEvent(self, event):
        """Handle show event to reposition."""
        super().showEvent(event)
        self._reposition()

    def resizeParent(self):
        """Call this when parent is resized to reposition the widget."""
        if self.isVisible():
            self._reposition()
