"""Rich display utilities for Todo CLI."""

from datetime import datetime
from typing import Optional

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

from .models import Todo, Priority, Status
from .config import get_config


def get_console() -> Console:
    """Get console configured based on color_scheme setting."""
    config = get_config()
    scheme = config.color_scheme.lower()

    if scheme == "none":
        return Console(no_color=True)
    elif scheme == "light":
        # Light theme with adjusted colors for light backgrounds
        light_theme = Theme({
            "info": "blue",
            "warning": "yellow",
            "error": "red",
            "success": "green",
            "dim": "bright_black",
        })
        return Console(theme=light_theme)
    elif scheme == "dark":
        # Dark theme (default Rich colors work well on dark backgrounds)
        return Console()
    else:  # auto
        return Console()




PRIORITY_COLORS = {
    Priority.P0: "bold red",
    Priority.P1: "yellow",
    Priority.P2: "blue",
    Priority.P3: "dim",
}

PRIORITY_ICONS = {
    Priority.P0: "🔴",
    Priority.P1: "🟡",
    Priority.P2: "🔵",
    Priority.P3: "⚪",
}

STATUS_ICONS = {
    Status.TODO: "○",
    Status.DOING: "◐",
    Status.DONE: "●",
}


def format_due_date(todo: Todo) -> Text:
    """Format due date with overdue highlighting."""
    if not todo.due_date:
        return Text("-", style="dim")

    config = get_config()
    date_str = todo.due_date.strftime(config.get_date_format_str())
    if todo.is_overdue:
        return Text(f"⚠️ {date_str}", style="bold red")

    # Check if due today
    if todo.due_date.date() == datetime.now().date():
        return Text(f"📅 {date_str}", style="yellow")

    return Text(date_str)


def display_todos(todos: list[Todo], title: str = "Todos"):
    """Display todos in a rich table."""
    if not todos:
        get_console().print("[dim]No todos found.[/dim]")
        return

    # Get ProjectManager to resolve project_ids to names
    from .projects import ProjectManager
    pm = ProjectManager(get_config().get_db_path())

    table = Table(title=title, show_header=True, header_style="bold cyan")

    table.add_column("ID", style="dim", width=4)
    table.add_column("P", width=3)
    table.add_column("Status", width=6)
    table.add_column("Task", no_wrap=False, overflow="fold")
    table.add_column("Project", width=12)
    table.add_column("Tags", width=15)
    table.add_column("Time", width=10)
    table.add_column("Due", width=12)

    for todo in todos:
        priority_icon = PRIORITY_ICONS[todo.priority]
        status_icon = STATUS_ICONS[todo.status]

        # Style task based on status
        task_style = ""
        if todo.status == Status.DONE:
            task_style = "dim strike"
        elif todo.is_tracking:
            task_style = "bold green"

        # Format time with tracking indicator
        time_str = todo.format_time()
        if todo.is_tracking:
            time_str = f"⏱️ {time_str}"

        # Format tags
        tags_str = ", ".join(todo.tags) if todo.tags else "-"

        # Resolve project_id to project name (prefer project_id over legacy project string)
        project_name = "-"
        if todo.project_id:
            project_obj = pm.get_project(todo.project_id)
            if project_obj:
                project_name = project_obj.name
        elif todo.project:
            # Fallback to legacy project string for backwards compatibility
            project_name = todo.project

        table.add_row(
            str(todo.id),
            priority_icon,
            status_icon,
            Text(todo.task, style=task_style) if task_style else Text(todo.task),
            project_name,
            tags_str,
            time_str,
            format_due_date(todo),
        )

    get_console().print(table)


def display_todo_detail(todo: Todo):
    """Display detailed view of a single todo."""
    config = get_config()
    date_fmt = config.get_date_format_str()
    time_fmt = config.get_time_format_str()
    datetime_fmt = f"{date_fmt} {time_fmt}"

    priority_color = PRIORITY_COLORS[todo.priority]
    priority_icon = PRIORITY_ICONS[todo.priority]

    # Resolve project_id to project name
    from .projects import ProjectManager
    pm = ProjectManager(config.get_db_path())
    project_name = 'None'
    if todo.project_id:
        project_obj = pm.get_project(todo.project_id)
        if project_obj:
            project_name = project_obj.name
    elif todo.project:
        project_name = todo.project

    content = f"""
[bold]Task:[/bold] {todo.task}
[bold]Priority:[/bold] [{priority_color}]{priority_icon} {todo.priority}[/{priority_color}]
[bold]Status:[/bold] {STATUS_ICONS[todo.status]} {todo.status.value}
[bold]Project:[/bold] {project_name}
[bold]Tags:[/bold] {', '.join(todo.tags) if todo.tags else 'None'}
[bold]Due Date:[/bold] {todo.due_date.strftime(datetime_fmt) if todo.due_date else 'None'}
[bold]Created:[/bold] {todo.created_at.strftime(datetime_fmt)}
[bold]Completed:[/bold] {todo.completed_at.strftime(datetime_fmt) if todo.completed_at else 'Not completed'}
[bold]Time Spent:[/bold] {todo.format_time()}{'  ⏱️ Currently tracking' if todo.is_tracking else ''}
"""

    title = f"Todo #{todo.id}"
    if todo.is_overdue:
        title += " [bold red]OVERDUE[/bold red]"

    get_console().print(Panel(content.strip(), title=title, border_style="cyan"))


def display_stats(stats: dict):
    """Display todo statistics."""
    total_seconds = stats["total_time_seconds"]
    hours, remainder = divmod(total_seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    time_str = f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}"

    table = Table(title="Statistics", show_header=False, box=None)
    table.add_column("Metric", style="cyan")
    table.add_column("Value", style="bold")

    table.add_row("Total Todos", str(stats["total"]))
    table.add_row("  Todo", str(stats["todo"]))
    table.add_row("  In Progress", str(stats["doing"]))
    table.add_row("  Completed", str(stats["done"]))
    table.add_row("Total Time Tracked", time_str)

    get_console().print(table)


def success(message: str):
    """Display success message."""
    get_console().print(f"[green]✓[/green] {message}")


def error(message: str):
    """Display error message."""
    get_console().print(f"[red]✗[/red] {message}")


def warning(message: str):
    """Display warning message."""
    get_console().print(f"[yellow]⚠[/yellow] {message}")


def info(message: str):
    """Display info message."""
    get_console().print(f"[blue]ℹ[/blue] {message}")


def display_projects(projects: list):
    """Display list of projects in a table.

    Args:
        projects: List of Project objects
    """
    console = get_console()

    table = Table(title="Projects", show_header=True)
    table.add_column("Name", style="cyan", no_wrap=True)
    table.add_column("Description", style="dim")
    table.add_column("Tasks", justify="right")
    table.add_column("Completed", justify="right")
    table.add_column("Progress", justify="right")

    for project in projects:
        # Calculate progress bar
        if project.total_tasks > 0:
            progress = project.completed_tasks / project.total_tasks
            bar_length = 10
            filled = int(progress * bar_length)
            bar = "█" * filled + "░" * (bar_length - filled)
            progress_text = f"{bar} {progress*100:.0f}%"
        else:
            progress_text = "No tasks"

        # Apply color if set
        name_text = f"[{project.color}]{project.name}[/{project.color}]" if project.color else project.name

        table.add_row(
            name_text,
            project.description or "",
            str(project.total_tasks),
            str(project.completed_tasks),
            progress_text
        )

    console.print(table)


def display_project_detail(stats: dict):
    """Display detailed project information.

    Args:
        stats: Dictionary with project statistics from ProjectManager.get_project_stats()
    """
    console = get_console()
    project = stats['project']

    # Create project header
    title = f"📁 {project.name}"
    if project.color:
        title = f"[{project.color}]{title}[/{project.color}]"

    # Build detail text
    details = []

    if project.description:
        details.append(f"[dim]{project.description}[/dim]\n")

    details.append(f"[bold]Statistics:[/bold]")
    details.append(f"  Total Tasks: {stats['total_tasks']}")
    details.append(f"  Completed: {stats['completed_tasks']}")
    details.append(f"  Active: {stats['active_tasks']}")

    if stats['total_tasks'] > 0:
        details.append(f"  Completion Rate: {stats['completion_rate']:.1f}%")

    if stats['total_time_seconds'] > 0:
        hours = stats['total_time_seconds'] / 3600
        details.append(f"  Time Spent: {hours:.1f}h")

    if stats['earliest_due_date']:
        due_date = stats['earliest_due_date']
        config = get_config()
        date_str = due_date.strftime(config.get_date_format())
        details.append(f"  Next Due Date: {date_str}")

    if stats['priority_breakdown']:
        details.append(f"\n[bold]Priority Breakdown:[/bold]")
        priority_names = {0: "P0 (Urgent)", 1: "P1 (High)", 2: "P2 (Normal)", 3: "P3 (Low)"}
        for priority, count in sorted(stats['priority_breakdown'].items()):
            priority_name = priority_names.get(priority, f"P{priority}")
            details.append(f"  {priority_name}: {count}")

    panel = Panel(
        "\n".join(details),
        title=title,
        border_style="cyan"
    )

    console.print(panel)
