import os
from qgis.PyQt.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QTabWidget, QWidget,
    QLabel, QLineEdit, QPushButton,
    QFileDialog, QMessageBox, QTableWidget, QTableWidgetItem,
    QHeaderView, QCheckBox, QColorDialog, QGroupBox, QTextEdit,
    QApplication
)
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtGui import QColor

from .kml_i18n import get_help
from .kml_to_shp import KmlToShpConverter
from .merge_tab import MergeTabWidget


class LvtKmlViewDialog(QDialog):
    def __init__(self, iface, parent=None):
        super().__init__(parent)
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        self.lang = 'vi'

        screen = QApplication.primaryScreen()
        if screen:
            sh = int(screen.availableGeometry().height() * 0.95)
        else:
            sh = 750
        self.resize(1100, sh)
        self._setup_ui()
        self._refresh_ui_text()
        self.merge_widget.ensure_initialized()

        self.btn_close.clicked.connect(self.close)

    def _setup_ui(self):
        main_layout = QVBoxLayout(self)

        top_ly = QHBoxLayout()
        self.btn_lang = QPushButton()
        self.btn_lang.setFixedWidth(100)
        self.btn_lang.clicked.connect(self._toggle_language)
        top_ly.addWidget(self.btn_lang)
        top_ly.addStretch()
        main_layout.addLayout(top_ly)

        self.tabs = QTabWidget()
        main_layout.addWidget(self.tabs)

        # Tab 0: SHP → KML (MergeTabWidget — supports single & multi-layer)
        self.merge_widget = MergeTabWidget(lang=self.lang)
        self.tabs.addTab(self.merge_widget, "SHP → KML")

        # Tab 1: KML → SHP
        self.tab_kml2shp = QWidget()
        self._setup_tab_kml2shp()
        self.tabs.addTab(self.tab_kml2shp, "KML → SHP")

        # Tab 2: Hướng dẫn
        self.tab_guide = QWidget()
        self._setup_tab_guide()
        self.tabs.addTab(self.tab_guide, "")

        # Hide preview panel when on KML→SHP or other tabs
        self.tabs.currentChanged.connect(self._on_tab_changed)

        btn_layout = QHBoxLayout()
        self.btn_close = QPushButton()
        btn_layout.addStretch()
        btn_layout.addWidget(self.btn_close)
        main_layout.addLayout(btn_layout)

    def _on_tab_changed(self, index):
        """Refresh merge preview when switching to SHP→KML tab."""
        if index == 0:
            self.merge_widget.refresh_geom_tabs()

    def _setup_tab_guide(self):
        ly = QVBoxLayout(self.tab_guide)
        self.guide = QTextEdit()
        self.guide.setReadOnly(True)
        ly.addWidget(self.guide)

    def _setup_tab_kml2shp(self):
        ly = QVBoxLayout(self.tab_kml2shp)
        self.lbl_kml_src = QLabel()
        ly.addWidget(self.lbl_kml_src)

        row_kml = QHBoxLayout()
        self.txt_kml_in = QLineEdit()
        self.btn_browse_kml = QPushButton("...")
        self.btn_browse_kml.setFixedWidth(40)
        self.btn_browse_kml.clicked.connect(self._browse_kml)
        row_kml.addWidget(self.txt_kml_in)
        row_kml.addWidget(self.btn_browse_kml)
        ly.addLayout(row_kml)

        self.lbl_crs = QLabel()
        ly.addWidget(self.lbl_crs)
        self.txt_crs = QLineEdit("EPSG:4326")
        ly.addWidget(self.txt_crs)

        # --- KML info & field selection ---
        self.gp_kml_fields = QGroupBox("Fields")
        kf_ly = QVBoxLayout(self.gp_kml_fields)

        self.lbl_kml_info = QLabel("")
        self.lbl_kml_info.setStyleSheet("color: #555; font-size: 12px;")
        self.lbl_kml_info.setWordWrap(True)
        kf_ly.addWidget(self.lbl_kml_info)

        kf_btn_ly = QHBoxLayout()
        self.btn_kml_scan = QPushButton("🔍 Scan")
        self.btn_kml_scan.setFixedWidth(100)
        self.btn_kml_scan.clicked.connect(self._scan_kml_fields)
        kf_btn_ly.addWidget(self.btn_kml_scan)
        self.btn_kml_check_all = QPushButton("✅ All")
        self.btn_kml_check_all.setFixedWidth(80)
        self.btn_kml_check_all.clicked.connect(self._kml_check_all)
        kf_btn_ly.addWidget(self.btn_kml_check_all)
        self.btn_kml_uncheck_all = QPushButton("❎ None")
        self.btn_kml_uncheck_all.setFixedWidth(80)
        self.btn_kml_uncheck_all.clicked.connect(self._kml_uncheck_all)
        kf_btn_ly.addWidget(self.btn_kml_uncheck_all)
        kf_btn_ly.addStretch()
        kf_ly.addLayout(kf_btn_ly)

        self.tbl_kml_fields = QTableWidget(0, 3)
        self.tbl_kml_fields.setHorizontalHeaderLabels(["√", "Field", "Sample"])
        self.tbl_kml_fields.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tbl_kml_fields.setMaximumHeight(200)
        kf_ly.addWidget(self.tbl_kml_fields)
        ly.addWidget(self.gp_kml_fields)

        self.btn_extract = QPushButton()
        self.btn_extract.clicked.connect(self._convert_kml)
        ly.addWidget(self.btn_extract)
        ly.addStretch()

    def _refresh_ui_text(self):
        self.setWindowTitle("LVT4U KML view")
        self.btn_lang.setText(
            "🌐 " + ("English" if self.lang == 'vi' else "Tiếng Việt"))
        is_vi = self.lang == 'vi'

        self.btn_close.setText("Đóng" if is_vi else "Close")

        self.lbl_kml_src.setText("Đường dẫn KML:" if is_vi else "KML Source:")
        self.lbl_crs.setText("Hệ tọa độ:" if is_vi else "Target CRS:")
        self.btn_extract.setText(
            "🔄 CHUYỂN ĐỔI SHP" if is_vi else "🔄 EXTRACT SHP")
        self.gp_kml_fields.setTitle(
            "Trường dữ liệu xuất" if is_vi else "Export Fields")
        self.btn_kml_scan.setText("🔍 Quét" if is_vi else "🔍 Scan")
        self.btn_kml_check_all.setText("✅ Tất cả" if is_vi else "✅ All")
        self.btn_kml_uncheck_all.setText("❎ Bỏ chọn" if is_vi else "❎ None")
        self.tbl_kml_fields.setHorizontalHeaderLabels(
            ["√", "Trường" if is_vi else "Field", "Mẫu" if is_vi else "Sample"])

        self.tabs.setTabText(0, "SHP → KML")
        self.merge_widget.update_labels(self.lang)
        self.tabs.setTabText(1, "KML → SHP")
        self.tabs.setTabText(2, "Hướng dẫn" if is_vi else "Guide")

        self.guide.setHtml(get_help(self.lang))

    def _load_current_layers(self):
        """Refresh layer list — delegates to merge_widget."""
        self.merge_widget.refresh_geom_tabs()

    def _toggle_language(self):
        self.lang = 'en' if self.lang == 'vi' else 'vi'
        self._refresh_ui_text()

    def _pick_color(self, btn):
        c = QColorDialog.getColor(QColor(btn.text()))
        if c.isValid():
            btn.setText(c.name())
            btn.setStyleSheet("background-color: {}".format(c.name()))

    # ── KML → SHP methods ──────────────────────────────

    def _browse_kml(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "Chọn File KML/KMZ", "", "KML/KMZ Files (*.kml *.kmz)")
        if file_path:
            self.txt_kml_in.setText(file_path)
            self._scan_kml_fields()

    def _scan_kml_fields(self):
        """Scan KML file and populate field selection table."""
        kml_path = self.txt_kml_in.text()
        if not kml_path or not os.path.exists(kml_path):
            self.lbl_kml_info.setText(
                "⚠ Chưa chọn file" if self.lang == 'vi' else "⚠ No file selected")
            return

        converter = KmlToShpConverter()
        result = converter.discover_fields(kml_path)
        if result is None:
            self.lbl_kml_info.setText(
                "❌ Không đọc được file" if self.lang == 'vi' else "❌ Cannot read file")
            return

        all_fields = result['fields']
        total_features = result['total_features']
        geom_types = result['geom_types']

        # Update info label
        geom_str = ", ".join(sorted(geom_types)) if geom_types else "?"
        info = ("📊 {} features | 📐 {} | "
                "📋 {} fields").format(total_features, geom_str, len(all_fields))
        if len(geom_types) > 1:
            if self.lang == 'vi':
                info += "\n💡 Multi-geometry → sẽ tách thành {} file SHP".format(len(geom_types))
            else:
                info += "\n💡 Multi-geometry → will split into {} SHP files".format(len(geom_types))
        self.lbl_kml_info.setText(info)

        # Populate field table
        self.tbl_kml_fields.setRowCount(0)
        for i, (fname, sample) in enumerate(all_fields.items()):
            self.tbl_kml_fields.insertRow(i)
            chk = QCheckBox()
            chk.setChecked(True)
            self.tbl_kml_fields.setCellWidget(i, 0, chk)
            item_name = QTableWidgetItem(fname)
            item_name.setFlags(item_name.flags() & ~Qt.ItemIsEditable)
            self.tbl_kml_fields.setItem(i, 1, item_name)
            item_sample = QTableWidgetItem(sample)
            item_sample.setFlags(item_sample.flags() & ~Qt.ItemIsEditable)
            self.tbl_kml_fields.setItem(i, 2, item_sample)

    def _kml_check_all(self):
        for i in range(self.tbl_kml_fields.rowCount()):
            chk = self.tbl_kml_fields.cellWidget(i, 0)
            if chk:
                chk.setChecked(True)

    def _kml_uncheck_all(self):
        for i in range(self.tbl_kml_fields.rowCount()):
            chk = self.tbl_kml_fields.cellWidget(i, 0)
            if chk:
                chk.setChecked(False)

    def _convert_kml(self):
        kml_path = self.txt_kml_in.text()
        if not kml_path or not os.path.exists(kml_path):
            QMessageBox.warning(
                self,
                "Lỗi" if self.lang == 'vi' else "Error",
                "Vui lòng chọn file KML!" if self.lang == 'vi' else "Please select valid KML!")
            return

        out_shp, _ = QFileDialog.getSaveFileName(
            self, "Lưu SHP" if self.lang == 'vi' else "Save SHP",
            "", "Shapefile (*.shp)")
        if not out_shp:
            return

        # Collect selected fields
        selected_fields = None  # None means all
        if self.tbl_kml_fields.rowCount() > 0:
            selected = []
            for i in range(self.tbl_kml_fields.rowCount()):
                chk = self.tbl_kml_fields.cellWidget(i, 0)
                if chk and chk.isChecked():
                    item = self.tbl_kml_fields.item(i, 1)
                    if item:
                        selected.append(item.text())
            if selected:
                selected_fields = selected

        converter = KmlToShpConverter()
        success, msg = converter.convert(
            kml_path, out_shp, self.txt_crs.text(),
            selected_fields=selected_fields)

        if success:
            QMessageBox.information(
                self,
                "✅ " + ("Thành công" if self.lang == 'vi' else "Success"),
                msg)
        else:
            QMessageBox.warning(
                self,
                "❌ " + ("Lỗi" if self.lang == 'vi' else "Error"),
                msg)
