# edited by glg
# upgraded: inherit base class

import re

from pypos.core.base_view import BaseView
from pypos.modules.penjualan.views import index as _orig_module


def _load_orig_module():
    if not hasattr(_orig_module, "TransaksiPenjualanView"):
        raise ImportError(
            "Modul pypos.modules.penjualan.views.index tidak memiliki TransaksiPenjualanView"
        )
    return _orig_module


_orig_module = _load_orig_module()

# Ekspor semua simbol asli agar kompatibel
for _name in dir(_orig_module):
    if _name.startswith("__"):
        continue
    globals()[_name] = getattr(_orig_module, _name)


class TransaksiPenjualanView(BaseView, _orig_module.TransaksiPenjualanView):
    """Wrapper agar view mewarisi BaseView tanpa mengubah logika asli."""

    def showEvent(self, event):
        from pypos.core.utils.window_size_helper import set_window_size_by_screen

        set_window_size_by_screen(self)
        super().showEvent(event)

    def __init__(self, controller, user_info, db_path, parent_window=None):
        BaseView.__init__(self, controller, user_info, db_path, parent_window)

    # edited by glg
    def _log_quick_sync_event(self, event_name, **context):
        event = str(event_name or "").strip() or "unknown"
        detail = " ".join(
            [f"{str(k)}={str(v)}" for k, v in (context or {}).items() if str(k).strip()]
        ).strip()
        if detail:
            self.log_info(f"[QuickSyncHarga] event={event} {detail}")
            return
        self.log_info(f"[QuickSyncHarga] event={event}")

    # upgraded: fallback buka modal settlement agar selalu berfungsi setelah refactor
    def buka_modal_settlement(self):
        """
        Override untuk memastikan dialog settlement dapat dibuka walau modul asli terkompilasi.
        """
        try:
            if self.parent_window and hasattr(self.parent_window, "buka_page_settlement"):
                self.parent_window.buka_page_settlement()
                return
            if hasattr(self.controller, "open_settlement_dialog_from_view"):
                self.controller.open_settlement_dialog_from_view(parent_window=self)
                return
            self.log_warning("[Settlement] Controller belum menyediakan open_settlement_dialog_from_view")
        except Exception as exc:  # pragma: no cover
            self.log_error(f"[Settlement] Gagal membuka dialog: {exc}")

    # -------------------------------------------------------------------------
    # Helper UI Methods (Best Practice)
    # -------------------------------------------------------------------------
    def show_error(self, message):
        super().show_error(message, title="Error")

    def show_warning(self, title, message):
        # edited by glg
        # Popup khusus untuk kasus harga belum diatur agar kasir mendapat aksi cepat.
        if self._is_missing_harga_warning(title, message):
            self._show_missing_harga_warning_with_sync_action(title, message)
            return
        super().show_warning(title, message)

    def show_info(self, title, message):
        super().show_info(title, message)

    def show_confirmation(self, title, message):
        from PySide6.QtWidgets import QMessageBox

        reply = QMessageBox.question(self, title, message, QMessageBox.Yes | QMessageBox.No)
        return reply == QMessageBox.Yes

    # edited by glg
    def _is_missing_harga_warning(self, title, message):
        payload = f"{title}\n{message}".lower()
        return (
            "harga barang belum diatur" in payload
            or "harganya belum diatur" in payload
            or "belum memiliki harga jual aktif" in payload
        )

    # edited by glg
    def _show_missing_harga_warning_with_sync_action(self, title, message):
        from PySide6.QtCore import Qt
        from PySide6.QtWidgets import QLabel, QMessageBox, QSizePolicy
        from pypos.core.utils.ui_message_utils import sanitize_ui_message

        safe_title = str(title or "Harga Barang Belum Diatur")
        safe_message, sanitized = sanitize_ui_message("warning", message)
        if sanitized:
            self.log_warning(f"UI message sanitized in {self.__class__.__name__}: {message}")
        context = self._extract_missing_harga_context(safe_message)
        self._log_quick_sync_event(
            "dialog_opened",
            title=safe_title,
            retry_lookup=context.get("lookup") or "-",
            barcode_only=1 if bool(context.get("barcode_only", True)) else 0,
        )

        box = QMessageBox(self)
        box.setIcon(QMessageBox.Warning)
        box.setWindowTitle(safe_title)
        box.setText(str(safe_message or "Harga barang belum diatur."))

        btn_sync = box.addButton("Sinkronisasi Lengkap", QMessageBox.AcceptRole)
        btn_close = box.addButton("Tutup", QMessageBox.RejectRole)

        # edited by glg
        # Pastikan dialog dan tombol cukup lebar agar teks tidak terpotong.
        box.setTextFormat(Qt.PlainText)
        label = box.findChild(QLabel, "qt_msgbox_label")
        if label:
            label.setWordWrap(True)
            label.setMinimumWidth(560)
        for button, min_width in (
            (btn_sync, 240),
            (btn_close, 120),
        ):
            button.setMinimumWidth(min_width)
            button.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        box.setMinimumWidth(860)
        box.adjustSize()

        box.setDefaultButton(btn_sync)
        box.exec()

        if box.clickedButton() == btn_sync:
            self._log_quick_sync_event("dialog_click_full_sync")
            if self._confirm_open_full_sync():
                self._open_sinkronisasi_page()
            else:
                self._log_quick_sync_event("dialog_cancel_full_sync")
            return
        if box.clickedButton() == btn_close:
            self._log_quick_sync_event("dialog_click_close")
            return

    # edited by glg
    def _extract_missing_harga_context(self, message):
        text = str(message or "")
        barcode_match = re.search(r"barcode:\s*([^\)\]\s]+)", text, flags=re.IGNORECASE)
        if barcode_match:
            return {
                "lookup": str(barcode_match.group(1) or "").strip(),
                "barcode_only": True,
            }
        return {"lookup": "", "barcode_only": True}

    # edited by glg
    def _confirm_open_full_sync(self):
        from PySide6.QtWidgets import QMessageBox

        confirm = QMessageBox(self)
        confirm.setIcon(QMessageBox.Warning)
        confirm.setWindowTitle("Konfirmasi Sinkronisasi Lengkap")
        confirm.setText(
            "Anda akan menjalankan sinkronisasi lengkap.\n"
            "Proses ini lebih lama dan dapat memuat ulang data master.\n\n"
            "Lanjutkan sinkronisasi lengkap sekarang?"
        )
        confirm.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        confirm.setDefaultButton(QMessageBox.No)
        return confirm.exec() == QMessageBox.Yes

    # edited by glg
    def _is_any_sync_running(self):
        parent_window = getattr(self, "parent_window", None) or self.parent()
        dashboard_controller = getattr(parent_window, "dashboard_controller", None)
        if dashboard_controller and hasattr(dashboard_controller, "is_any_sync_running"):
            try:
                return bool(dashboard_controller.is_any_sync_running())
            except Exception as exc:
                self.log_warning(f"Gagal cek status sinkronisasi: {exc}")
        return False

    # edited by glg
    def _open_sinkronisasi_page(self):
        parent_window = getattr(self, "parent_window", None)
        if parent_window is None:
            parent_window = self.parent()
        if parent_window is None:
            return
        try:
            if hasattr(parent_window, "navigate_to_page"):
                parent_window.navigate_to_page("sinkron")
                return
            if hasattr(parent_window, "buka_menu_sinkron_data"):
                parent_window.buka_menu_sinkron_data()
                return
        except Exception as exc:
            self.log_warning(f"Gagal membuka halaman sinkronisasi: {exc}")
