# standard
from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING, Optional

# PyQGIS
from qgis.core import Qgis
from qgis.PyQt import uic
from qgis.PyQt.QtGui import QIcon, QShowEvent

# Project
from oslandia.__about__ import DIR_PLUGIN_ROOT
from oslandia.gui.onboarding.wdg_base_page import WidgetPageBase

# Project
from oslandia.helpdesk.user import UserRequestManager
from oslandia.toolbelt import PlgLogger


if TYPE_CHECKING:
    from qgis.PyQt.QtWidgets import QWidget


class LoggedInfoPage(WidgetPageBase):
    def __init__(self, parent: Optional[QWidget] = None) -> None:
        """Page containing information about the currently logged-in user.

        :param parent: Parent widget, defaults to None
        :type parent: QObject, optional
        """
        # Initialize module and UI
        super().__init__(parent)
        uic.loadUi(Path(__file__).parent / f"{Path(__file__).stem}.ui", self)
        self.log = PlgLogger().log

        self.update_user_widget()
        self.btn_continue.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT / "resources/images/flash.svg"))
        )
        self.btn_continue.clicked.connect(lambda: self.next_page_signal.emit(0))
        self.btn_continue.setIcon(QIcon(":images/themes/default/mActionArrowRight.svg"))

    def showEvent(self, event: QShowEvent) -> None:  # noqa: N802
        """Called when the page becomes visible."""
        super().showEvent(event)
        self.update_user_widget()

    def update_user_widget(self) -> None:
        """Update the user widget with the current user."""
        try:
            manager = UserRequestManager()
            user = manager.get_current_user()
            self.wdg_user.set_user(user)
        except Exception as err:
            self.log(
                message=f"Error updating user widget: {err}",
                log_level=Qgis.MessageLevel.Critical,
            )
