"""Rich display components for the CLI."""

from __future__ import annotations

import math
from typing import TYPE_CHECKING

from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

if TYPE_CHECKING:
    from lockin.config import Config, Profile, Schedule
    from lockin.presets import Preset
    from lockin.session import Session

console = Console()
error_console = Console(stderr=True)


def format_duration(seconds: float) -> str:
    """Format seconds into human-readable duration string."""
    total = int(seconds)
    if total < 60:
        return f"{total}s"
    hours, remainder = divmod(total, 3600)
    minutes, secs = divmod(remainder, 60)
    parts: list[str] = []
    if hours:
        parts.append(f"{hours}h")
    if minutes:
        parts.append(f"{minutes}m")
    if secs:
        parts.append(f"{secs}s")
    return " ".join(parts)


def show_status(session: Session | None) -> None:
    """Display current session status."""
    if session is None:
        panel = Panel(
            "[dim]No active focus session.[/dim]\n\n"
            "Start one with: [bold]sudo lockin start <profile> --duration 2h[/bold]",
            title="[bold]Lockin Status[/bold]",
            border_style="dim",
        )
        console.print(panel)
        return

    remaining = session.remaining_seconds
    elapsed = session.elapsed_seconds
    progress = min(elapsed / session.duration_seconds, 1.0) if session.duration_seconds > 0 else 1.0

    # Progress bar
    bar_width = 30
    filled = int(bar_width * progress)
    bar = "[green]" + "█" * filled + "[/green]" + "[dim]░[/dim]" * (bar_width - filled)

    domains_count = len(session.blocked_domains)
    apps_count = len(session.blocked_apps)

    content = (
        f"[bold green]Session Active[/bold green]\n\n"
        f"  Profile:   [bold]{session.profile_name}[/bold]\n"
        f"  Remaining: [bold yellow]{format_duration(remaining)}[/bold yellow]\n"
        f"  Progress:  {bar} {math.floor(progress * 100)}%\n"
        f"  Blocking:  [cyan]{domains_count}[/cyan] domains, [cyan]{apps_count}[/cyan] apps\n"
    )

    panel = Panel(content, title="[bold]Lockin Status[/bold]", border_style="green")
    console.print(panel)


def show_presets(presets: list[Preset]) -> None:
    """Display built-in presets."""
    table = Table(title="Built-in Presets", show_lines=True)
    table.add_column("Name", style="bold cyan", min_width=15)
    table.add_column("Description", style="dim")
    table.add_column("Domains", style="white")
    table.add_column("Apps", style="yellow")

    for preset in presets:
        domains_str = ", ".join(preset.domains)
        apps_str = ", ".join(preset.apps) if preset.apps else "[dim]none[/dim]"
        table.add_row(preset.name, preset.description, domains_str, apps_str)

    console.print(table)


def show_profiles(profiles: dict[str, Profile]) -> None:
    """Display all profiles."""
    if not profiles:
        console.print("[dim]No profiles configured. Create one with:[/dim]")
        console.print("[bold]  lockin profile create <name> --preset social[/bold]")
        return

    table = Table(title="Profiles", show_lines=True)
    table.add_column("Name", style="bold cyan", min_width=12)
    table.add_column("Presets", style="green")
    table.add_column("Custom Sites", style="white")
    table.add_column("Apps", style="yellow")

    for name, profile in profiles.items():
        presets_str = ", ".join(profile.presets) if profile.presets else "[dim]none[/dim]"
        sites_str = ", ".join(profile.custom_sites) if profile.custom_sites else "[dim]none[/dim]"
        apps_str = ", ".join(profile.blocked_apps) if profile.blocked_apps else "[dim]none[/dim]"
        table.add_row(name, presets_str, sites_str, apps_str)

    console.print(table)


def show_profile_detail(profile: Profile) -> None:
    """Display a single profile in detail."""
    domains = profile.resolve_domains()
    apps = profile.resolve_apps()

    content = (
        f"  Presets:      [green]{', '.join(profile.presets) or 'none'}[/green]\n"
        f"  Custom Sites: [white]{', '.join(profile.custom_sites) or 'none'}[/white]\n"
        f"  Extra Apps:   [yellow]{', '.join(profile.blocked_apps) or 'none'}[/yellow]\n"
        f"\n"
        f"  [dim]Resolved → {len(domains)} domains, {len(apps)} apps[/dim]"
    )

    panel = Panel(content, title=f"[bold]Profile: {profile.name}[/bold]", border_style="cyan")
    console.print(panel)


def show_schedules(schedules: dict[str, Schedule]) -> None:
    """Display all schedules."""
    if not schedules:
        console.print("[dim]No schedules configured. Create one with:[/dim]")
        console.print("[bold]  lockin schedule create <name> --profile work --days mon,tue --start 09:00 --duration 120[/bold]")
        return

    table = Table(title="Schedules", show_lines=True)
    table.add_column("Name", style="bold cyan")
    table.add_column("Profile", style="green")
    table.add_column("Days", style="white")
    table.add_column("Start", style="yellow")
    table.add_column("Duration", style="magenta")

    for name, schedule in schedules.items():
        days_str = ", ".join(schedule.days)
        table.add_row(
            name,
            schedule.profile,
            days_str,
            schedule.start_time,
            f"{schedule.duration_minutes}m",
        )

    console.print(table)


def show_apps(apps: list[str]) -> None:
    """Display detected macOS apps."""
    table = Table(title=f"Detected macOS Apps ({len(apps)})")
    table.add_column("#", style="dim", width=4)
    table.add_column("App Name", style="bold")

    for i, app in enumerate(apps, 1):
        table.add_row(str(i), app)

    console.print(table)


def show_always_blocked(sites: list[str], apps: list[str]) -> None:
    """Display always-blocked items."""
    if not sites and not apps:
        console.print("[dim]No always-blocked items.[/dim]")
        return

    content = ""
    if sites:
        content += "[bold]Sites:[/bold]\n"
        for site in sites:
            content += f"  • {site}\n"
    if apps:
        content += "[bold]Apps:[/bold]\n"
        for app in apps:
            content += f"  • {app}\n"

    panel = Panel(content.rstrip(), title="[bold]Always Blocked[/bold]", border_style="red")
    console.print(panel)


def print_success(message: str) -> None:
    console.print(f"[bold green]✓[/bold green] {message}")


def print_error(message: str) -> None:
    error_console.print(f"[bold red]✗[/bold red] {message}")


def print_warning(message: str) -> None:
    console.print(f"[bold yellow]![/bold yellow] {message}")


def print_info(message: str) -> None:
    console.print(f"[bold blue]i[/bold blue] {message}")
