"""
register_dialog.py — Opret ny konto på LineDance API.
"""
from PyQt6.QtWidgets import (
    QDialog, QVBoxLayout, QFormLayout, QLabel, QLineEdit,
    QPushButton, QGroupBox, QMessageBox,
)
from PyQt6.QtCore import Qt


class RegisterDialog(QDialog):
    def __init__(self, server_url: str = "http://localhost:8000", parent=None):
        super().__init__(parent)
        self._server_url = server_url.rstrip("/")
        self.setWindowTitle("Opret konto")
        self.setMinimumWidth(400)
        self._build_ui()

    def _build_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(16, 16, 16, 16)
        layout.setSpacing(12)

        lbl = QLabel(f"Opret konto på:\n{self._server_url}")
        lbl.setObjectName("result_count")
        lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(lbl)

        grp = QGroupBox("Kontooplysninger")
        form = QFormLayout(grp)

        self._name = QLineEdit()
        self._name.setPlaceholderText("Dit fulde navn")
        form.addRow("Navn:", self._name)

        self._username = QLineEdit()
        self._username.setPlaceholderText("brugernavn (ingen mellemrum)")
        form.addRow("Brugernavn:", self._username)

        self._email = QLineEdit()
        self._email.setPlaceholderText("din@email.dk")
        form.addRow("E-mail:", self._email)

        self._password = QLineEdit()
        self._password.setEchoMode(QLineEdit.EchoMode.Password)
        self._password.setPlaceholderText("mindst 8 tegn")
        form.addRow("Kodeord:", self._password)

        self._password2 = QLineEdit()
        self._password2.setEchoMode(QLineEdit.EchoMode.Password)
        self._password2.setPlaceholderText("gentag kodeord")
        form.addRow("Gentag kodeord:", self._password2)

        layout.addWidget(grp)

        self._status = QLabel("")
        self._status.setObjectName("result_count")
        self._status.setWordWrap(True)
        self._status.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self._status)

        btn_row = QVBoxLayout()
        self._btn_register = QPushButton("✚  Opret konto")
        self._btn_register.setObjectName("btn_play")
        self._btn_register.clicked.connect(self._register)
        btn_row.addWidget(self._btn_register)

        btn_cancel = QPushButton("Annuller")
        btn_cancel.clicked.connect(self.reject)
        btn_row.addWidget(btn_cancel)
        layout.addLayout(btn_row)

    def _register(self):
        name      = self._name.text().strip()
        username  = self._username.text().strip()
        email     = self._email.text().strip()
        password  = self._password.text()
        password2 = self._password2.text()

        # Validering
        if not all([username, email, password]):
            self._status.setText("⚠ Udfyld alle felter.")
            return
        if " " in username:
            self._status.setText("⚠ Brugernavnet må ikke indeholde mellemrum.")
            return
        if "@" not in email:
            self._status.setText("⚠ Ugyldig e-mailadresse.")
            return
        if len(password) < 8:
            self._status.setText("⚠ Kodeordet skal være mindst 8 tegn.")
            return
        if password != password2:
            self._status.setText("⚠ Kodeordene er ikke ens.")
            return

        self._btn_register.setEnabled(False)
        self._status.setText("Opretter konto...")

        try:
            import urllib.request, json
            data = json.dumps({
                "username":  username,
                "email":     email,
                "full_name": name,
                "password":  password,
            }).encode("utf-8")
            req = urllib.request.Request(
                f"{self._server_url}/auth/register",
                data=data,
                headers={"Content-Type": "application/json"},
                method="POST"
            )
            with urllib.request.urlopen(req, timeout=10) as resp:
                result = json.loads(resp.read())

            self._status.setText(
                f"✓ Konto oprettet!\n\n"
                f"Tjek din e-mail ({email}) for at bekræfte kontoen.\n"
                f"Herefter kan du logge ind."
            )
            self._btn_register.setEnabled(False)

        except urllib.error.HTTPError as e:
            body = json.loads(e.read())
            msg = body.get("detail", str(e))
            self._status.setText(f"⚠ {msg}")
            self._btn_register.setEnabled(True)
        except Exception as e:
            self._status.setText(f"⚠ Kunne ikke forbinde til server:\n{e}")
            self._btn_register.setEnabled(True)
