import sys
from PyQt6.QtWidgets import (
    QApplication,
    QMainWindow,
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QTextEdit,
    QLineEdit,
    QPushButton,
    QLabel,
)

from PyQt6.QtCore import Qt, QThread, pyqtSignal
from PyQt6.QtGui import QFont
from .client import Dracula


# ============================================================
# WORKER THREAD — runs Gemini request in background
# so the UI doesn't freeze while waiting for a response
# ============================================================


class Worker(QThread):
    response_ready = pyqtSignal(str)
    error_occurred = pyqtSignal(str)

    def __init__(self, ai: Dracula, message: str):
        super().__init__()
        self.ai = ai
        self.message = message

    def run(self):
        try:
            response = self.ai.chat(self.message)
            self.response_ready.emit(response)

        except Exception as e:
            self.error_occurred.emit(str(e))


# ============================================================
# THEMES
# ============================================================


DARK_THEME = {
    "window_bg": "#1e1e2e",
    "chat_bg": "#181825",
    "user_bubble": "#89b4fa",
    "user_text": "#1e1e2e",
    "ai_bubble": "#313244",
    "ai_text": "#cdd6f4",
    "input_bg": "#313244",
    "input_text": "#cdd6f4",
    "button_bg": "#89b4fa",
    "button_text": "#1e1e2e",
    "button_hover": "#74c7ec",
    "title_text": "#cdd6f4",
    "subtitle_text": "#6c7086",
}

LIGHT_THEME = {
    "window_bg": "#eff1f5",
    "chat_bg": "#ffffff",
    "user_bubble": "#1e66f5",
    "user_text": "#ffffff",
    "ai_bubble": "#e6e9ef",
    "ai_text": "#4c4f69",
    "input_bg": "#ffffff",
    "input_text": "#4c4f69",
    "button_bg": "#1e66f5",
    "button_text": "#ffffff",
    "button_hover": "#04a5e5",
    "title_text": "#4c4f69",
    "subtitle_text": "#9ca0b0",
}


# ============================================================
# MAIN CHAT WINDOW
# ============================================================


class DraculaChatUI(QMainWindow):
    def __init__(
        self,
        ai: Dracula,
        title: str = "Dracula AI Chat",
        subtitle: str = "Powered by Dracula & Google Gemini",
        theme: str = "dark",
    ):
        super().__init__()
        self.ai = ai
        self.theme = DARK_THEME if theme == "dark" else LIGHT_THEME
        self.title = title
        self.subtitle = subtitle
        self._setup_window()
        self._setup_ui()
        self._apply_theme()

    def _setup_window(self):
        self.setWindowTitle(self.title)
        self.setMinimumSize(600, 700)
        self.resize(700, 800)

    def _setup_ui(self):
        central = QWidget()
        self.setCentralWidget(central)
        layout = QVBoxLayout(central)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)

        # Header
        header = QWidget()
        header_layout = QVBoxLayout(header)
        header_layout.setContentsMargins(20, 15, 20, 15)

        self.title_label = QLabel(self.title)
        self.title_label.setFont(QFont("Segoe UI", 16, QFont.Weight.Bold))

        self.subtitle_label = QLabel(self.subtitle)
        self.subtitle_label.setFont(QFont("Segoe UI", 10))

        header_layout.addWidget(self.title_label)
        header_layout.addWidget(self.subtitle_label)
        layout.addWidget(header)

        # Chat display
        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        self.chat_display.setFont(QFont("Segoe UI", 11))
        self.chat_display.setContentsMargins(10, 10, 10, 10)
        layout.addWidget(self.chat_display, stretch=1)

        # Input area
        input_widget = QWidget()
        input_layout = QHBoxLayout(input_widget)
        input_layout.setContentsMargins(15, 10, 15, 15)
        input_layout.setSpacing(10)

        self.input_field = QLineEdit()
        self.input_field.setPlaceholderText("Type your message here...")
        self.input_field.setFont(QFont("Segoe UI", 11))
        self.input_field.returnPressed.connect(self._send_message)

        self.send_button = QPushButton("Send")
        self.send_button.setFixedSize(90, 45)
        self.send_button.setFont(QFont("Segoe UI", 11, QFont.Weight.Bold))
        self.send_button.setCursor(Qt.CursorShape.PointingHandCursor)
        self.send_button.clicked.connect(self._send_message)

        input_layout.addWidget(self.input_field)
        input_layout.addWidget(self.send_button)
        layout.addWidget(input_widget)

    def _apply_theme(self):
        t = self.theme
        self.setStyleSheet(f"background-color: {t['window_bg']};")

        self.title_label.setStyleSheet(f"color: {t['title_text']};")
        self.subtitle_label.setStyleSheet(f"color: {t['subtitle_text']};")

        self.chat_display.setStyleSheet(
            f"""
            QTextEdit {{
                background-color: {t['chat_bg']};
                border: none;
                padding: 10px;
                color: {t['ai_text']};
            }}
            code {{
                background-color: {t['ai_bubble']};
                color: {t['user_bubble']};
                padding: 2px 6px;
                border-radius: 4px;
                font-family: Consolas, monospace;
                font-size: 12px;
            }}
            pre {{
                background-color: {t['ai_bubble']};
                padding: 10px;
                border-radius: 8px;
                font-family: Consolas, monospace;
                font-size: 12px;
            }}
        """
        )

        self.input_field.setStyleSheet(
            f"""
            QLineEdit {{
                background-color: {t['input_bg']};
                color: {t['input_text']};
                border: 2px solid {t['ai_bubble']};
                border-radius: 22px;
                padding: 0 15px;
            }}
            QLineEdit:focus {{
                border: 2px solid {t['button_bg']};
            }}
        """
        )

        self.send_button.setStyleSheet(
            f"""
            QPushButton {{
                background-color: {t['button_bg']};
                color: {t['button_text']};
                border: none;
                border-radius: 22px;
            }}
            QPushButton:hover {{
                background-color: {t['button_hover']};
            }}
            QPushButton:disabled {{
                background-color: {t['ai_bubble']};
                color: {t['subtitle_text']};
            }}
        """
        )

    def _send_message(self):
        message = self.input_field.text().strip()

        if not message:
            return

        self.input_field.clear()
        self.send_button.setEnabled(False)
        self.input_field.setEnabled(False)

        self._add_message("You", message, is_user=True)
        self._add_message("Gemini", "Thinking...", is_user=False)

        self.worker = Worker(self.ai, message)
        self.worker.response_ready.connect(self._on_response)
        self.worker.error_occurred.connect(self._on_error)
        self.worker.start()

    def _on_response(self, response: str):
        self._replace_last_message("Gemini", response, is_user=False)
        self.send_button.setEnabled(True)
        self.input_field.setEnabled(True)
        self.input_field.setFocus()

    def _on_error(self, error: str):
        self._replace_last_message("Gemini", f"❌ Error: {error}", is_user=False)
        self.send_button.setEnabled(True)
        self.input_field.setEnabled(True)

    def _add_message(self, sender: str, message: str, is_user: bool):
        import markdown

        t = self.theme
        bubble_color = t["user_bubble"] if is_user else t["ai_bubble"]
        text_color = t["user_text"] if is_user else t["ai_text"]
        align = "right" if is_user else "left"
        emoji = "👤" if is_user else "🤖"

        if not is_user:
            formatted_message = markdown.markdown(
                message, extensions=["fenced_code", "codehilite", "tables"]
            )
        else:
            formatted_message = message

        html = f"""
        <div style="text-align: {align}; margin: 8px 5px;">
            <span style="
                display: inline-block;
                background-color: {bubble_color};
                color: {text_color};
                padding: 10px 15px;
                border-radius: 18px;
                max-width: 75%;
                font-size: 13px;
                line-height: 1.5;
            ">
                <b>{emoji} {sender}</b><br>{formatted_message}
            </span>
        </div>
        """
        self.chat_display.append(html)
        self.chat_display.verticalScrollBar().setValue(
            self.chat_display.verticalScrollBar().maximum()
        )

    def _replace_last_message(self, sender: str, message: str, is_user: bool):
        cursor = self.chat_display.textCursor()
        cursor.movePosition(cursor.MoveOperation.End)
        self.chat_display.setTextCursor(cursor)
        self.chat_display.append("")

        content = self.chat_display.toHtml()
        last_idx = content.rfind("Thinking...")
        if last_idx != -1:
            self.chat_display.clear()
            clean = content[:last_idx].rsplit("<div", 1)[0]
            self.chat_display.setHtml(clean)

        self._add_message(sender, message, is_user)


# ============================================================
# LAUNCH FUNCTION
# ============================================================


def launch(
    ai: Dracula,
    title: str = "Dracula AI Chat 🧛",
    subtitle: str = "Powered by Dracula & Google Gemini",
    theme: str = "dark",
):
    app = QApplication(sys.argv)
    window = DraculaChatUI(ai=ai, title=title, subtitle=subtitle, theme=theme)
    window.show()
    sys.exit(app.exec())
