"""
Reusable layer selection widget with checkboxes
"""

from ...qt_compat import (
    QWidget, QVBoxLayout, QLabel, QListWidget, QListWidgetItem,
    QPushButton, QHBoxLayout
)
from ...qt_compat import Qt, pyqtSignal
from typing import List, Dict, Any


class LayerSelectorWidget(QWidget):
    """
    Widget for selecting layers from QGIS map

    Signals:
        selection_changed: Emitted when layer selection changes
    """

    selection_changed = pyqtSignal(list)  # List of selected layer names

    def __init__(self, available_layers: List[str] = None, parent=None):
        """
        Initialize layer selector

        Args:
            available_layers: List of available layer names
            parent: Parent widget
        """
        super().__init__(parent)
        self.available_layers = available_layers or []
        self.layer_data: Dict[str, Any] = {}  # Store layer metadata
        self.init_ui()

    def init_ui(self):
        """Initialize UI"""
        layout = QVBoxLayout()

        # Label
        layout.addWidget(QLabel("Select Input Layers:"))

        # List widget
        self.list_widget = QListWidget()
        self._populate_layers()
        self.list_widget.itemChanged.connect(self._on_selection_changed)
        layout.addWidget(self.list_widget)

        # Selection buttons
        button_layout = QHBoxLayout()

        self.btn_select_all = QPushButton("Select All")
        self.btn_select_all.clicked.connect(self.select_all)
        button_layout.addWidget(self.btn_select_all)

        self.btn_deselect_all = QPushButton("Deselect All")
        self.btn_deselect_all.clicked.connect(self.deselect_all)
        button_layout.addWidget(self.btn_deselect_all)

        button_layout.addStretch()
        layout.addLayout(button_layout)

        self.setLayout(layout)

    def _populate_layers(self):
        """Populate list widget with available layers"""
        self.list_widget.blockSignals(True)
        self.list_widget.clear()

        for layer_name in self.available_layers:
            item = QListWidgetItem(layer_name)
            item.setCheckState(Qt.CheckState.Checked)
            self.list_widget.addItem(item)

        self.list_widget.blockSignals(False)

    def _on_selection_changed(self):
        """Handle selection change"""
        self.selection_changed.emit(self.get_selected_layers())

    def get_selected_layers(self) -> List[str]:
        """
        Get list of selected layer names

        Returns:
            List of selected layer names
        """
        selected = []
        for i in range(self.list_widget.count()):
            item = self.list_widget.item(i)
            if item.checkState() == Qt.CheckState.Checked:
                selected.append(item.text())
        return selected

    def set_layers(self, layers: List[str], select_all: bool = True):
        """
        Set available layers

        Args:
            layers: List of layer names
            select_all: Whether to check all layers by default
        """
        self.available_layers = layers
        self.list_widget.blockSignals(True)
        self.list_widget.clear()

        for layer_name in self.available_layers:
            item = QListWidgetItem(layer_name)
            if select_all:
                item.setCheckState(Qt.CheckState.Checked)
            else:
                item.setCheckState(Qt.CheckState.Unchecked)
            self.list_widget.addItem(item)

        self.list_widget.blockSignals(False)

    def select_all(self):
        """Select all layers"""
        self.list_widget.blockSignals(True)
        for i in range(self.list_widget.count()):
            item = self.list_widget.item(i)
            item.setCheckState(Qt.CheckState.Checked)
        self.list_widget.blockSignals(False)
        self._on_selection_changed()

    def deselect_all(self):
        """Deselect all layers"""
        self.list_widget.blockSignals(True)
        for i in range(self.list_widget.count()):
            item = self.list_widget.item(i)
            item.setCheckState(Qt.CheckState.Unchecked)
        self.list_widget.blockSignals(False)
        self._on_selection_changed()

    def is_valid(self) -> bool:
        """Check if at least one layer is selected"""
        return len(self.get_selected_layers()) > 0
