from PySide6.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QLabel
from PySide6.QtGui import QPixmap, QPainter, QColor, QBrush
from PySide6.QtCore import Qt
from app.core.theme import theme_manager

class ChatListItemWidget(QWidget):
    def __init__(self, companion_name, last_message, timestamp, avatar_path=None, unread_count=0):
        super().__init__()
        # Ensure fully transparent background for the item widget
        self.setAutoFillBackground(False)
        self.setStyleSheet("background-color: transparent;")
        self.init_ui(companion_name, last_message, timestamp, avatar_path, unread_count)
        self.update_theme()
        # Ensure badge shape reflects current count
        self._update_unread_badge_shape()

    def init_ui(self, companion_name, last_message, timestamp, avatar_path, unread_count):
        """Инициализирует пользовательский интерфейс виджета."""
        main_layout = QHBoxLayout(self)
        # Reduce right margin to bring unread badge closer to edge
        main_layout.setContentsMargins(10, 5, 6, 5)
        main_layout.setSpacing(10)

        # Аватар
        self.avatar_label = QLabel()
        self.set_avatar(avatar_path)
        main_layout.addWidget(self.avatar_label)

        # Центральная часть: имя и последнее сообщение
        info_layout = QVBoxLayout()
        info_layout.setSpacing(2)
        
        self.name_label = QLabel(companion_name)
        self.last_message_label = QLabel(last_message)
        
        info_layout.addWidget(self.name_label)
        info_layout.addWidget(self.last_message_label)
        info_layout.addStretch()

        # Правая часть: время и количество непрочитанных
        meta_layout = QVBoxLayout()
        meta_layout.setSpacing(2)
        meta_layout.setAlignment(Qt.AlignRight)
        meta_layout.setContentsMargins(0, 0, 0, 0)

        self.timestamp_label = QLabel(timestamp)
        self.unread_label = QLabel(str(unread_count) if unread_count > 0 else "")
        self.unread_label.setAlignment(Qt.AlignCenter)
        self.unread_label.setMargin(0)
        self.unread_label.setContentsMargins(0, 0, 0, 0)
        
        meta_layout.addWidget(self.timestamp_label)
        meta_layout.addWidget(self.unread_label)
        meta_layout.addStretch()

        main_layout.addLayout(info_layout)
        # Push metadata (time + unread) to the far right
        main_layout.addStretch(1)
        main_layout.addLayout(meta_layout)

        self.update_theme()

    def update_theme(self):
        """Обновляет стили виджета в соответствии с текущей темой."""
        palette = theme_manager.get_current_palette()
        
        self.name_label.setStyleSheet(f"font-weight: bold; font-size: 11pt; color: {palette['text']}; background-color: transparent;")
        self.last_message_label.setStyleSheet(f"font-size: 9pt; color: {palette['text_secondary']}; background-color: transparent;")
        self.timestamp_label.setStyleSheet(f"font-size: 8pt; color: {palette['text_secondary']}; background-color: transparent;")
        
        unread_bg = palette['accent']
        unread_text = "#ffffff"
        # Base style; specific shape applied in _update_unread_badge_shape
        self._unread_base_style = (
            f"font-size: 8pt; font-weight: bold; color: {unread_text}; "
            f"background-color: {unread_bg};"
        )
        self._update_unread_badge_shape()
        self.unread_label.setVisible(self.unread_label.text() != "")

    def _update_unread_badge_shape(self):
        text = self.unread_label.text()
        if not hasattr(self, "_unread_base_style"):
            self._unread_base_style = ""
        # Default hidden when empty is handled by caller
        if not text:
            self.unread_label.setVisible(False)
            return
        # Single digit -> perfect circle
        if len(text) == 1:
            size = 18
            self.unread_label.setFixedSize(size, size)
            self.unread_label.setStyleSheet(
                self._unread_base_style + f" border-radius: {size//2}px; padding: 0;"
            )
        else:
            # Multiple digits -> pill
            height = 18
            self.unread_label.setFixedHeight(height)
            self.unread_label.setMinimumWidth(height)
            self.unread_label.setMaximumWidth(200)
            self.unread_label.setStyleSheet(
                self._unread_base_style + f" border-radius: {height//2}px; padding: 0 6px;"
            )


    def set_avatar(self, image_path):
        """Устанавливает аватар. Если путь не указан, создает заглушку."""
        if image_path:
            pixmap = QPixmap(image_path)
        else:
            # Создаем круглую заглушку
            pixmap = QPixmap(40, 40)
            pixmap.fill(Qt.transparent)
            painter = QPainter(pixmap)
            painter.setRenderHint(QPainter.Antialiasing)
            painter.setBrush(QBrush(QColor("#e0e0e0")))
            painter.setPen(Qt.NoPen)
            painter.drawEllipse(0, 0, 40, 40)
            painter.end()
            
        self.avatar_label.setPixmap(pixmap)
        self.avatar_label.setFixedSize(40, 40)
        self.avatar_label.setScaledContents(True)

    def paintEvent(self, event):
        """Переопределяем для скругления углов аватара, если это изображение."""
        # Этот метод можно будет доработать для создания круглых аватаров из картинок
        super().paintEvent(event)
