from qgis.PyQt import QtWidgets, QtCore, QtGui
from qgis.PyQt.QtGui import QIcon
import os


class SecureLineEdit(QtWidgets.QLineEdit):
    """Ein QLineEdit das Copy/Cut/Paste verhindert - für Passwort-Felder"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setEchoMode(QtWidgets.QLineEdit.Password)
        # Kontextmenü deaktivieren
        self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)

    def keyPressEvent(self, event):
        # Ctrl+C, Ctrl+X, Ctrl+V blockieren
        if event.modifiers() == QtCore.Qt.ControlModifier:
            if event.key() in (QtCore.Qt.Key_C, QtCore.Qt.Key_X, QtCore.Qt.Key_V):
                event.ignore()
                return
        super().keyPressEvent(event)

    def mousePressEvent(self, event):
        # Doppelklick zum Markieren verhindern
        if event.type() == QtCore.QEvent.MouseButtonDblClick:
            event.ignore()
            return
        super().mousePressEvent(event)

    def mouseDoubleClickEvent(self, event):
        # Doppelklick komplett ignorieren
        event.ignore()


class PasswordConfirmDialog(QtWidgets.QDialog):
    """Dialog zur Passwort-Bestätigung vor kritischen Aktionen wie Abnahme/Ablehnung"""

    def __init__(self, parent=None, action_text="Aktion bestätigen", description=""):
        super().__init__(parent)
        self.setWindowTitle("Bestätigung erforderlich")
        self.setMinimumWidth(400)
        self.setModal(True)

        # Icon setzen
        icon_path = os.path.join(os.path.dirname(__file__), "..", "assets", "icon.png")
        icon_path = os.path.abspath(icon_path)
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))

        self._setup_ui(action_text, description)

    def _setup_ui(self, action_text, description):
        layout = QtWidgets.QVBoxLayout(self)
        layout.setSpacing(16)

        # Styles
        self.setStyleSheet("""
            QDialog {
                background-color: #ffffff;
            }
            QLabel {
                color: #333;
            }
            QLineEdit {
                padding: 8px;
                border: 1px solid #ccc;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border: 1px solid #0078d7;
            }
            QPushButton {
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 13px;
            }
        """)

        # Beschreibung
        if description:
            desc_label = QtWidgets.QLabel(description)
            desc_label.setWordWrap(True)
            desc_label.setStyleSheet("color: #666; margin-bottom: 8px;")
            layout.addWidget(desc_label)

        # Warnung
        warning_label = QtWidgets.QLabel(
            "Bitte geben Sie Ihr Passwort ein, um diese Aktion zu bestätigen."
        )
        warning_label.setStyleSheet("font-weight: bold; margin-bottom: 8px;")
        layout.addWidget(warning_label)

        # Passwort-Eingabe mit SecureLineEdit
        self.password_edit = SecureLineEdit()
        self.password_edit.setPlaceholderText("Passwort")
        layout.addWidget(self.password_edit)

        # Fehler-Label (initial versteckt)
        self.error_label = QtWidgets.QLabel("")
        self.error_label.setStyleSheet("color: #dc2626; font-size: 12px;")
        self.error_label.hide()
        layout.addWidget(self.error_label)

        # Buttons
        button_layout = QtWidgets.QHBoxLayout()
        button_layout.addStretch()

        self.cancel_btn = QtWidgets.QPushButton("Abbrechen")
        self.cancel_btn.setStyleSheet("""
            QPushButton {
                background-color: #fff;
                border: 1px solid #ccc;
                color: #333;
            }
            QPushButton:hover {
                background-color: #f5f5f5;
            }
        """)
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_btn)

        self.confirm_btn = QtWidgets.QPushButton(action_text)
        self.confirm_btn.setStyleSheet("""
            QPushButton {
                background-color: #000;
                border: 1px solid #000;
                color: white;
            }
            QPushButton:hover {
                background-color: #333;
            }
        """)
        self.confirm_btn.clicked.connect(self._on_confirm)
        button_layout.addWidget(self.confirm_btn)

        layout.addLayout(button_layout)

        # Enter-Taste zum Bestätigen
        self.password_edit.returnPressed.connect(self._on_confirm)

    def _on_confirm(self):
        """Wird aufgerufen wenn der Benutzer bestätigt"""
        if not self.password_edit.text():
            self.error_label.setText("Bitte geben Sie Ihr Passwort ein.")
            self.error_label.show()
            return
        self.accept()

    def get_password(self) -> str:
        """Gibt das eingegebene Passwort zurück"""
        return self.password_edit.text()

    def show_error(self, message: str):
        """Zeigt eine Fehlermeldung an"""
        self.error_label.setText(message)
        self.error_label.show()
        self.password_edit.clear()
        self.password_edit.setFocus()
