"""
dance_picker_dialog.py — Dialog til at vælge dans og koreograf med autoudfyld.
"""

from PyQt6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit,
    QPushButton, QListWidget, QListWidgetItem,
)
from PyQt6.QtCore import Qt, QTimer


class DancePickerDialog(QDialog):
    def __init__(self, current_dance: str = "", current_choreo: str = "",
                 song_title: str = "", parent=None):
        super().__init__(parent)
        self._chosen_dance  = current_dance
        self._chosen_choreo = current_choreo
        self.setWindowTitle("Vælg dans")
        self.setMinimumWidth(400)
        self.setFixedWidth(440)
        self._build_ui(current_dance, current_choreo, song_title)
        self._load_dance_suggestions("")

    def _build_ui(self, current_dance: str, current_choreo: str, song_title: str):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(12, 12, 12, 12)
        layout.setSpacing(8)

        if song_title:
            lbl = QLabel(song_title)
            lbl.setObjectName("track_title")
            lbl.setWordWrap(True)
            layout.addWidget(lbl)

        # ── Dans ──────────────────────────────────────────────────────────────
        lbl2 = QLabel("Dans:")
        lbl2.setObjectName("track_meta")
        layout.addWidget(lbl2)

        self._edit_dance = QLineEdit()
        self._edit_dance.setText(current_dance)
        self._edit_dance.setPlaceholderText("Skriv dans-navn...")
        self._edit_dance.selectAll()
        self._edit_dance.textChanged.connect(self._on_dance_text_changed)
        self._edit_dance.returnPressed.connect(lambda: self._edit_choreo.setFocus())
        layout.addWidget(self._edit_dance)

        self._dance_list = QListWidget()
        self._dance_list.setMaximumHeight(160)
        self._dance_list.itemDoubleClicked.connect(self._on_dance_selected)
        self._dance_list.itemClicked.connect(
            lambda item: self._edit_dance.setText(
                item.data(Qt.ItemDataRole.UserRole) or item.text().split(" / ")[0]
            )
        )
        layout.addWidget(self._dance_list)

        # ── Koreograf ─────────────────────────────────────────────────────────
        lbl3 = QLabel("Koreograf (valgfri):")
        lbl3.setObjectName("track_meta")
        layout.addWidget(lbl3)

        self._edit_choreo = QLineEdit()
        self._edit_choreo.setText(current_choreo)
        self._edit_choreo.setPlaceholderText("Koreografens navn...")
        self._edit_choreo.textChanged.connect(self._on_choreo_text_changed)
        self._edit_choreo.returnPressed.connect(self._on_accept)
        layout.addWidget(self._edit_choreo)

        self._choreo_list = QListWidget()
        self._choreo_list.setMaximumHeight(100)
        self._choreo_list.itemDoubleClicked.connect(self._on_choreo_selected)
        self._choreo_list.itemClicked.connect(
            lambda item: self._edit_choreo.setText(item.text())
        )
        layout.addWidget(self._choreo_list)

        # ── Debounce timere ───────────────────────────────────────────────────
        self._dance_timer = QTimer(self)
        self._dance_timer.setSingleShot(True)
        self._dance_timer.setInterval(200)
        self._dance_timer.timeout.connect(
            lambda: self._load_dance_suggestions(self._edit_dance.text().strip())
        )

        self._choreo_timer = QTimer(self)
        self._choreo_timer.setSingleShot(True)
        self._choreo_timer.setInterval(200)
        self._choreo_timer.timeout.connect(
            lambda: self._load_choreo_suggestions(self._edit_choreo.text().strip())
        )

        # ── Knapper ───────────────────────────────────────────────────────────
        btn_row = QHBoxLayout()
        btn_row.addStretch()
        btn_cancel = QPushButton("Annuller")
        btn_cancel.clicked.connect(self.reject)
        btn_row.addWidget(btn_cancel)
        btn_ok = QPushButton("✓  Vælg")
        btn_ok.setObjectName("btn_play")
        btn_ok.clicked.connect(self._on_accept)
        btn_row.addWidget(btn_ok)
        layout.addLayout(btn_row)

        self._edit_dance.setFocus()

    def _on_dance_text_changed(self):
        self._dance_timer.start()

    def _on_choreo_text_changed(self):
        self._choreo_timer.start()

    def _load_dance_suggestions(self, prefix: str):
        try:
            from local.local_db import get_dance_suggestions
            suggestions = get_dance_suggestions(prefix or "", limit=20)
            self._dance_list.clear()
            for s in suggestions:
                label = f"{s['name']} / {s['level_name']}" if s.get("level_name") else s["name"]
                if s.get("choreographer"):
                    label += f"  ({s['choreographer']})"
                item = QListWidgetItem(label)
                item.setData(Qt.ItemDataRole.UserRole, s["name"])
                item.setData(Qt.ItemDataRole.UserRole + 1, s.get("choreographer", ""))
                self._dance_list.addItem(item)
        except Exception:
            pass

    def _load_choreo_suggestions(self, prefix: str):
        try:
            from local.local_db import get_choreographer_suggestions
            suggestions = get_choreographer_suggestions(prefix or "", limit=15)
            self._choreo_list.clear()
            for name in suggestions:
                self._choreo_list.addItem(QListWidgetItem(name))
        except Exception:
            pass

    def _on_dance_selected(self, item: QListWidgetItem):
        name   = item.data(Qt.ItemDataRole.UserRole) or item.text().split(" / ")[0]
        choreo = item.data(Qt.ItemDataRole.UserRole + 1) or ""
        self._edit_dance.setText(name)
        if choreo and not self._edit_choreo.text().strip():
            self._edit_choreo.setText(choreo)
        self._chosen_dance  = name
        self._chosen_choreo = self._edit_choreo.text().strip()
        self.accept()

    def _on_choreo_selected(self, item: QListWidgetItem):
        self._edit_choreo.setText(item.text())
        self._choreo_list.clear()

    def _on_accept(self):
        self._chosen_dance  = self._edit_dance.text().strip()
        self._chosen_choreo = self._edit_choreo.text().strip()
        if self._chosen_dance:
            self.accept()

    def get_dance(self) -> str:
        return self._chosen_dance

    def get_choreo(self) -> str:
        return self._chosen_choreo
