import logging
import os
import sys

from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import (
    QDialog,
    QFormLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QVBoxLayout,
    QWidget,
)

from pypos.core.base_view import BaseView
from pypos.core.utils.ui_scale_runtime import scale_ui_px
from pypos.modules.auth.controllers.config_dialog_controller import ConfigDialogController


LOGGER = logging.getLogger(__name__)


class ConfigDialog(BaseView, QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Konfigurasi Aplikasi")
        self.controller = ConfigDialogController(self)
        # edited by glg
        # Dialog konfigurasi perlu area lebih lebar agar input URL panjang
        # tidak terpotong saat pertama kali dibuka.
        self._configure_dialog_size()

        root_layout = QVBoxLayout(self)
        root_layout.setContentsMargins(
            scale_ui_px(14),
            scale_ui_px(12),
            scale_ui_px(14),
            scale_ui_px(12),
        )
        root_layout.setSpacing(scale_ui_px(8))

        title_label = QLabel("Pengaturan Koneksi Aplikasi")
        title_label.setProperty("class", "config-dialog-title")
        root_layout.addWidget(title_label)

        helper_label = QLabel(
            "Perubahan API Base URL akan meminta restart aplikasi agar koneksi baru aktif."
        )
        helper_label.setWordWrap(True)
        helper_label.setProperty("class", "config-dialog-helper")
        root_layout.addWidget(helper_label)

        form_container = QWidget()
        layout = QFormLayout(form_container)
        layout.setHorizontalSpacing(scale_ui_px(12))
        layout.setVerticalSpacing(scale_ui_px(8))
        form_data = self.controller.load_form_data()

        self.api_url_input = QLineEdit()
        self.api_url_input.setPlaceholderText("https://contoh-domain/api")
        self.api_url_input.setText(form_data.get("api_base_url", ""))
        self.api_url_input.setMinimumWidth(scale_ui_px(520))
        layout.addRow("API Base URL", self.api_url_input)

        self.client_name_input = QLineEdit()
        self.client_name_input.setPlaceholderText("Nama client atau nama toko")
        self.client_name_input.setText(form_data.get("client_name", ""))
        layout.addRow("Client Name", self.client_name_input)

        self.timeout_input = QLineEdit()
        self.timeout_input.setPlaceholderText("3")
        self.timeout_input.setText(str(form_data.get("request_timeout", 3)))
        layout.addRow("Request Timeout", self.timeout_input)

        root_layout.addWidget(form_container, 1)

        button_row = QHBoxLayout()
        button_row.addStretch(1)
        btn_cancel = QPushButton("Batal")
        btn_cancel.clicked.connect(self.reject)
        btn_save = QPushButton("Simpan")
        btn_save.clicked.connect(self.save)
        button_row.addWidget(btn_cancel)
        button_row.addWidget(btn_save)
        root_layout.addLayout(button_row)

    # edited by glg
    def _configure_dialog_size(self):
        base_width = scale_ui_px(900)
        base_height = scale_ui_px(520)
        min_width = scale_ui_px(760)
        min_height = scale_ui_px(380)
        screen = QGuiApplication.primaryScreen()
        if screen is not None:
            available = screen.availableGeometry()
            # Sisakan margin agar dialog tidak menabrak batas layar kecil.
            max_width = max(scale_ui_px(640), int(available.width() * 0.92))
            max_height = max(scale_ui_px(360), int(available.height() * 0.88))
            base_width = min(base_width, max_width)
            base_height = min(base_height, max_height)
            min_width = min(min_width, max_width)
            min_height = min(min_height, max_height)
        self.setMinimumSize(min_width, min_height)
        self.resize(base_width, base_height)
        if hasattr(self, "setSizeGripEnabled"):
            self.setSizeGripEnabled(True)

    def save(self):
        ok, message, restart_required = self.controller.save_form_data(
            api_base_url=self.api_url_input.text().strip(),
            client_name=self.client_name_input.text().strip(),
            request_timeout=self.timeout_input.text().strip(),
        )
        if not ok:
            self.show_warning("Konfigurasi", message)
            return
        self.show_info("Konfigurasi", message)
        if restart_required and not self._restart_application():
            self.show_warning(
                "Restart Manual",
                "Konfigurasi sudah tersimpan, tetapi restart otomatis gagal. Silakan tutup lalu buka ulang aplikasi.",
            )
        self.accept()

    def _restart_application(self):
        executable = sys.executable
        argv = [executable]
        argv.extend(sys.argv)
        try:
            # edited by glg
            # Restart aplikasi via executable path absolut milik proses saat ini.
            os.execv(executable, argv)  # nosec B606
            return True
        except OSError as exc:
            LOGGER.error("Restart otomatis gagal: %s", exc)
            return False
