"""ProgressPanel - Project progress display widget.

Contract: CNT-TUI-WDG-002
Traceability: UX-001, UI-002
"""

from pathlib import Path

from textual.reactive import reactive
from textual.widgets import Static

from laida_cli.services.detect_state import DetectStateService, ProjectState


class ProgressPanel(Static):
    """Widget displaying project progress and next step.

    Integrates with DetectStateService to show:
    - Current phase/step
    - Progress bar (steps completed / total steps)
    - Next action to take
    """

    DEFAULT_CSS = """
    ProgressPanel {
        border: round #8b5cf6;
        padding: 1 2;
        margin: 0 1 1 1;
        height: auto;
    }
    """

    # Reactive attributes for automatic UI updates
    current_phase: reactive[int] = reactive(0)
    current_step: reactive[int] = reactive(0)
    completed_steps: reactive[int] = reactive(0)
    is_complete: reactive[bool] = reactive(False)

    TOTAL_STEPS = 20  # 5 phases × 4 steps

    def __init__(
        self,
        project_path: Path,
        state_service: DetectStateService | None = None,
    ) -> None:
        """Initialize with project path and optional state service.

        Args:
            project_path: Path to LAIDA project
            state_service: Service for state detection (creates default if None)
        """
        super().__init__()
        self._project_path = project_path
        self._state_service = state_service or DetectStateService()
        self._last_state: ProjectState | None = None

    def on_mount(self) -> None:
        """Start periodic updates when widget is mounted."""
        # Update every 2 seconds
        self.set_interval(2.0, self._refresh_state)
        # Initial update
        self._refresh_state()

    def _refresh_state(self) -> None:
        """Fetch latest project state and update reactive attributes."""
        state = self._state_service.detect(self._project_path)
        self._last_state = state

        self.current_phase = state.next_phase
        self.current_step = state.next_step
        self.is_complete = state.is_complete

        # Calculate completed steps
        if state.is_complete:
            self.completed_steps = self.TOTAL_STEPS
        elif state.last_completed_phase is None:
            self.completed_steps = 0
        else:
            phase = state.last_completed_phase
            step = state.last_completed_step or 0
            self.completed_steps = (phase * 4) + step + 1

    def render(self) -> str:
        """Render the progress panel content."""
        # Progress bar
        progress_pct = (self.completed_steps / self.TOTAL_STEPS) * 100
        bar_width = 20
        filled = int((self.completed_steps / self.TOTAL_STEPS) * bar_width)
        bar = "█" * filled + "░" * (bar_width - filled)

        # Status text
        if self.is_complete:
            status = "[bold #10b981]✔ Complete[/]"
            next_action = "All phases finished"
        else:
            status = f"[#a78bfa]Phase {self.current_phase}[/] [#64748b]Step {self.current_step}[/]"
            step_name = self._state_service.get_step_name(self.current_phase, self.current_step)
            next_action = f"Next: {step_name}"

        return (
            f"[bold #a78bfa]📊 PROJECT PROGRESS[/]\n\n"
            f"{status}\n"
            f"[#5eead4]{bar}[/] {progress_pct:.0f}%\n"
            f"[#64748b]{self.completed_steps}/{self.TOTAL_STEPS} steps completed[/]\n\n"
            f"[#94a3b8]{next_action}[/]"
        )

    @property
    def project_state(self) -> ProjectState | None:
        """Get the last detected project state."""
        return self._last_state
