''' app/ui/widgets/menubar.py '''
from PyQt6.QtGui import QAction
from PyQt6.QtWidgets import QMenuBar, QApplication, QMessageBox, QDialog, QVBoxLayout, QLabel, QPushButton


class MenuBar(QMenuBar):
    """
    Initialize the menu bar.

    Args:
        parent: The parent widget.
    """

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

        self.settings_window = None

        # setup menus
        file_menu = self.addMenu("File")
        # edit_menu = self.addMenu("Edit")
        # view_menu = self.addMenu("View")
        help_menu = self.addMenu("Help")

        # --file menu--
        # new job
        new_job_action = QAction("New Job...", self)
        new_job_action.setShortcut(f'Ctrl+N')
        new_job_action.triggered.connect(self.new_job)
        file_menu.addAction(new_job_action)
        # settings
        settings_action = QAction("Settings...", self)
        settings_action.triggered.connect(self.show_settings)
        settings_action.setShortcut(f'Ctrl+,')
        file_menu.addAction(settings_action)
        # exit
        exit_action = QAction('&Exit', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.triggered.connect(QApplication.instance().quit)
        file_menu.addAction(exit_action)

        # --help menu--
        about_action = QAction("About", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
        update_action = QAction("Check for Updates...", self)
        update_action.triggered.connect(self.check_for_updates)
        help_menu.addAction(update_action)

    def new_job(self):
        self.parent().new_job()

    def show_settings(self):
        from src.ui.settings_window import SettingsWindow
        self.settings_window = SettingsWindow()
        self.settings_window.show()

    @staticmethod
    def show_about():
        from src.ui.about_window import AboutDialog
        dialog = AboutDialog()
        dialog.exec()

    @staticmethod
    def check_for_updates():
        from src.utilities.misc_helper import check_for_updates
        from src.version import APP_NAME, APP_VERSION, APP_REPO_NAME, APP_REPO_OWNER
        found_update = check_for_updates(APP_REPO_NAME, APP_REPO_OWNER, APP_NAME, APP_VERSION)
        if found_update:
            dialog = UpdateDialog(found_update, APP_VERSION)
            dialog.exec()
        else:
            QMessageBox.information(None, "No Update", "No updates available.")


class UpdateDialog(QDialog):
    def __init__(self, release_info, current_version, parent=None):
        super().__init__(parent)
        self.setWindowTitle(f"Update Available ({current_version} -> {release_info['tag_name']})")

        layout = QVBoxLayout()
        label = QLabel(f"A new version ({release_info['tag_name']}) is available! Current version: {current_version}")
        layout.addWidget(label)

        # Label to show the release notes
        description = QLabel(release_info["body"])
        layout.addWidget(description)

        # Button to download the latest version
        download_button = QPushButton(f"Download Latest Version ({release_info['tag_name']})")
        download_button.clicked.connect(lambda: self.open_url(release_info["html_url"]))
        layout.addWidget(download_button)

        # OK button to dismiss the dialog
        ok_button = QPushButton("Dismiss")
        ok_button.clicked.connect(self.accept)  # Close the dialog when clicked
        layout.addWidget(ok_button)

        self.setLayout(layout)

    def open_url(self, url):
        from PyQt6.QtCore import QUrl
        from PyQt6.QtGui import QDesktopServices
        QDesktopServices.openUrl(QUrl(url))
        self.accept()
