from PySide6.QtWidgets import QWidget, QListWidget, QVBoxLayout, QLabel, QListWidgetItem
from app.core.models.chat_models import PrivateChatListItem

class ChatListView(QWidget):
    def __init__(self, username, chat_items: list[PrivateChatListItem]):
        super().__init__()
        self.setWindowTitle(f"Чаты — {username}")
        self.setMinimumSize(400, 500)

        self.chat_items = chat_items
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        self.label = QLabel("Список чатов:")
        layout.addWidget(self.label)

        self.chat_list = QListWidget()
        self.render_chat_items()
        layout.addWidget(self.chat_list)

        self.setLayout(layout)

    def render_chat_items(self):
        self.chat_list.clear()
        for chat in self.chat_items:
            companion_name = chat.companion_data.get("username", "Без имени") if chat.companion_data else "Неизвестный"
            last_msg = chat.last_message.context if chat.last_message else "Нет сообщений"
            item_text = f"{companion_name} — {last_msg}"
            self.chat_list.addItem(QListWidgetItem(item_text))

    def update_chat_items(self, new_items: list[PrivateChatListItem]):
        self.chat_items = new_items
        self.render_chat_items()
