"""
share_dialog.py — Forenklet del-dialog.
Kun ejer kan dele. Delte brugere får listen ved næste sync.
"""
from PyQt6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit,
    QPushButton, QComboBox, QFrame, QListWidget, QListWidgetItem,
    QMessageBox,
)
from PyQt6.QtCore import Qt


class ShareDialog(QDialog):
    def __init__(self, playlist_id: str, playlist_name: str,
                 server_url: str, token: str, parent=None):
        super().__init__(parent)
        self._playlist_id   = playlist_id
        self._playlist_name = playlist_name
        self._server_url    = server_url.rstrip("/")
        self._token         = token

        self.setWindowTitle(f"Del — {playlist_name}")
        self.setMinimumWidth(440)
        self._build_ui()
        self._load_shares()
        self._load_visibility()

    def _headers(self):
        return {
            "Content-Type":  "application/json",
            "Authorization": f"Bearer {self._token}",
        }

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

        # Synlighed
        vis_frame = QFrame()
        vis_frame.setObjectName("track_display")
        vis_layout = QHBoxLayout(vis_frame)
        vis_layout.setContentsMargins(10, 8, 10, 8)
        vis_layout.addWidget(QLabel("Synlighed:"))
        self._vis_combo = QComboBox()
        self._vis_combo.addItem("Privat — kun dig",         "private")
        self._vis_combo.addItem("Delt — kun inviterede",    "shared")
        self._vis_combo.addItem("Public — hjemmesiden",     "public")
        vis_layout.addWidget(self._vis_combo, stretch=1)
        btn_vis = QPushButton("Gem")
        btn_vis.setFixedHeight(28)
        btn_vis.clicked.connect(self._set_visibility)
        vis_layout.addWidget(btn_vis)
        layout.addWidget(vis_frame)

        # Del med bruger
        inv_frame = QFrame()
        inv_frame.setObjectName("track_display")
        inv_layout = QVBoxLayout(inv_frame)
        inv_layout.setContentsMargins(10, 8, 10, 8)
        inv_layout.setSpacing(6)
        inv_layout.addWidget(QLabel("Del med (e-mail):"))
        row = QHBoxLayout()
        self._email_input = QLineEdit()
        self._email_input.setPlaceholderText("bruger@eksempel.dk")
        row.addWidget(self._email_input)
        btn_inv = QPushButton("Del")
        btn_inv.setFixedHeight(28)
        btn_inv.clicked.connect(self._invite)
        row.addWidget(btn_inv)
        inv_layout.addLayout(row)
        note = QLabel("Brugeren får listen ved næste synkronisering.\nKun du kan redigere listen.")
        note.setObjectName("result_count")
        note.setWordWrap(True)
        inv_layout.addWidget(note)
        layout.addWidget(inv_frame)

        # Liste
        lbl = QLabel("Delt med:")
        lbl.setObjectName("track_meta")
        layout.addWidget(lbl)
        self._shares_list = QListWidget()
        self._shares_list.setMaximumHeight(120)
        layout.addWidget(self._shares_list)

        btn_remove = QPushButton("✕  Fjern valgt deling")
        btn_remove.clicked.connect(self._remove_share)
        layout.addWidget(btn_remove)

        self._status = QLabel("")
        self._status.setObjectName("result_count")
        self._status.setWordWrap(True)
        layout.addWidget(self._status)

        btn_close = QPushButton("Luk")
        btn_close.clicked.connect(self.accept)
        layout.addWidget(btn_close)

    def _load_visibility(self):
        try:
            import urllib.request, json
            req = urllib.request.Request(
                f"{self._server_url}/sharing/playlists/{self._playlist_id}",
                headers=self._headers()
            )
            with urllib.request.urlopen(req, timeout=8) as resp:
                data = json.loads(resp.read())
            vis = data.get("visibility", "private")
            for i in range(self._vis_combo.count()):
                if self._vis_combo.itemData(i) == vis:
                    self._vis_combo.setCurrentIndex(i)
                    break
        except Exception:
            pass

    def _set_visibility(self):
        vis = self._vis_combo.currentData()
        try:
            import urllib.request, json
            req = urllib.request.Request(
                f"{self._server_url}/sharing/playlists/{self._playlist_id}/visibility?visibility={vis}",
                data=b"", headers=self._headers(), method="PATCH"
            )
            urllib.request.urlopen(req, timeout=8)
            self._status.setText(f"✓ Synlighed gemt")
        except Exception as e:
            self._status.setText(f"⚠ {e}")

    def _load_shares(self):
        try:
            import urllib.request, json
            req = urllib.request.Request(
                f"{self._server_url}/sharing/playlists/{self._playlist_id}/shares",
                headers=self._headers()
            )
            with urllib.request.urlopen(req, timeout=8) as resp:
                shares = json.loads(resp.read())
            self._shares_list.clear()
            for s in shares:
                item = QListWidgetItem(s["email"])
                item.setData(Qt.ItemDataRole.UserRole, s["id"])
                self._shares_list.addItem(item)
        except Exception as e:
            self._status.setText(f"Kunne ikke hente delinger: {e}")

    def _invite(self):
        email = self._email_input.text().strip()
        if not email or "@" not in email:
            self._status.setText("⚠ Ugyldig e-mailadresse")
            return
        try:
            import urllib.request, json
            data = json.dumps({"email": email}).encode()
            req  = urllib.request.Request(
                f"{self._server_url}/sharing/playlists/{self._playlist_id}/share",
                data=data, headers=self._headers(), method="POST"
            )
            urllib.request.urlopen(req, timeout=8)
            self._email_input.clear()
            self._status.setText(f"✓ Delt med {email}")
            self._load_shares()
        except Exception as e:
            self._status.setText(f"⚠ {e}")

    def _remove_share(self):
        item = self._shares_list.currentItem()
        if not item:
            return
        share_id = item.data(Qt.ItemDataRole.UserRole)
        try:
            import urllib.request
            req = urllib.request.Request(
                f"{self._server_url}/sharing/playlists/{self._playlist_id}/share/{share_id}",
                headers=self._headers(), method="DELETE"
            )
            urllib.request.urlopen(req, timeout=8)
            self._status.setText("✓ Deling fjernet")
            self._load_shares()
        except Exception as e:
            self._status.setText(f"⚠ {e}")
