import os

from qgis.PyQt.QtWidgets import QAction, QMessageBox
import webbrowser
from qgis.PyQt.QtGui import QIcon
from qgis.core import QgsProject

from .smart_geometry_splitter_dialog import SmartGeometrySplitterDialog


class SmartGeometrySplitter:
    def __init__(self, iface):
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        self.action = None
        self.feedback_action = None
        self.clear_segments_action = None
        self.clear_vertices_action = None
        self.clear_all_outputs_action = None
        self.dialog = None

    def initGui(self):
        icon_path = os.path.join(self.plugin_dir, "icon.png")

        if os.path.exists(icon_path):
            icon = QIcon(icon_path)
        else:
            icon = QIcon()

        self.action = QAction(
            icon,
            "Smart Geometry Splitter",
            self.iface.mainWindow()
        )

        self.action.setObjectName("SmartGeometrySplitterAction")
        self.action.setToolTip("Smart Geometry Splitter")
        self.action.setStatusTip(
            "Split polygons and lines directly in the active editable layer"
        )

        self.action.triggered.connect(self.run)

        self.feedback_action = QAction(
            icon,
            "Feedback / Report bug / Feature request",
            self.iface.mainWindow()
        )
        self.feedback_action.triggered.connect(self.open_feedback)

        self.clear_segments_action = QAction(icon, "Clear Segment Labels", self.iface.mainWindow())
        self.clear_segments_action.triggered.connect(self.clear_segment_labels)

        self.clear_vertices_action = QAction(icon, "Clear Vertex Numbers", self.iface.mainWindow())
        self.clear_vertices_action.triggered.connect(self.clear_vertex_numbers)

        self.clear_all_outputs_action = QAction(icon, "Clear All SGS Outputs", self.iface.mainWindow())
        self.clear_all_outputs_action.triggered.connect(self.clear_all_outputs)

        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(
            "&Smart Geometry Splitter",
            self.action
        )
        self.iface.addPluginToMenu(
            "&Smart Geometry Splitter",
            self.feedback_action
        )
        self.iface.addPluginToMenu("&Smart Geometry Splitter", self.clear_segments_action)
        self.iface.addPluginToMenu("&Smart Geometry Splitter", self.clear_vertices_action)
        self.iface.addPluginToMenu("&Smart Geometry Splitter", self.clear_all_outputs_action)

    def unload(self):
        if self.action:
            self.iface.removeToolBarIcon(self.action)
            self.iface.removePluginMenu(
                "&Smart Geometry Splitter",
                self.action
            )
        if self.feedback_action:
            self.iface.removePluginMenu(
                "&Smart Geometry Splitter",
                self.feedback_action
            )
        if self.clear_segments_action:
            self.iface.removePluginMenu("&Smart Geometry Splitter", self.clear_segments_action)
        if self.clear_vertices_action:
            self.iface.removePluginMenu("&Smart Geometry Splitter", self.clear_vertices_action)
        if self.clear_all_outputs_action:
            self.iface.removePluginMenu("&Smart Geometry Splitter", self.clear_all_outputs_action)

    def run(self):
        if self.dialog is None:
            self.dialog = SmartGeometrySplitterDialog(self.iface)

        self.dialog.show()
        self.dialog.raise_()
        self.dialog.activateWindow()
    def open_feedback(self):
        webbrowser.open("https://forms.gle/aqABvAe3QD46Ce3W9")


    def _remove_layers_by_name(self, layer_names):
        project = QgsProject.instance()
        removed = []
        for layer in list(project.mapLayers().values()):
            if layer.name() in layer_names:
                removed.append(layer.name())
                project.removeMapLayer(layer.id())
        return removed

    def _show_cleanup_message(self, removed, target_label):
        if removed:
            unique = []
            for name in removed:
                if name not in unique:
                    unique.append(name)
            QMessageBox.information(
                self.iface.mainWindow(),
                "Smart Geometry Splitter",
                "Removed SGS output layer(s):\n\n" + "\n".join(f"✓ {name}" for name in unique)
            )
        else:
            QMessageBox.information(
                self.iface.mainWindow(),
                "Smart Geometry Splitter",
                f"Nothing to remove for: {target_label}"
            )

    def clear_segment_labels(self):
        removed = self._remove_layers_by_name(["SGS Segment Lengths"])
        self._show_cleanup_message(removed, "Segment labels")

    def clear_vertex_numbers(self):
        removed = self._remove_layers_by_name(["SGS Vertex Numbers"])
        self._show_cleanup_message(removed, "Vertex numbers")

    def clear_all_outputs(self):
        removed = self._remove_layers_by_name(["SGS Segment Lengths", "SGS Vertex Numbers"])
        self._show_cleanup_message(removed, "All SGS outputs")
