import concurrent.futures
import json
from typing import Dict, Optional, List, Tuple

import requests
import urllib3

from PyQt6.QtCore import QThread, QTimer, Qt, pyqtSignal
from PyQt6.QtGui import QIcon, QImage, QPixmap
from PyQt6.QtWidgets import (
    QDialog,
    QVBoxLayout,
    QListWidget,
    QHBoxLayout,
    QPushButton,
    QDialogButtonBox,
    QMessageBox,
    QInputDialog,
    QLineEdit,
    QFrame,
    QProgressBar,
    QLabel,
    QListWidgetItem,
    QCheckBox,
    QScrollArea,
)

from core.config import logger
from core.runtime_platform import detect_runtime_platform
from core.tenant_manager import TenantManager
from modules.hardware.thermal_printer import ThermalPrinterManager


class LoadingDialog(QDialog):
    def __init__(self, message="İşlem yapılıyor...", parent=None):
        super().__init__(parent)
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setModal(True)
        self.setFixedSize(350, 120)

        layout = QVBoxLayout(self)
        self.frame = QFrame()
        self.frame.setStyleSheet(
            "QFrame { background-color: #2D2D2D; border-radius: 12px; border: 2px solid #D4AF37; } "
            "QLabel { color: white; font-weight: bold; }"
        )
        layout.addWidget(self.frame)

        fl = QVBoxLayout(self.frame)
        self.message_label = QLabel(message, alignment=Qt.AlignmentFlag.AlignCenter)
        fl.addWidget(self.message_label)

        self.progress = QProgressBar()
        self.progress.setRange(0, 0)
        self.progress.setTextVisible(False)
        fl.addWidget(self.progress)

    def set_message(self, message: str) -> None:
        try:
            self.message_label.setText(message)
        except Exception:
            return


class ProfileManagerDialog(QDialog):
    """
    MySQL tabanlı Profil Seçim/Yönetim Ekranı.
    Profil oluşturma, silme ve seçim işlemlerini yönetir.
    """

    def __init__(self, lang: Dict[str, str], db, parent=None):
        super().__init__(parent)
        self.lang = lang
        self.selected_profile_id: Optional[str] = None
        self.selected_profile_name: Optional[str] = None

        try:
            self.db = db
        except Exception as e:
            QMessageBox.critical(self, self.lang.get("error", "Error"), str(e))
            self.reject()
            return

        self.setWindowTitle(self.lang.get("profile_management", "Profile Management"))
        self.setMinimumWidth(450)
        self.setMinimumHeight(450)

        layout = QVBoxLayout(self)
        layout.setSpacing(15)

        lbl_info = QLabel(self.lang.get("select_profile", "Select a profile:"))
        lbl_info.setStyleSheet("font-size: 14px; font-weight: bold; color: #555;")
        layout.addWidget(lbl_info)

        self.list_widget = QListWidget()
        self.list_widget.setStyleSheet(
            """
            QListWidget { font-size: 14px; padding: 5px; border: 1px solid #ccc; border-radius: 4px; }
            QListWidget::item { padding: 8px; }
            QListWidget::item:selected { background-color: #3498db; color: white; border-radius: 3px; }
        """
        )
        self.list_widget.itemDoubleClicked.connect(self.accept)
        layout.addWidget(self.list_widget)

        btn_layout = QHBoxLayout()

        btn_new = QPushButton(self.lang.get("new_profile", "New Profile"))
        btn_new.setIcon(QIcon.fromTheme("list-add"))
        btn_new.setMinimumHeight(45)
        btn_new.setStyleSheet("font-weight: bold;")
        btn_new.clicked.connect(self.create_new_profile)

        btn_delete = QPushButton(self.lang.get("delete_profile", "Delete Profile"))
        btn_delete.setIcon(QIcon.fromTheme("edit-delete"))
        btn_delete.setObjectName("dangerButton")
        btn_delete.setStyleSheet(
            "background-color: #e74c3c; color: white; font-weight: bold; border-radius: 4px;"
        )
        btn_delete.setMinimumHeight(45)
        btn_delete.clicked.connect(self.delete_selected_profile)

        btn_layout.addWidget(btn_new)
        btn_layout.addStretch()
        btn_layout.addWidget(btn_delete)
        layout.addLayout(btn_layout)

        self.buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        ok_btn = self.buttons.button(QDialogButtonBox.StandardButton.Ok)
        if ok_btn:
            ok_btn.setDefault(True)
            ok_btn.setAutoDefault(True)
        layout.addWidget(self.buttons)

        self.load_profiles_list()

    def load_profiles_list(self) -> None:
        """Veritabanındaki aktif profilleri çeker ve listeler."""
        self.list_widget.clear()
        try:
            profiles = self.db.fetch_all(
                """
                SELECT id, name
                FROM profiles
                WHERE is_active = 1 AND COALESCE(is_deleted, 0) = 0
                ORDER BY name ASC
                """
            )
            for prof in profiles:
                item = QListWidgetItem(prof["name"])
                item.setIcon(QIcon.fromTheme("folder"))
                item.setData(Qt.ItemDataRole.UserRole, prof["id"])
                self.list_widget.addItem(item)
            if self.list_widget.count() > 0:
                self.list_widget.setCurrentRow(0)
            ok_btn = self.buttons.button(QDialogButtonBox.StandardButton.Ok)
            if ok_btn:
                ok_btn.setEnabled(self.list_widget.count() > 0)
        except Exception as e:
            logger.error(f"Profil listesi yüklenemedi: {e}")
            QMessageBox.warning(self, self.lang.get("error", "Error"), str(e))

    def create_new_profile(self) -> None:
        """Yeni bir profil oluşturur (INSERT) ve varsayılan ayarları ekler."""
        name, ok = QInputDialog.getText(
            self, self.lang.get("new_profile", "New Profile"), self.lang.get("enter_profile_name", "Profile name:")
        )
        if not ok or not name.strip():
            return
        name = name.strip()
        try:
            from core.profile_sync_service import ProfileSyncService

            ProfileSyncService(self.db).create_local_profile(
                name,
                source="ProfileManagerDialog.create_new_profile",
            )
            self.load_profiles_list()
            items = self.list_widget.findItems(name, Qt.MatchFlag.MatchExactly)
            if items:
                self.list_widget.setCurrentItem(items[0])
            QMessageBox.information(self, self.lang.get("success", "Success"), f"'{name}' profili oluşturuldu.")
        except Exception as e:
            logger.error(f"Profil oluşturma hatası: {e}")
            QMessageBox.critical(self, self.lang.get("error", "Error"), str(e))

    def delete_selected_profile(self) -> None:
        """Seçili profili ve tüm verilerini siler."""
        item = self.list_widget.currentItem()
        if not item:
            return

        profile_id = item.data(Qt.ItemDataRole.UserRole)
        profile_name = item.text()

        confirm = QMessageBox.question(
            self,
            self.lang.get("delete_profile", "Delete Profile"),
            self.lang.get("confirm_delete_profile_full", "Delete profile '{profile_name}'?").format(
                profile_name=profile_name
            ),
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
        )
        if confirm != QMessageBox.StandardButton.Yes:
            return

        try:
            from core.profile_sync_service import ProfileSyncService

            ProfileSyncService(self.db).delete_local_profile(
                profile_id=profile_id,
                profile_name=profile_name,
                source="ProfileManagerDialog.delete_selected_profile",
            )
            row = self.list_widget.row(item)
            self.list_widget.takeItem(row)
            QMessageBox.information(self, self.lang.get("success", "Success"), f"'{profile_name}' silindi.")
        except Exception as e:
            logger.error(f"Profil silme hatası: {e}")
            QMessageBox.critical(self, self.lang.get("error", "Error"), f"Silinemedi: {e}")

    def accept(self) -> None:
        """Seçimi onayla ve veriyi ana uygulamaya ilet."""
        item = self.list_widget.currentItem()
        if not item:
            QMessageBox.warning(
                self, self.lang.get("warning", "Warning"), self.lang.get("select_profile", "Select a profile.")
            )
            return
        self.selected_profile_id = item.data(Qt.ItemDataRole.UserRole)
        self.selected_profile_name = item.text()
        super().accept()


class BackupProfilePickerDialog(QDialog):
    def __init__(self, db, current_profile_id: str = "", parent=None):
        super().__init__(parent)
        self.db = db
        self.current_profile_id = str(current_profile_id or "").strip()
        self._checks: List[Tuple[str, QCheckBox]] = []

        self.setWindowTitle("Yedeklenecek Profiller")
        self.setMinimumSize(420, 380)

        layout = QVBoxLayout(self)
        layout.addWidget(QLabel("Yedeklenecek profilleri seçin:"))

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        container = QFrame()
        container_layout = QVBoxLayout(container)

        rows = self.db.fetch_all(
            "SELECT id, name FROM profiles WHERE COALESCE(is_deleted, 0) = 0 ORDER BY name ASC"
        ) or []

        if not rows:
            container_layout.addWidget(QLabel("Profil bulunamadı."))
        else:
            for row in rows:
                profile_id = str(row.get("id") or "").strip()
                if not profile_id:
                    continue
                profile_name = str(row.get("name") or profile_id).strip()
                cb = QCheckBox(profile_name)
                if profile_id == self.current_profile_id:
                    cb.setChecked(True)
                container_layout.addWidget(cb)
                self._checks.append((profile_id, cb))

        container_layout.addStretch()
        scroll.setWidget(container)
        layout.addWidget(scroll)

        buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        buttons.accepted.connect(self._on_accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

    def _on_accept(self) -> None:
        if not self.selected_profile_ids():
            QMessageBox.warning(self, "Uyarı", "En az bir profil seçmelisiniz.")
            return
        self.accept()

    def selected_profile_ids(self) -> List[str]:
        return [pid for pid, cb in self._checks if cb.isChecked()]


class DevicePairingDialog(QDialog):
    def __init__(self, tenant_manager, parent=None):
        super().__init__(parent)
        self.tenant_manager = tenant_manager
        self.api_token = tenant_manager.get_api_token()
        self.base_url = "https://app.golder.biz/api/devices" # API URL'niz
        self.pairing_token = ""
        self._qr_pixmap = None
        
        self.setWindowTitle("Yeni Web Cihazı Bağla")
        self.setFixedSize(420, 620)
        self.setStyleSheet("background-color: #f5f5f5; color: #333;")
        
        layout = QVBoxLayout(self)
        layout.setSpacing(12)
        layout.setContentsMargins(14, 14, 14, 14)
        
        self.info_label = QLabel("<b>Telefon kamerasından QR Kodu okutun</b><br>veya aşağıdaki PIN kodunu girin.")
        self.info_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.info_label.setWordWrap(True)
        self.info_label.setStyleSheet("font-size: 14px;")
        layout.addWidget(self.info_label)
        
        self.qr_label = QLabel("Yükleniyor...")
        self.qr_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.qr_label.setFixedSize(360, 360)
        self.qr_label.setStyleSheet("background-color: white; border-radius: 10px; padding: 8px;")
        layout.addWidget(self.qr_label)
        
        self.pin_label = QLabel("PIN: ...")
        self.pin_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.pin_label.setStyleSheet("font-size: 28px; font-weight: bold; letter-spacing: 5px; color: #285430;")
        layout.addWidget(self.pin_label)
        
        self.cancel_btn = QPushButton("İptal Et")
        self.cancel_btn.setStyleSheet("background-color: #D32F2F; color: white; padding: 10px; font-weight: bold; border-radius: 5px;")
        self.cancel_btn.clicked.connect(self.reject)
        layout.addWidget(self.cancel_btn)
        
        self.poll_timer = QTimer(self)
        self.poll_timer.timeout.connect(self.check_status)
        
        # Ekran açılır açılmaz sunucudan QR üret
        self.generate_qr()

    def _extract_api_error_message(self, resp: requests.Response, fallback: str) -> str:
        try:
            data = resp.json()
        except Exception:
            data = None
        if isinstance(data, dict):
            message = str(data.get("message") or "").strip()
            if message:
                return message
        try:
            body = str(resp.text or "").strip()
        except Exception:
            body = ""
        return body or fallback

    def generate_qr(self):
        try:
            import qrcode
        except ImportError:
            QMessageBox.critical(self, "Eksik Kütüphane", "Lütfen terminalden 'pip install qrcode pillow' komutunu çalıştırın.")
            self.reject()
            return

        try:
            is_mac = detect_runtime_platform() == "macos"
            verify_ssl = not is_mac
            if is_mac:
                urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

            headers = {"Authorization": f"Bearer {self.api_token}"}
            if is_mac:
                headers["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"

            timeout_val = 20 if is_mac else 10
            resp = requests.post(
                f"{self.base_url}/generate_qr.php",
                headers=headers,
                timeout=timeout_val,
                verify=verify_ssl,
            )
            data = resp.json()
            if resp.status_code >= 400:
                raise RuntimeError(
                    self._extract_api_error_message(resp, "Web cihaz ekleme kodu alınamadı.")
                )
            
            if data.get("status") == "ok":
                self.pairing_token = data["pairing_token"]
                pin = data["pin_code"]
                self.pin_label.setText(f"{pin[:3]} {pin[3:]}")
                
                # QR Kodu Görüntüye Çevir
                qr = qrcode.QRCode(box_size=6, border=2)
                qr.add_data(self.pairing_token)
                qr.make(fit=True)
                img = qr.make_image(fill_color="black", back_color="white").convert("RGBA")
                
                data_bytes = img.tobytes("raw", "RGBA")
                qim = QImage(data_bytes, img.size[0], img.size[1], QImage.Format.Format_RGBA8888)
                self._qr_pixmap = QPixmap.fromImage(qim)
                scaled = self._qr_pixmap.scaled(
                    self.qr_label.size(),
                    Qt.AspectRatioMode.KeepAspectRatio,
                    Qt.TransformationMode.SmoothTransformation,
                )
                self.qr_label.setPixmap(scaled)
                
                # Her 2 saniyede bir telefonu kontrol et
                self.poll_timer.start(2000) 
            else:
                QMessageBox.critical(self, "Hata", data.get("message", "Sunucu hatası."))
                self.reject()
        except Exception as e:
            QMessageBox.critical(self, "Bağlantı Hatası", f"Sunucuya ulaşılamadı:\n{e}")
            self.reject()

    def check_status(self):
        try:
            is_mac = detect_runtime_platform() == "macos"
            verify_ssl = not is_mac
            if is_mac:
                urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

            headers = {"Authorization": f"Bearer {self.api_token}"}
            if is_mac:
                headers["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"

            payload = {"pairing_token": self.pairing_token}
            timeout_val = 15 if is_mac else 5
            resp = requests.post(
                f"{self.base_url}/check_qr_status.php",
                json=payload,
                headers=headers,
                timeout=timeout_val,
                verify=verify_ssl,
            )
            
            if resp.status_code == 200:
                data = resp.json()
                status = data.get("pairing_status")
                
                if status == "paired":
                    self.poll_timer.stop()
                    self.accept() # Başarılı dönüş
                elif status == "expired":
                    self.poll_timer.stop()
                    QMessageBox.warning(self, "Süre Doldu", "Güvenlik nedeniyle kodun süresi doldu. Lütfen tekrar deneyin.")
                    self.reject()
        except Exception:
            pass # Anlık internet kopmalarını yoksay
            
    def closeEvent(self, event):
        self.poll_timer.stop()
        super().closeEvent(event)


class DeviceManagementDialog(QDialog):
    def __init__(self, tenant_manager, parent=None):
        super().__init__(parent)
        self.tenant_manager = tenant_manager
        self.api_token = tenant_manager.get_api_token()
        self.base_url = "https://app.golder.biz/api/devices"
        self.devices = []

        self.setWindowTitle("Bağlı Web Cihazları")
        self.setMinimumSize(520, 420)

        layout = QVBoxLayout(self)
        layout.setSpacing(10)

        info = QLabel("Bu kullanıcıya ait web cihazlarını buradan silebilirsiniz.")
        info.setWordWrap(True)
        layout.addWidget(info)

        self.list_widget = QListWidget()
        layout.addWidget(self.list_widget)

        btn_row = QHBoxLayout()
        self.refresh_btn = QPushButton("Yenile")
        self.delete_btn = QPushButton("Seçili Cihazı Sil")
        self.delete_btn.setObjectName("dangerButton")
        self.delete_btn.setEnabled(False)
        btn_row.addWidget(self.refresh_btn)
        btn_row.addStretch()
        btn_row.addWidget(self.delete_btn)
        layout.addLayout(btn_row)

        self.list_widget.currentRowChanged.connect(self._on_row_changed)
        self.refresh_btn.clicked.connect(self.load_devices)
        self.delete_btn.clicked.connect(self.delete_selected_device)

        self.load_devices()

    def _auth_headers(self) -> dict:
        return {"Authorization": f"Bearer {self.api_token}"}

    def _extract_api_error_message(self, resp: requests.Response, fallback: str) -> str:
        try:
            data = resp.json()
        except Exception:
            data = None
        if isinstance(data, dict):
            message = str(data.get("message") or "").strip()
            if message:
                return message
        try:
            body = str(resp.text or "").strip()
        except Exception:
            body = ""
        return body or fallback

    def _on_row_changed(self, row: int):
        self.delete_btn.setEnabled(row >= 0)

    def load_devices(self):
        self.list_widget.clear()
        self.devices = []
        try:
            resp = requests.get(f"{self.base_url}/list.php", headers=self._auth_headers(), timeout=10)
            data = resp.json()
            if resp.status_code >= 400:
                raise RuntimeError(
                    self._extract_api_error_message(resp, "Web cihaz ekleme kodu alınamadı.")
                )
            if data.get("status") != "ok":
                raise RuntimeError(str(data.get("message") or "Cihaz listesi alınamadı."))

            self.devices = list(data.get("devices") or [])
            if not self.devices:
                self.list_widget.addItem("Kayıtlı web cihazı bulunamadı.")
                self.list_widget.setEnabled(False)
                self.delete_btn.setEnabled(False)
                return

            self.list_widget.setEnabled(True)
            for dev in self.devices:
                device_id = int(dev.get("id") or 0)
                name = str(dev.get("device_name") or "Adsız Cihaz")
                dtype = str(dev.get("device_type") or "web")
                last_active = str(dev.get("last_active_at") or dev.get("last_login") or "-")
                active_sessions = int(dev.get("active_sessions") or 0)
                is_blocked = int(dev.get("is_blocked") or 0) == 1
                status = "Engelli" if is_blocked else "Aktif"
                label = (
                    f"{name} | Tip: {dtype} | Aktif Web Oturum: {active_sessions} "
                    f"| Son Aktivite: {last_active} | Durum: {status}"
                )
                item = QListWidgetItem(label)
                item.setData(Qt.ItemDataRole.UserRole, device_id)
                self.list_widget.addItem(item)

            if self.list_widget.count() > 0:
                self.list_widget.setCurrentRow(0)
        except Exception as e:
            self.list_widget.setEnabled(False)
            self.delete_btn.setEnabled(False)
            QMessageBox.critical(self, "Hata", f"Cihaz listesi alınamadı:\n{e}")

    def delete_selected_device(self):
        item = self.list_widget.currentItem()
        if not item:
            return
        device_id = int(item.data(Qt.ItemDataRole.UserRole) or 0)
        if device_id <= 0:
            return

        confirm = QMessageBox.question(
            self,
            "Cihazı Sil",
            "Seçili cihaz engellenecek ve bu cihazdaki web oturumları sonlanacaktır.\nDevam etmek istiyor musunuz?",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
        )
        if confirm != QMessageBox.StandardButton.Yes:
            return

        try:
            resp = requests.post(
                f"{self.base_url}/remove.php",
                json={"device_id": device_id},
                headers=self._auth_headers(),
                timeout=10,
            )
            resp.raise_for_status()
            data = resp.json()
            if data.get("status") != "ok":
                raise RuntimeError(str(data.get("message") or "Cihaz silinemedi."))
            QMessageBox.information(self, "Başarılı", "Cihaz silindi.")
            self.load_devices()
        except Exception as e:
            QMessageBox.critical(self, "Hata", f"Cihaz silinemedi:\n{e}")


class ThermalPrinterDiscoveryWorker(QThread):
    finished_scan = pyqtSignal(list, list)
    failed_scan = pyqtSignal(str)

    def run(self):
        manager = ThermalPrinterManager()

        try:
            local_ips = manager.get_local_ipv4_addresses()
            candidate_ips = manager._build_candidate_ip_pool()
            found_devices = []

            if candidate_ips:
                worker_count = max(1, min(64, len(candidate_ips)))
                executor = concurrent.futures.ThreadPoolExecutor(max_workers=worker_count)
                futures = [
                    executor.submit(manager._probe_network_printer, ip_addr, 0.25)
                    for ip_addr in candidate_ips
                ]

                try:
                    for future in concurrent.futures.as_completed(futures):
                        if self.isInterruptionRequested():
                            executor.shutdown(wait=False, cancel_futures=True)
                            return
                        try:
                            result = future.result()
                        except Exception:
                            continue
                        if result:
                            found_devices.append(result)
                finally:
                    executor.shutdown(wait=True, cancel_futures=False)

            found_devices.sort(key=lambda item: manager._sort_ip_key(item.get("ip", "")))
            self.finished_scan.emit(local_ips, found_devices)
        except Exception as e:
            self.failed_scan.emit(str(e))


class ThermalPrinterDiscoveryDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Termal Yazici Ag Taramasi")
        self.setMinimumSize(520, 420)

        self.selected_printer_ip = ""
        self.worker: Optional[ThermalPrinterDiscoveryWorker] = None

        layout = QVBoxLayout(self)

        self.info_label = QLabel(
            "Aynı yerel agdaki termal yazicilar aranacak.\n"
            "Tarama, mevcut baski akisi ile uyumlu olarak 9100 portunu kontrol eder."
        )
        self.info_label.setWordWrap(True)
        layout.addWidget(self.info_label)

        self.local_ip_label = QLabel("")
        self.local_ip_label.setWordWrap(True)
        layout.addWidget(self.local_ip_label)

        self.progress = QProgressBar()
        self.progress.setRange(0, 0)
        self.progress.setTextVisible(False)
        layout.addWidget(self.progress)

        self.result_list = QListWidget()
        self.result_list.itemDoubleClicked.connect(lambda *_: self._use_selected())
        layout.addWidget(self.result_list)

        btn_row = QHBoxLayout()
        self.scan_btn = QPushButton("Agi Yeniden Tara")
        self.scan_btn.clicked.connect(self.start_scan)
        btn_row.addWidget(self.scan_btn)

        btn_row.addStretch()

        self.use_btn = QPushButton("Secileni Kullan")
        self.use_btn.setObjectName("primaryButton")
        self.use_btn.setEnabled(False)
        self.use_btn.clicked.connect(self._use_selected)
        btn_row.addWidget(self.use_btn)

        self.cancel_btn = QPushButton("Iptal")
        self.cancel_btn.clicked.connect(self.reject)
        btn_row.addWidget(self.cancel_btn)

        layout.addLayout(btn_row)

        QTimer.singleShot(0, self.start_scan)

    def start_scan(self):
        if self.worker and self.worker.isRunning():
            return

        self.selected_printer_ip = ""
        self.result_list.clear()
        self.use_btn.setEnabled(False)
        self.progress.show()
        self.info_label.setText("Ag taraniyor... Bu islem genelde birkac saniye surer.")
        self.local_ip_label.setText("")
        self.scan_btn.setEnabled(False)

        self.worker = ThermalPrinterDiscoveryWorker()
        self.worker.finished_scan.connect(self._on_scan_finished)
        self.worker.failed_scan.connect(self._on_scan_failed)
        self.worker.finished.connect(self._on_worker_finished)
        self.worker.start()

    def _on_scan_finished(self, local_ips: List[str], devices: List[Dict[str, str]]):
        local_ip_text = ", ".join(local_ips) if local_ips else "Yerel IPv4 algilanamadi"
        self.local_ip_label.setText(f"Tarama cikis IP'leri: {local_ip_text}")

        if not devices:
            self.info_label.setText(
                "Agda otomatik bulunan bir termal yazici yok.\n"
                "IP'yi elle girebilir veya yazicinin ayni agda oldugunu kontrol edebilirsiniz."
            )
            return

        self.info_label.setText("Bulunan cihazlar listelendi. Secip kullanabilirsiniz.")
        for device in devices:
            label = str(device.get("display_name") or device.get("ip") or "").strip()
            item = QListWidgetItem(label)
            item.setData(Qt.ItemDataRole.UserRole, device.get("ip"))
            self.result_list.addItem(item)

        self.result_list.setCurrentRow(0)
        self.use_btn.setEnabled(True)

    def _on_scan_failed(self, message: str):
        self.info_label.setText("Ag taramasi sirasinda hata olustu.")
        QMessageBox.warning(self, "Ag Taramasi", f"Termal yazici aranamadi:\n{message}")

    def _on_worker_finished(self):
        self.progress.hide()
        self.scan_btn.setEnabled(True)

    def _use_selected(self):
        item = self.result_list.currentItem()
        if not item:
            QMessageBox.information(self, "Secim Gerekli", "Lutfen listeden bir yazici secin.")
            return

        self.selected_printer_ip = str(item.data(Qt.ItemDataRole.UserRole) or "").strip()
        if not self.selected_printer_ip:
            QMessageBox.warning(self, "Gecersiz Kayit", "Secilen kayittan IP bilgisi okunamadi.")
            return
        self.accept()

    def _stop_worker(self):
        if self.worker and self.worker.isRunning():
            self.worker.requestInterruption()
            self.worker.wait(4000)

    def reject(self):
        self._stop_worker()
        super().reject()

    def closeEvent(self, event):
        self._stop_worker()
        super().closeEvent(event)


class RemoteBarcodeScannerDialog(QDialog):
    """Telefondan (Web) barkod okutma köprü penceresi."""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("📱 Telefondan Barkod Okut")
        self.setFixedSize(350, 400)
        self.tenant = TenantManager()
        self.api_token = self.tenant.get_api_token()
        self.scanned_barcode = None
        self.request_id = None
        
        self.layout = QVBoxLayout(self)
        
        self.info_label = QLabel("Lütfen okuma yapacağınız cihazı seçin:")
        self.info_label.setWordWrap(True)
        self.layout.addWidget(self.info_label)
        
        self.device_list = QListWidget()
        self.layout.addWidget(self.device_list)
        
        btn_layout = QHBoxLayout()
        self.cancel_btn = QPushButton("İptal")
        self.cancel_btn.clicked.connect(self.reject)
        
        self.send_btn = QPushButton("Bu Cihaza İstek Gönder")
        self.send_btn.setObjectName("primaryButton")
        self.send_btn.clicked.connect(self.send_scan_request)
        
        btn_layout.addWidget(self.cancel_btn)
        btn_layout.addWidget(self.send_btn)
        self.layout.addLayout(btn_layout)
        
        self.poll_timer = QTimer(self)
        self.poll_timer.timeout.connect(self.poll_result)
        
        self.fetch_devices()

    def fetch_devices(self):
        try:
            resp = requests.get("https://app.golder.biz/api/devices/list.php",
                                headers={"Authorization": f"Bearer {self.api_token}"}, timeout=5)
            data = resp.json()
            if data.get("status") == "ok":
                for dev in data.get("devices", []):
                    if dev.get("device_type") == "web":
                        item = QListWidgetItem(f"📱 {dev.get('device_name')}")
                        item.setData(Qt.ItemDataRole.UserRole, dev.get("id"))
                        self.device_list.addItem(item)
            if self.device_list.count() == 0:
                self.info_label.setText("Aktif bağlı bir telefon/web cihazı bulunamadı. Lütfen Ayarlar > Cihaz Yönetimi'nden cihaz bağlayın.")
                self.send_btn.setEnabled(False)
            else:
                self.device_list.setCurrentRow(0)
        except Exception:
            self.info_label.setText("Cihazlar alınırken ağ hatası oluştu.")
            self.send_btn.setEnabled(False)

    def send_scan_request(self):
        item = self.device_list.currentItem()
        if not item:
            return
        dev_id = item.data(Qt.ItemDataRole.UserRole)
        
        try:
            resp = requests.post("https://app.golder.biz/api/scanner/request.php",
                                 json={"device_id": dev_id},
                                 headers={"Authorization": f"Bearer {self.api_token}"}, timeout=5)
            data = resp.json()
            if data.get("status") == "ok":
                self.request_id = data.get("request_id")
                self.device_list.setVisible(False)
                self.send_btn.setVisible(False)
                self.info_label.setText("⏳ <b>Telefondan barkod okutulması bekleniyor...</b>\n\n(Telefonda kamera otomatik açılacaktır. Lütfen barkodu okutun.)")
                self.info_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
                self.poll_timer.start(1500) # 1.5 saniyede bir kontrol et
            else:
                QMessageBox.warning(self, "Hata", data.get("message", "İstek gönderilemedi."))
        except Exception as e:
            QMessageBox.critical(self, "Ağ Hatası", f"Sunucuya ulaşılamadı: {e}")

    def poll_result(self):
        if not self.request_id:
            return
        try:
            resp = requests.post("https://app.golder.biz/api/scanner/poll.php",
                                 json={"request_id": self.request_id},
                                 headers={"Authorization": f"Bearer {self.api_token}"}, timeout=3)
            data = resp.json()
            status = data.get("scan_status")
            
            if status == "completed":
                self.poll_timer.stop()
                self.scanned_barcode = data.get("barcode")
                self.accept()
            elif status == "cancelled":
                self.poll_timer.stop()
                QMessageBox.warning(self, "İptal Edildi", "Telefondan okuma işlemi iptal edildi veya zaman aşımına uğradı.")
                self.reject()
        except Exception:
            pass # Anlık ağ kopmalarını yok say
            
    def closeEvent(self, event):
        self.poll_timer.stop()
        super().closeEvent(event)




