
from PyQt6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QTableWidget,
    QTableWidgetItem, QHeaderView, QPushButton, QComboBox,
    QMessageBox, QGroupBox, QSpinBox
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QColor
from core.tenant_manager import TenantManager
import uuid

class GoldBatchDialog(QDialog):
    """
    Altin (Product) Alis/Satis icin Toplu Barkodlu Islem Ekrani.
    """
    def __init__(self, mode, stock_manager, product_manager, depot_list, parent=None):
        super().__init__(parent)
        self.mode = mode 
        self.stock_manager = stock_manager
        self.product_manager = product_manager
        self.depot_list = depot_list
        
        self.use_barcode = True
        if hasattr(parent, 'settings_manager'):
            self.use_barcode = parent.settings_manager.get_setting("use_barcode_system", True)
            
        self.setWindowTitle(f"Hizli Altin {'Satis' if mode == 'Sale' else 'Alis'}")
        self.setMinimumWidth(950) 
        self.setMinimumHeight(600)
        self.processed_data = []
        self._init_ui()

    def _init_ui(self):
        layout = QVBoxLayout(self)
        top_group = QGroupBox("Islem Ayarlari")
        top_layout = QHBoxLayout(top_group)
        
        self.depot_combo = QComboBox()
        self.depot_combo.addItems(self.depot_list)
        
        self.product_combo = QComboBox()
        self.product_combo.setEditable(True)
        products = sorted([p.product_name for p in self.product_manager.get_all()])
        self.product_combo.addItems(products)
        self.product_combo.setPlaceholderText("Urun Turu Secin")
        
        self.qty_spin = QSpinBox()
        self.qty_spin.setRange(1, 500)
        self.qty_spin.setValue(1)
        self.qty_spin.setSuffix(" Adet")
        
        self.btn_create = QPushButton("Listeyi Hazirla")
        self.btn_create.setStyleSheet("font-weight: bold;")
        self.btn_create.clicked.connect(self._create_table_rows)
        
        top_layout.addWidget(QLabel("Depo:"))
        top_layout.addWidget(self.depot_combo, 1)
        top_layout.addWidget(QLabel("Urun:"))
        top_layout.addWidget(self.product_combo, 2)
        top_layout.addWidget(QLabel("Adet:"))
        top_layout.addWidget(self.qty_spin, 1)
        top_layout.addWidget(self.btn_create)
        layout.addWidget(top_group)
        
        self.table = QTableWidget()
        headers = ["Barkod (Okut)", "Gram", "Ayar", "Birim Fiyat", "Durum / Bilgi"]
        self.table.setColumnCount(len(headers))
        self.table.setHorizontalHeaderLabels(headers)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        layout.addWidget(self.table)
        
        self.table.cellChanged.connect(self._on_cell_changed)
        
        self.tm = TenantManager()
        self.btn_remote_scan = QPushButton("📱 Secili Satir Icin Telefondan Okut")
        self.btn_remote_scan.setStyleSheet("background-color: #1976D2; color: white; font-weight: bold; padding: 8px;")
        self.btn_remote_scan.clicked.connect(self._start_remote_scan)
        layout.addWidget(self.btn_remote_scan)
        
        if not self.use_barcode:
            self.table.setColumnHidden(0, True)
            self.btn_remote_scan.hide()
            
        bottom_layout = QHBoxLayout()
        self.lbl_summary = QLabel("Toplam: 0 Adet | 0.00 Gram | 0.00 Tutar")
        self.lbl_summary.setStyleSheet("font-weight: bold; font-size: 14px; color: #333;")
        
        self.btn_save = QPushButton(f"Islemi Onayla ({'Satis' if self.mode == 'Sale' else 'Alis'})")
        self.btn_save.setStyleSheet(f"font-weight: bold; padding: 12px; background-color: {'#C62828' if self.mode == 'Sale' else '#2E7D32'}; color: white;")
        self.btn_save.clicked.connect(self._save_transaction)
        self.btn_save.setEnabled(False)
        
        btn_cancel = QPushButton("Iptal")
        btn_cancel.clicked.connect(self.reject)
        
        bottom_layout.addWidget(self.lbl_summary)
        bottom_layout.addStretch()
        bottom_layout.addWidget(self.btn_save)
        bottom_layout.addWidget(btn_cancel)
        layout.addLayout(bottom_layout)

    def _create_table_rows(self):
        product_name = self.product_combo.currentText().strip()
        depot_name = self.depot_combo.currentText().strip()
        if not product_name or not depot_name:
            QMessageBox.warning(self, "Uyari", "Lutfen urun turu ve depo secin.")
            return
            
        qty = self.qty_spin.value()
        self.table.setRowCount(0)
        self.table.setRowCount(qty)
        self.table.blockSignals(True)
        
        p_def = self.product_manager.find_by_attribute("product_name", product_name)
        default_karat = p_def.karat_purity if p_def else ""
        default_price = f"{p_def.default_purchase_price:.2f}" if (p_def and self.mode == "Purchase") else "0.00"
        if self.mode == "Sale" and p_def:
             default_price = f"{p_def.default_sale_price:.2f}"
             
        if self.mode == "Sale" and not self.use_barcode:
            available = [i for i in self.stock_manager.get_all() if i.item_type == product_name and i.depot_name == depot_name and i.quantity > 0]
            if len(available) < qty:
                QMessageBox.warning(self, "Yetersiz Stok", f"Depoda satilabilecek {qty} adet urun yok.")
                self.table.setRowCount(0)
                self.table.blockSignals(False)
                return
                
            for row in range(qty):
                item = available[row]
                self.table.setItem(row, 0, QTableWidgetItem(item.unique_barcode))
                g_item = QTableWidgetItem(str(item.quantity_gr))
                k_item = QTableWidgetItem(default_karat)
                p_item = QTableWidgetItem(default_price)
                st_item = QTableWidgetItem("✔ Otomatik Secildi")
                
                for it in [g_item, k_item, p_item, st_item]:
                    it.setFlags(it.flags() & ~Qt.ItemFlag.ItemIsEditable)
                    it.setBackground(Qt.GlobalColor.lightGray)
                    
                st_item.setForeground(Qt.GlobalColor.green)
                self.table.setItem(row, 1, g_item)
                self.table.setItem(row, 2, k_item)
                self.table.setItem(row, 3, p_item)
                self.table.setItem(row, 4, st_item)
        else:
            for row in range(qty):
                self.table.setItem(row, 0, QTableWidgetItem(""))
                gram_item = QTableWidgetItem("0.00" if self.mode == "Purchase" else "")
                karat_item = QTableWidgetItem(default_karat)
                
                if self.mode == "Sale":
                    gram_item.setFlags(gram_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
                    karat_item.setFlags(karat_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
                    gram_item.setBackground(Qt.GlobalColor.lightGray)
                    karat_item.setBackground(Qt.GlobalColor.lightGray)
                    
                self.table.setItem(row, 1, gram_item)
                self.table.setItem(row, 2, karat_item)
                self.table.setItem(row, 3, QTableWidgetItem(default_price))
                
                status_text = "Barkod Bekleniyor..." if self.mode == "Sale" else "Veri Giriniz"
                status_item = QTableWidgetItem(status_text)
                status_item.setFlags(status_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
                self.table.setItem(row, 4, status_item)

        self.table.blockSignals(False)
        self.btn_save.setEnabled(True)
        if hasattr(self, "btn_create"): self.btn_create.setDefault(False)
        self._update_summary()

    def _on_cell_changed(self, row, column):
        if column == 0 and self.use_barcode: 
            barcode = self.table.item(row, 0).text().strip()
            if not barcode: return
            selected_depot = self.depot_combo.currentText()
            
            if self.mode == "Sale":
                found_item = next((i for i in self.stock_manager.get_all() if i.unique_barcode == barcode and i.quantity > 0 and i.depot_name == selected_depot), None)
                self.table.blockSignals(True)
                if found_item:
                    self.table.item(row, 1).setText(f"{found_item.quantity_gr:.2f}")
                    p_def = self.product_manager.find_by_attribute("product_name", found_item.item_type)
                    self.table.item(row, 2).setText(p_def.karat_purity if p_def else "?")
                    self.table.item(row, 4).setText("✔ Stokta")
                    self.table.item(row, 4).setForeground(Qt.GlobalColor.green)
                else:
                    self.table.item(row, 1).setText("")
                    self.table.item(row, 2).setText("")
                    self.table.item(row, 4).setText("❌ BULUNAMADI!")
                    self.table.item(row, 4).setForeground(Qt.GlobalColor.red)
                self.table.blockSignals(False)
            elif self.mode == "Purchase":
                exists = any(i.unique_barcode == barcode for i in self.stock_manager.get_all())
                self.table.blockSignals(True)
                if exists:
                    self.table.item(row, 4).setText("❌ BARKOD KULLANIMDA!")
                    self.table.item(row, 4).setForeground(Qt.GlobalColor.red)
                else:
                    self.table.item(row, 4).setText("✔ Uygun")
                    self.table.item(row, 4).setForeground(Qt.GlobalColor.black)
                self.table.blockSignals(False)
                
        if column == 1 or column == 3: 
            self._update_summary()

    def _start_remote_scan(self):
        if not self.tm.is_web_mobile_enabled():
            message = (
                "Senkronizasyon suresi doldu. Telefon uygulamasi calismayacaktir."
                if self.tm.get_sync_status() == "expired"
                else "Bu lisans planinda telefon ve web erisimi kapali."
            )
            QMessageBox.warning(self, "Plan Yetersiz", message)
            return
        import requests
        try: requests.get("https://app.golder.biz", timeout=2)
        except Exception: return
        
        row = self.table.currentRow()
        if row < 0: return
            
        from ui.dialogs import RemoteBarcodeScannerDialog
        dlg = RemoteBarcodeScannerDialog(self)
        if dlg.exec() == QDialog.DialogCode.Accepted and dlg.scanned_barcode:
            self.table.item(row, 0).setText(dlg.scanned_barcode)
            self._on_cell_changed(row, 0)

    def _update_summary(self):
        total_gr, total_val, count = 0.0, 0.0, 0
        for r in range(self.table.rowCount()):
            try:
                if self.table.item(r, 1): total_gr += float(self.table.item(r, 1).text().replace(',', '.') or 0)
                if self.table.item(r, 3): total_val += float(self.table.item(r, 3).text().replace(',', '.') or 0)
                count += 1
            except: pass
        self.lbl_summary.setText(f"Toplam: {count} Adet | {total_gr:.2f} Gram | {total_val:,.2f} Tutar")

    def _save_transaction(self):
        rows = self.table.rowCount()
        product_type = self.product_combo.currentText()
        depot_name = self.depot_combo.currentText()
        items_to_process = []
        
        for r in range(rows):
            bc = self.table.item(r, 0).text().strip()
            if not self.use_barcode and not bc:
                bc = f"SYS-{uuid.uuid4().hex[:8].upper()}"
            if not bc: continue
            
            status = self.table.item(r, 4).text()
            if "❌" in status:
                QMessageBox.warning(self, "Hata", f"{r+1}. satirda hata var.")
                return
            try:
                gram = float(self.table.item(r, 1).text().replace(',', '.'))
                if gram <= 0: raise ValueError
                price = float(self.table.item(r, 3).text().replace(',', '.') or 0)
            except:
                QMessageBox.warning(self, "Hata", f"{r+1}. satirda Gramaj veya Fiyat hatali.")
                return
                
            items_to_process.append({
                "barcode": bc, "gram": gram, "karat": self.table.item(r, 2).text(),
                "price": price, "type": product_type
            })
            
        if not items_to_process:
            QMessageBox.warning(self, "Uyari", "Islenecek satir yok.")
            return
            
        self.processed_data = {
            "items": items_to_process,
            "total_gram": sum(i["gram"] for i in items_to_process),
            "total_qty": len(items_to_process),
            "action": self.mode, "depot": depot_name
        }
        self.accept()

    def get_data(self):
        return self.processed_data




