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

from typing import Optional

class ChatListItemWidget(QWidget):
    def __init__(self, companion_name, last_message, timestamp, avatar_path=None, unread_count=0, is_outgoing: bool = False, is_read: Optional[bool] = None):
        super().__init__()
        # Ensure fully transparent background for the item widget
        self.setAutoFillBackground(False)
        self.setStyleSheet("background-color: transparent;")
        self.is_outgoing = is_outgoing
        self.is_read = is_read
        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, 2, 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)

        # Delivery/read status icon (left of timestamp)
        self.status_label = QLabel("")
        self.status_label.setFixedWidth(12)
        self.status_label.setFixedHeight(14)
        self.status_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.status_label.setContentsMargins(0, 0, 0, 0)
        self.status_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.timestamp_label = QLabel(timestamp)
        self.timestamp_label.setFixedHeight(14)
        self.timestamp_label.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.timestamp_label.setContentsMargins(0, 0, 0, 0)
        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)
        
        # Put status and time on a single row aligned right
        time_row = QHBoxLayout()
        time_row.setSpacing(1)
        time_row.setContentsMargins(0, 0, 0, 0)
        time_row.addWidget(self.status_label)
        time_row.addWidget(self.timestamp_label)
        time_row.addStretch()
        meta_layout.addLayout(time_row)
        
        # Offsets for unread badge anchoring (editable)
        self.unread_offset_right = 6
        self.unread_offset_bottom = 4

        # Add stretch to push next row to the bottom
        meta_layout.addStretch(1)

        # Bottom row: anchor unread badge to bottom-right with margins
        bottom_row = QHBoxLayout()
        bottom_row.setSpacing(0)
        bottom_row.setContentsMargins(0, 0, self.unread_offset_right, self.unread_offset_bottom)
        bottom_row.addStretch(1)
        bottom_row.addWidget(self.unread_label)
        meta_layout.addLayout(bottom_row)

        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;")
        # Status color depends on state; default to secondary
        status_color = palette['text_secondary']
        if getattr(self, 'is_outgoing', False):
            if getattr(self, 'is_read', None) is True:
                status_color = palette['accent']
        self.status_label.setStyleSheet(f"font-size: 7pt; color: {status_color}; background-color: transparent;")
        self._update_status_icon()
        
        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 set_timestamp_tooltip(self, tooltip_text: str):
        try:
            self.timestamp_label.setToolTip(tooltip_text or "")
        except Exception:
            # Be defensive if label not yet created
            pass

    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 _update_status_icon(self):
        # Show ticks only for outgoing messages with a known read state
        if getattr(self, 'is_outgoing', False) and getattr(self, 'is_read', None) is not None:
            if self.is_read:
                self.status_label.setText("✓✓")
            else:
                self.status_label.setText("✓")
            self.status_label.setVisible(True)
        else:
            self.status_label.setVisible(False)


    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)
