from PySide6.QtGui import Qt
from PySide6.QtWidgets import QWidget, QVBoxLayout, QPushButton, QHBoxLayout

from clochette.domain.entity.configuration.CalendarConfiguration import CalendarConfiguration
from clochette.framework.qt.Signal import InSolidSignal, OutHollowSignal
from clochette.presentation.widget.QList import QList, ListItem


class QCalendarListView(QWidget):
    """Pure view widget for displaying and managing calendar list"""

    set_calendars: InSolidSignal[list[CalendarConfiguration]]
    on_add_clicked: OutHollowSignal
    on_edit_clicked: OutHollowSignal
    on_delete_clicked: OutHollowSignal

    _list_calendar: QList[CalendarConfiguration]

    def __init__(self) -> None:
        super().__init__()

        self.set_calendars = InSolidSignal(self._set_calendars)
        self.on_add_clicked = OutHollowSignal()
        self.on_edit_clicked = OutHollowSignal()
        self.on_delete_clicked = OutHollowSignal()

        main_layout = QHBoxLayout()
        self.setLayout(main_layout)

        self._list_calendar = QList()

        # Create the buttons layout
        buttons_layout = QVBoxLayout()
        buttons_layout.setAlignment(Qt.AlignmentFlag.AlignTop)

        # Create the Add button
        add_button = QPushButton(self.tr("Add"))
        add_button.clicked.connect(lambda: self.on_add_clicked.send())
        buttons_layout.addWidget(add_button)

        # Create the Edit button
        edit_button = QPushButton(self.tr("Edit"))
        edit_button.clicked.connect(lambda: self.on_edit_clicked.send())
        buttons_layout.addWidget(edit_button)

        # Create the Delete button
        delete_button = QPushButton(self.tr("Delete"))
        delete_button.clicked.connect(lambda: self.on_delete_clicked.send())
        buttons_layout.addWidget(delete_button)

        # Add the list widget and the buttons layout to the main layout
        main_layout.addWidget(self._list_calendar)
        main_layout.addLayout(buttons_layout)
        main_layout.addStretch()

    def _set_calendars(self, calendars: list[CalendarConfiguration]):
        """Update the calendar list with new data"""
        self._list_calendar.clear()
        for calendar in calendars:
            self._list_calendar.add(ListItem(calendar.name, calendar))

        calendar = self._list_calendar.get_selected_item()
        if calendars and calendar is None:
            self._list_calendar.setCurrentRow(0)

    @property
    def selected_calendar(self) -> CalendarConfiguration | None:
        """Get the currently selected calendar"""
        return self._list_calendar.get_selected_item()
