"""Detail panel widget showing lesson information."""

from textual.app import ComposeResult
from textual.containers import Container
from textual.widgets import Static

from ..models import Lesson, ChangeType, Timetable


class DetailPanel(Container):
    """
    Panel showing detailed information about the selected lesson.
    
    Displays subject, time, teacher, room, topic, and any changes.
    """
    
    DEFAULT_CSS = """
    DetailPanel {
        height: 8;
        border: round $primary;
        padding: 0 1;
        margin-top: 1;
        overflow-y: auto;
    }
    
    DetailPanel .detail-title {
        text-style: bold;
        color: $text;
    }
    
    DetailPanel .detail-time {
        color: $text-muted;
    }
    
    DetailPanel .detail-row {
        margin-top: 0;
    }
    
    DetailPanel .detail-label {
        color: $text-muted;
        width: 12;
    }
    
    DetailPanel .detail-value {
        color: $text;
    }
    
    DetailPanel .change-info {
        margin-top: 1;
        padding: 0 1;
        border: round $warning;
    }
    
    DetailPanel .change-room {
        border: round $warning;
        color: $warning;
    }
    
    DetailPanel .change-cancelled {
        border: round $error;
        color: $error;
    }
    
    DetailPanel .change-transferred {
        border: round $accent;
        color: $accent;
    }
    
    DetailPanel .change-substitute {
        border: round $secondary;
        color: $secondary;
    }
    
    DetailPanel .empty-message {
        color: $text-muted;
        text-style: italic;
    }
    
    DetailPanel .day-off-message {
        color: #7ab8ff;
        text-style: italic;
    }
    """
    
    def __init__(
        self,
        id: str | None = None,
        classes: str | None = None,
    ) -> None:
        super().__init__(id=id, classes=classes)
        self._lesson: Lesson | None = None
        self._day_name: str = ""
        self._day_date: str = ""
        self._timetable: Timetable | None = None
        self._is_day_off: bool = False
        self._day_off_text: str = ""
    
    def compose(self) -> ComposeResult:
        """Create child widgets."""
        yield Static("Vyberte hodinu pro zobrazení detailů", classes="empty-message", id="detail-content")
    
    def set_timetable(self, timetable: Timetable | None) -> None:
        """Set timetable for time lookups."""
        self._timetable = timetable
    
    def update_lesson(self, lesson: Lesson | None, day_name: str = "", day_date: str = "", is_day_off: bool = False, day_off_text: str = "") -> None:
        """Update the displayed lesson information."""
        self._lesson = lesson
        self._day_name = day_name
        self._day_date = day_date
        self._is_day_off = is_day_off
        self._day_off_text = day_off_text
        self._refresh_content()
    
    def _refresh_content(self) -> None:
        """Refresh the detail content display."""
        content = self.query_one("#detail-content", Static)
        
        # Check for day-off first (from grid, not lesson)
        if self._is_day_off:
            text = self._day_off_text or "Volno"
            date_info = f"{self._day_name}"
            if self._day_date:
                date_info += f" {self._day_date}"
            content.update(f"[bold]{text}[/bold]\n[dim]{date_info}[/dim]")
            content.set_classes("day-off-message")
            return
        
        if not self._lesson:
            content.update("Vyberte hodinu pro zobrazeni detailu")
            content.set_classes("empty-message")
            return
        
        lesson = self._lesson
        
        # Handle day off in lesson
        if lesson.is_day_off:
            text = lesson.day_off_text or "Volno"
            content.update(f"[bold]{text}[/bold]")
            content.set_classes("day-off-message")
            return
        
        if lesson.is_empty:
            content.update("Prázdná hodina")
            content.set_classes("empty-message")
            return

        
        content.set_classes("")
        
        # Build content
        lines = []
        
        # Title line: Subject | Day Date | Slot (time)
        time_range = ""
        if self._timetable:
            time_range = self._timetable.get_time_range(lesson.slot)
        
        slot_info = f"{lesson.slot}"
        if time_range:
            slot_info += f" ({time_range})"
        
        date_str = f"{self._day_name}"
        if self._day_date:
            date_str += f" {self._day_date}"
        
        title = f"[bold]{lesson.subject}[/bold]"
        if date_str:
            title += f" | {date_str}"
        title += f" | {slot_info}"
        lines.append(title)
        lines.append("")
        
        # Teacher
        if lesson.teacher:
            lines.append(f"[dim]Učitel:[/dim] {lesson.teacher}")
        
        # Room
        if lesson.room:
            lines.append(f"[dim]Učebna:[/dim] {lesson.room}")
        
        # Group
        if lesson.group:
            lines.append(f"[dim]Skupina:[/dim] {lesson.group}")
        
        # Theme/Topic
        if lesson.theme:
            lines.append(f"[dim]Téma:[/dim] {lesson.theme}")
        
        # Change info
        if lesson.change_info:
            lines.append("")
            change_style = self._get_change_style(lesson.change_type)
            indicator = self._get_change_indicator(lesson.change_type)
            lines.append(f"[{change_style}]{indicator} {lesson.change_info}[/{change_style}]")
        
        content.update("\n".join(lines))
    
    def _get_change_style(self, change_type: ChangeType) -> str:
        """Get Rich style for change type."""
        return {
            ChangeType.NONE: "",
            ChangeType.ROOM_CHANGE: "yellow",
            ChangeType.CANCELLED: "red strike",
            ChangeType.TRANSFERRED: "cyan",
            ChangeType.SUBSTITUTE: "magenta",
            ChangeType.OTHER: "yellow",
        }.get(change_type, "")
    
    def _get_change_indicator(self, change_type: ChangeType) -> str:
        """Get text indicator for change type."""
        return {
            ChangeType.NONE: "",
            ChangeType.ROOM_CHANGE: "[Zmena]",
            ChangeType.CANCELLED: "[Zruseno]",
            ChangeType.TRANSFERRED: "[Presun]",
            ChangeType.SUBSTITUTE: "[Suplovani]",
            ChangeType.OTHER: "[Info]",
        }.get(change_type, "")
