from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QWidget, QVBoxLayout, QListWidget, QListWidgetItem, QLabel
from app.ui.widgets.chat_list_item_widget import ChatListItemWidget


class SearchResultsView(QWidget):
    result_selected = Signal(dict)
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        self.list = QListWidget()
        self.list.setUniformItemSizes(False)
        self.list.setSpacing(2)
        self.list.itemClicked.connect(self._on_item_clicked)
        layout.addWidget(self.list)

    def clear(self):
        self.list.clear()

    def populate(self, data):
        """data: SearchData (users, groups, channels, messages)."""
        self.clear()
        # Если пусто — показать заглушку
        users = getattr(data, 'users', []) or []
        groups = getattr(data, 'groups', []) or []
        channels = getattr(data, 'channels', []) or []
        messages = getattr(data, 'messages', []) or []
        if not users and not groups and not channels and not messages:
            self._show_empty_state("Ничего не нашли")
            return

        # Users
        users = users
        if users:
            self._add_section_header("Пользователи")
            for u in users:
                title = u.login
                subtitle = u.full_name or u.custom_name or "Пользователь"
                self._add_chat_like_item(title, subtitle, timestamp="", payload={"type": "user", "user_id": str(u.user_id)})

        # Groups
        groups = groups
        if groups:
            self._add_section_header("Беседы")
            for g in groups:
                title = g.get("title") if isinstance(g, dict) else getattr(g, "title", "")
                self._add_chat_like_item(title or "Группа", "Беседа", timestamp="", payload={"type": "group", "chat_id": str((g.get("chat_id") if isinstance(g, dict) else getattr(g, "chat_id", "")))})

        # Channels
        channels = channels
        if channels:
            self._add_section_header("Паблики")
            for ch in channels:
                title = ch.get("title") if isinstance(ch, dict) else getattr(ch, "title", "")
                self._add_chat_like_item(title or "Паблик", "Паблик", timestamp="", payload={"type": "channel", "channel_id": str((ch.get("channel_id") if isinstance(ch, dict) else getattr(ch, "channel_id", "")))})

        # Messages
        messages = messages
        if messages:
            self._add_section_header("Сообщения")
            for m in messages:
                content = m.get("content") if isinstance(m, dict) else getattr(m, "content", "")
                self._add_chat_like_item((content or "(пусто)"), "Сообщение", timestamp="", payload={"type": "message", "message_id": str((m.get("message_id") if isinstance(m, dict) else getattr(m, "message_id", "")))})

    def _add_section_header(self, text: str):
        item = QListWidgetItem()
        item.setFlags(Qt.ItemIsEnabled)
        # Оборачиваем в контейнер, чтобы занять всю ширину и корректно задать высоту
        container = QWidget()
        lay = QVBoxLayout(container)
        lay.setContentsMargins(12, 6, 12, 6)
        lay.setSpacing(0)
        label = QLabel(text)
        label.setStyleSheet("color: #8e8e93; font-weight: 600;")
        label.setWordWrap(False)
        lay.addWidget(label)
        # Задать sizeHint, чтобы не обрезалось
        item.setSizeHint(container.sizeHint())
        self.list.addItem(item)
        self.list.setItemWidget(item, container)

    def _add_two_line_item(self, title: str, subtitle: str = "", payload=None):
        w = QWidget()
        v = QVBoxLayout(w)
        v.setContentsMargins(12, 8, 12, 8)
        v.setSpacing(2)
        l1 = QLabel(title)
        l1.setObjectName("ResultTitle")
        l2 = QLabel(subtitle)
        l2.setObjectName("ResultSubtitle")
        l2.setStyleSheet("color: #8e8e93;")
        v.addWidget(l1)
        if subtitle:
            v.addWidget(l2)

        item = QListWidgetItem()
        item.setData(Qt.UserRole, payload)
        self.list.addItem(item)
        self.list.setItemWidget(item, w)

    def _add_chat_like_item(self, title: str, last_line: str, timestamp: str = "", payload=None):
        widget = ChatListItemWidget(companion_name=title, last_message=last_line, timestamp=timestamp, avatar_path=None, unread_count=0)
        item = QListWidgetItem()
        item.setSizeHint(widget.sizeHint())
        item.setData(Qt.UserRole, payload)
        self.list.addItem(item)
        self.list.setItemWidget(item, widget)

    def _on_item_clicked(self, item: QListWidgetItem):
        data = item.data(Qt.UserRole)
        if data is not None:
            self.result_selected.emit(data)

    def _show_empty_state(self, text: str):
        item = QListWidgetItem()
        item.setFlags(Qt.ItemIsEnabled)
        container = QWidget()
        lay = QVBoxLayout(container)
        lay.setContentsMargins(0, 40, 0, 0)
        lay.setSpacing(0)
        label = QLabel(text)
        label.setAlignment(Qt.AlignCenter)
        label.setStyleSheet("font-size: 18px; color: #8e8e93;")
        lay.addWidget(label)
        item.setSizeHint(container.sizeHint())
        self.list.addItem(item)
        self.list.setItemWidget(item, container)
