"""Archive widget for browsing past entries."""

from typing import List
from textual.widgets import ListView, ListItem, Label
from textual.message import Message
from textual.app import ComposeResult

from ..types import EntryMeta


class EntryListItem(ListItem):
    """A list item for a single entry."""

    def __init__(self, entry: EntryMeta, *args, **kwargs):
        """Initialize entry list item."""
        super().__init__(*args, **kwargs)
        self.entry = entry

    def compose(self) -> ComposeResult:
        """Compose the entry list item."""
        label = f"{self.entry.relative_time} - {self.entry.filename}"
        yield Label(label)


class EmptyListItem(ListItem):
    """A list item for empty state."""

    def __init__(self, *args, **kwargs):
        """Initialize empty list item."""
        super().__init__(*args, **kwargs)
        self.add_class("empty")

    def compose(self) -> ComposeResult:
        """Compose the empty list item."""
        yield Label("No entries yet")


class ArchiveList(ListView):
    """Archive list widget for browsing entries."""

    class EntrySelected(Message):
        """Message sent when an entry is selected."""

        def __init__(self, entry: EntryMeta):
            """Initialize entry selected message."""
            super().__init__()
            self.entry = entry

    def __init__(self, entries: List[EntryMeta], *args, **kwargs):
        """Initialize archive list."""
        super().__init__(*args, **kwargs)
        self.entries = entries

    def compose(self) -> ComposeResult:
        """Compose the archive list with entries."""
        if not self.entries:
            # Show empty state
            yield EmptyListItem()
        else:
            # Group entries by date
            entries_by_date = {}
            for entry in self.entries:
                date = entry.display_date
                if date not in entries_by_date:
                    entries_by_date[date] = []
                entries_by_date[date].append(entry)

            # Render entries grouped by date (newest first)
            for date in sorted(entries_by_date.keys(), reverse=True):
                # Entries for this date (newest first)
                for entry in sorted(
                    entries_by_date[date],
                    key=lambda e: e.filename,
                    reverse=True,
                ):
                    yield EntryListItem(entry)

    async def on_list_view_selected(self, event: ListView.Selected) -> None:
        """Handle entry selection."""
        item = event.item
        if isinstance(item, EntryListItem):
            # Post message to parent screen
            self.post_message(self.EntrySelected(item.entry))
