# -*- coding: utf-8 -*-
"""
Dialog to delete a network from the network-store with project-aware helpers.
"""

import os

from qgis.PyQt import uic, QtWidgets
from qgis.PyQt.QtWidgets import QDialogButtonBox, QMessageBox
from qgis.core import QgsProject, QgsApplication, QgsAuthMethodConfig

from .network_store_core import delete_network_in_store
from .network_store_settings import NetworkStoreSettingsStore

FORM_CLASS_NS_DELETE, _ = uic.loadUiType(
    os.path.join(os.path.dirname(__file__), "network_store_dialog_delete.ui")
)


class NetworkStorePluginDialogDelete(QtWidgets.QDialog, FORM_CLASS_NS_DELETE):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)

        try:
            self.button_box.accepted.disconnect()
        except Exception:
            pass
        self.button_box.accepted.connect(self._on_delete_clicked)
        self.button_box.rejected.connect(self.reject)

        ok_btn = self.button_box.button(QDialogButtonBox.Ok)
        if ok_btn is not None:
            ok_btn.setText(self.tr("Delete"))

        self.comboConfig.currentIndexChanged.connect(self._apply_selected_config)
        self.comboNetworkId.currentIndexChanged.connect(self._on_network_combo_changed)

        self._project_networks: list[dict[str, str]] = []
        self._reload_configs()
        self._refresh_project_networks()

    def _resolve_credentials_from_authcfg(
        self, authcfg: str | None
    ) -> tuple[str | None, str | None]:
        if not authcfg:
            return None, None
        try:
            cfg = QgsAuthMethodConfig()
            if QgsApplication.authManager().loadAuthenticationConfig(
                authcfg, cfg, True
            ):
                return cfg.config("username") or None, cfg.config("password") or None
        except Exception:
            pass
        return None, None

    def _reload_configs(self) -> None:
        store = NetworkStoreSettingsStore()
        configs = store.list()
        self.comboConfig.blockSignals(True)
        self.comboConfig.clear()
        for cfg in configs:
            label = f"{cfg.name} ({cfg.base_url})"
            self.comboConfig.addItem(label, cfg)
        self.comboConfig.blockSignals(False)
        if self.comboConfig.count() > 0:
            self.comboConfig.setCurrentIndex(0)
            self._apply_selected_config()

    def _apply_selected_config(self) -> None:
        idx = self.comboConfig.currentIndex()
        cfg = self.comboConfig.itemData(idx)
        if not cfg:
            return
        self.mLineEdit_baseURL.setText(str(cfg.base_url or "").strip())

    def _refresh_project_networks(self) -> None:
        self._project_networks = []
        prj = QgsProject.instance()
        seen = set()
        for lyr in prj.mapLayers().values():
            nid = str(lyr.customProperty("network:id", "")).strip()
            base = str(lyr.customProperty("network:base_url", "")).strip().rstrip("/")
            if not nid or nid in seen:
                continue
            seen.add(nid)
            self._project_networks.append({"network_id": nid, "base_url": base})

        self.comboNetworkId.blockSignals(True)
        self.comboNetworkId.clear()
        for item in self._project_networks:
            label = f"{item['network_id']} ({item['base_url'] or 'unknown'})"
            self.comboNetworkId.addItem(label, item)
        self.comboNetworkId.blockSignals(False)
        self._on_network_combo_changed(self.comboNetworkId.currentIndex())

    def _on_network_combo_changed(self, idx: int) -> None:
        data = self.comboNetworkId.itemData(idx)
        # Enable removal from project only when selection is from the dropdown
        self.chkRemoveFromProject.setEnabled(bool(data))

    def _show_error(self, title: str, msg: str) -> None:
        QMessageBox.critical(self, title, msg)

    def _on_delete_clicked(self) -> None:
        base_url = (self.mLineEdit_baseURL.text() or "").strip().rstrip("/")
        network_id = (self.comboNetworkId.currentText() or "").strip()

        if not base_url or not network_id:
            self._show_error(
                self.tr("Missing information"),
                self.tr("Base URL and network ID are required."),
            )
            return

        data = self.comboNetworkId.currentData()
        if data:
            proj_base = str(data.get("base_url") or "").strip().rstrip("/")
            if proj_base and base_url and proj_base != base_url:
                self._show_error(
                    self.tr("Base URL mismatch"),
                    self.tr(
                        f"Selected network comes from '{proj_base}', but base URL is '{base_url}'."
                    ),
                )
                return

        remove_from_project = bool(
            data is not None and self.chkRemoveFromProject.isChecked()
        )

        ok = delete_network_in_store(
            base_url,
            network_id,
            delete_elements=True,
            unload_network=remove_from_project,
            feedback=None,
        )
        if ok:
            self.accept()
