"""Main content panel showing the current step's UI."""

from __future__ import annotations

import asyncio

from textual.app import ComposeResult
from textual.widget import Widget
from textual.widgets import Static, RichLog
from textual.containers import VerticalScroll, Container
from textual.message import Message

from easyclaw_tui.state import InstallState


class StepPanel(Widget):
    """Scrollable panel showing current step content and log output."""

    class FormSubmitted(Message):
        """The user clicked Continue on a form."""

    def __init__(self, state: InstallState) -> None:
        super().__init__()
        self.state = state
        self._form_event: asyncio.Event | None = None

    def compose(self) -> ComposeResult:
        yield Static("Step 1 — Pre-flight Checks", id="step-title")
        yield Container(id="form-area")
        yield RichLog(id="step-log", wrap=True, highlight=True, markup=True)

    @property
    def log_widget(self) -> RichLog:
        return self.query_one("#step-log", RichLog)

    @property
    def form_area(self) -> Container:
        return self.query_one("#form-area", Container)

    def set_step(self, step_num: int, title: str) -> None:
        """Update the panel title for a new step."""
        self.query_one("#step-title", Static).update(
            f"Step {step_num} — {title}"
        )

    # ─── Form management ────────────────────────────────

    async def show_form(self, widget: Widget) -> None:
        """Mount a form widget into the form area."""
        self._form_event = asyncio.Event()
        await self.form_area.mount(widget)

    async def wait_for_submit(self) -> None:
        """Block until FormSubmitted is received."""
        if self._form_event:
            await self._form_event.wait()

    async def clear_form(self) -> None:
        """Remove all widgets from the form area."""
        await self.form_area.remove_children()
        self._form_event = None

    def on_step_panel_form_submitted(self, event: FormSubmitted) -> None:
        """Handle form submission by setting the event."""
        if self._form_event:
            self._form_event.set()

    # ─── Log helpers ─────────────────────────────────────

    def log_ok(self, msg: str) -> None:
        self.log_widget.write(f"  [green]✓[/green] {msg}")

    def log_warn(self, msg: str) -> None:
        self.log_widget.write(f"  [yellow]⚠[/yellow] {msg}")

    def log_error(self, msg: str) -> None:
        self.log_widget.write(f"  [red]✗[/red] {msg}")

    def log_info(self, msg: str) -> None:
        self.log_widget.write(f"  [cyan]→[/cyan] {msg}")

    def log_raw(self, msg: str) -> None:
        self.log_widget.write(msg)

    def clear_log(self) -> None:
        self.log_widget.clear()
