import logging
from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
    QListWidget, QTextEdit, QLineEdit, QPushButton
)
from PyQt6.QtCore import Qt
from core.ai_agent import AIAgentWorker
from ui.ai_response_formatter import format_ai_response_html

logger = logging.getLogger(__name__)

class AITab(QWidget):
    """
    [AI_DOC]
    Yapay Zeka (AI) asistani arayuzunu ve sinyal yonetimini barindiran izole sinif.
    Kullanicidan gelen sorulari alir, arka planda (QThread) AIAgentWorker'i baslatir 
    ve donen sonuclari ekrana basar. main_window.py'nin yukunu hafifletir.
    [/AI_DOC]
    """
    def __init__(self, main_window):
        super().__init__()
        self.main_window = main_window
        self.tenant_manager = main_window.tenant_manager
        self.db = main_window.data_manager.db
        self.profile_id = main_window.data_manager.profile_id
        self._ai_worker = None
        self._init_ui()

    def _init_ui(self):
        layout = QHBoxLayout(self)
        
        # Sol Panel - Gecmis Sorular
        left_panel = QVBoxLayout()
        left_panel.addWidget(QLabel("<b>Onceki Sorular</b>"))
        self.history_list = QListWidget()
        self.history_list.setFixedWidth(250)
        left_panel.addWidget(self.history_list)
        
        # Sag Panel - Sohbet ve Girdi
        right_panel = QVBoxLayout()
        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        self.chat_display.setHtml(
            "<h3>💎 Golder AI Asistanina Hosgeldiniz!</h3>"
            "<p>Magazanizin verileriyle ilgili dilediginiz soruyu sorabilirsiniz.<br>"
            "<i>Orn: Kasalarimda toplam ne kadar param var? Veya son 1 haftada kime satis yaptik?</i></p>"
            "<hr>"
        )
        right_panel.addWidget(self.chat_display, stretch=1)
        
        self.quota_label = QLabel("Kalan Soru Hakki: -/100")
        self.quota_label.setStyleSheet("color: gray; font-size: 11px;")
        right_panel.addWidget(self.quota_label, alignment=Qt.AlignmentFlag.AlignRight)
        
        input_layout = QHBoxLayout()
        self.question_input = QLineEdit()
        self.question_input.setPlaceholderText("Sorunuzu buraya yazin...")
        self.question_input.setFixedHeight(40)
        self.question_input.returnPressed.connect(self.ask_question)
        
        self.send_btn = QPushButton("Gonder")
        self.send_btn.setObjectName("primaryButton")
        self.send_btn.setFixedHeight(40)
        self.send_btn.setFixedWidth(100)
        self.send_btn.clicked.connect(self.ask_question)
        
        input_layout.addWidget(self.question_input)
        input_layout.addWidget(self.send_btn)
        right_panel.addLayout(input_layout)
        
        layout.addLayout(left_panel)
        layout.addLayout(right_panel)

    def ask_question(self):
        question = self.question_input.text().strip()
        if not question:
            return
        
        self.question_input.clear()
        self.send_btn.setEnabled(False)
        self.question_input.setEnabled(False)
        
        self.chat_display.append(f"<br><b>👤 Siz:</b> {question}")
        self.history_list.addItem(question)
        
        # Arka plan AI iscisi baslat
        self._ai_worker = AIAgentWorker(
            self.tenant_manager, 
            self.db, 
            self.main_window.data_manager.profile_id, 
            question
        )
        self._ai_worker.status_update.connect(self._on_status)
        self._ai_worker.response_ready.connect(self._on_response)
        self._ai_worker.error_occurred.connect(self._on_error)
        self._ai_worker.finished.connect(self._on_finished)
        self._ai_worker.start()

    def _on_status(self, status_text):
        self.chat_display.append(f"<i style='color:gray; font-size:11px;'>⚙️ {status_text}</i>")

    def _on_response(self, text, quota):
        rendered_html = format_ai_response_html(text)
        self.chat_display.append(f"<br><b style='color:#D4AF37;'>🤖 Golder AI:</b><br>{rendered_html}<br><hr>")
        self.quota_label.setText(f"Kalan Soru Hakki: {quota}/100")

    def _on_error(self, err_text):
        self.chat_display.append(f"<br><b style='color:#D32F2F;'>❌ Hata:</b> {err_text}<br><hr>")

    def _on_finished(self):
        self.send_btn.setEnabled(True)
        self.question_input.setEnabled(True)
        self.question_input.setFocus()




