from __future__ import annotations
from typing import Any, Dict, List, Optional
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import (
    QDialog, QDialogButtonBox, QDoubleSpinBox, QFormLayout, 
    QLabel, QLineEdit, QVBoxLayout, QListWidget, QListWidgetItem, QComboBox
)
from core.db import TaxDefinition

class TaxDefinitionEditorDialog(QDialog):
    # Vergi Tanımlama Ekranı (Ayarlar için)
    def __init__(self, tax: Optional[TaxDefinition] = None, parent=None):
        super().__init__(parent)
        
        # Parent üzerinden lang sözlüğüne güvenli erişim
        self.lang = getattr(parent, "lang", {}) if parent else {}
        
        self.setWindowTitle(self.lang.get("tax_definition", "Tax Definition") if not tax else self.lang.get("edit_tax_def", "Edit Tax Definition"))
        self.setMinimumWidth(350)
        layout = QVBoxLayout(self)
        form = QFormLayout()
        
        self.name_edit = QLineEdit((tax.name if tax else "").strip())
        form.addRow(self.lang.get("tax_name", "Tax Name") + "*:", self.name_edit)
        
        self.type_combo = QComboBox()
        self.type_combo.addItems([
            self.lang.get("tax_type_percent", "Percent (%)"), 
            self.lang.get("tax_type_fixed", "Fixed Amount")
        ])
        if tax and tax.type == "fixed": self.type_combo.setCurrentIndex(1)
        form.addRow(self.lang.get("type", "Type") + ":", self.type_combo)
        
        self.rate_spin = QDoubleSpinBox()
        self.rate_spin.setRange(0, 999999999)
        self.rate_spin.setDecimals(2)
        self.rate_spin.setValue(float(tax.rate) if tax else 0.0)
        form.addRow(self.lang.get("tax_value", "Value (Rate/Amount)") + ":", self.rate_spin)
        
        layout.addLayout(form)
        buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

    def get_data(self):
        t_type = "fixed" if self.type_combo.currentIndex() == 1 else "percent"
        return {
            "name": self.name_edit.text().strip(),
            "type": t_type,
            "rate": self.rate_spin.value(),
            "country": "TR",
            "active": True
        }

class TaxSelectionDialog(QDialog):
    """
    POS ekranında açılan 'Hangi vergileri uygulayayım?' penceresi.
    """
    def __init__(self, available_taxes: List[TaxDefinition], selected_ids: List[str] = None, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Uygulanacak Vergileri Seç")
        self.setMinimumWidth(300)
        self.setMinimumHeight(400)
        self.selected_taxes: List[Dict[str, Any]] = []
        
        layout = QVBoxLayout(self)
        layout.addWidget(QLabel("Listeden uygulanacak vergileri işaretleyiniz:"))
        
        self.list_widget = QListWidget()
        self.items_map = {} 
        
        selected_ids = selected_ids or []
        
        for tax in available_taxes:
            if not tax.active: continue
            rate_str = f"%{tax.rate}" if tax.type == 'percent' else f"{tax.rate} (Sabit)"
            item = QListWidgetItem(f"{tax.name} ({rate_str})")
            item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
            item.setCheckState(Qt.CheckState.Checked if tax.id in selected_ids else Qt.CheckState.Unchecked)
            self.list_widget.addItem(item)
            self.items_map[id(item)] = tax
            
        layout.addWidget(self.list_widget)
        
        btns = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        btns.accepted.connect(self._on_accept)
        btns.rejected.connect(self.reject)
        layout.addWidget(btns)
        
    def _on_accept(self):
        self.selected_taxes = []
        for i in range(self.list_widget.count()):
            item = self.list_widget.item(i)
            if item.checkState() == Qt.CheckState.Checked:
                tax = self.items_map.get(id(item))
                if tax:
                    self.selected_taxes.append({
                        "id": tax.id, "name": tax.name, "rate": tax.rate, "type": tax.type
                    })
        self.accept()
        
    def get_selected_taxes(self) -> List[Dict[str, Any]]:
        return self.selected_taxes



