"""Interview scheduling and management."""

import httpx
from rich.console import Console
from rich.table import Table

from skilark_cli.client import SkilarkClient
from skilark_cli.config_store import ConfigStore

console = Console()

VALID_TYPES = [
    "behavioral",
    "technical_coding",
    "system_design",
    "product_sense",
    "analytical",
    "case_study",
    "portfolio_review",
    "role_play",
]

USAGE = """\
Usage: skilark interview <subcommand>

Subcommands:
  schedule   Book a mock interview
  list       View your interviews
  cancel     Cancel an interview

Schedule options:
  --role       Role title (required)
  --type       Interview type (required)
  --at         Scheduled time, ISO 8601 (required)
  --invite     Invite code (required)
  --company    Company slug (optional)
  --link       Meeting link, e.g. Zoom/Meet URL (optional)
"""


def dispatch(args: list[str]) -> None:
    """Route interview subcommands to the appropriate handler."""
    store = ConfigStore()
    if store.is_first_run():
        console.print("[dim]Run 'skilark login' first to get started.[/dim]")
        return

    config = store.load()
    client = SkilarkClient(base_url=config["api_url"], user_id=config.get("user_id"))

    if not args:
        console.print(USAGE)
        return

    subcmd, rest = args[0], args[1:]

    if subcmd == "list":
        run_list(client)
    elif subcmd == "schedule":
        _dispatch_schedule(client, rest)
    elif subcmd == "cancel":
        if not rest:
            console.print("[red]Usage: skilark interview cancel <interview-id>[/red]")
            return
        run_cancel(client, rest[0])
    else:
        console.print(f"[red]Unknown subcommand: {subcmd}[/red]")
        console.print(USAGE)


def _dispatch_schedule(client: SkilarkClient, args: list[str]) -> None:
    """Parse schedule flags and delegate to run_schedule."""
    kwargs: dict[str, str] = {}
    flag_map = {
        "--role": "role_title",
        "--type": "interview_type",
        "--at": "scheduled_at",
        "--invite": "invite_code",
        "--company": "company_slug",
        "--link": "meeting_link",
    }
    i = 0
    while i < len(args) - 1:
        if args[i] in flag_map:
            kwargs[flag_map[args[i]]] = args[i + 1]
            i += 2
        else:
            console.print(f"[yellow]Warning: unknown flag '{args[i]}' ignored[/yellow]")
            i += 1

    missing = [
        f
        for f in ("role_title", "interview_type", "scheduled_at", "invite_code")
        if f not in kwargs
    ]
    if missing:
        console.print(
            f"[red]Missing required flags: {', '.join('--' + f.replace('_', '-') for f in missing)}[/red]"
        )
        return

    if kwargs["interview_type"] not in VALID_TYPES:
        console.print(
            f"[red]Invalid type. Valid types: {', '.join(VALID_TYPES)}[/red]"
        )
        return

    run_schedule(client, **kwargs)


def run_schedule(client: SkilarkClient, **kwargs) -> None:
    """Create an interview via the API and display the result."""
    try:
        result = client.create_interview(**kwargs)
        console.print(f"[green]Interview scheduled![/green] ID: {result['id']}")
        console.print(f"  Type: {result.get('interview_type', '')}")
        console.print(f"  When: {result.get('scheduled_at', '')}")
        console.print(f"  Status: {result.get('status', '')}")
    except httpx.HTTPStatusError as exc:
        if exc.response.status_code == 403:
            console.print("[red]Invalid, expired, or already used invite code.[/red]")
        else:
            console.print(f"[red]Failed to schedule interview: {exc}[/red]")
    except Exception as exc:
        console.print(f"[red]Failed to schedule interview: {exc}[/red]")


def run_list(client: SkilarkClient) -> None:
    """Fetch and display the user's interviews in a table."""
    try:
        data = client.list_interviews()
    except Exception as exc:
        console.print(f"[red]Failed to fetch interviews: {exc}[/red]")
        return

    interviews = data.get("interviews", [])
    if not interviews:
        console.print("[dim]No interviews scheduled.[/dim]")
        return

    table = Table(title="Your Interviews")
    table.add_column("ID", style="dim", max_width=8)
    table.add_column("Role")
    table.add_column("Type")
    table.add_column("Scheduled")
    table.add_column("Status")

    for iv in interviews:
        status_style = {
            "scheduled": "cyan",
            "completed": "green",
            "cancelled": "dim",
            "in_progress": "yellow",
        }.get(iv["status"], "")
        table.add_row(
            iv["id"][:8],
            iv["role_title"],
            iv["interview_type"],
            iv["scheduled_at"][:16],
            f"[{status_style}]{iv['status']}[/{status_style}]",
        )

    console.print(table)


def run_cancel(client: SkilarkClient, interview_id: str) -> None:
    """Cancel an interview by ID."""
    try:
        result = client.cancel_interview(interview_id)
        console.print(f"[yellow]Interview {result['id'][:8]} cancelled.[/yellow]")
    except Exception as exc:
        console.print(f"[red]Failed to cancel interview: {exc}[/red]")
