from __future__ import annotations

from textual import on, work
from textual.app import ComposeResult
from textual.containers import Vertical
from textual.events import Key
from textual.screen import ModalScreen
from textual.widgets import Button, Input, Label, Static


class ProfileViewScreen(ModalScreen[str | None]):
    """View a user's profile. Returns 'edit' if user wants to edit."""

    def __init__(self, user: dict, is_me: bool = False) -> None:
        super().__init__()
        self._user = user
        self._is_me = is_me

    def compose(self) -> ComposeResult:
        u = self._user
        status = u.get("status", "offline")
        online = u.get("is_online", False)
        dot = "[green]\u2022[/]" if online else "[dim]\u2022[/]"
        display = u.get("display_name") or u.get("username", "?")
        username = u.get("username", "?")
        pronouns = u.get("pronouns") or ""
        bio = u.get("bio") or ""
        raw_created = u.get("created_at") or ""
        created = str(raw_created)[:10] if raw_created else ""

        with Vertical(id="profile-modal"):
            yield Label("PROFILE", id="modal-title")
            yield Static(
                f"{dot} [bold]{display}[/]  [dim]@{username}[/]",
                classes="profile-name",
            )
            if pronouns:
                yield Static(f"[dim]{pronouns}[/]", classes="profile-field")
            yield Static(f"[dim]{status}[/]", classes="profile-field")
            if bio:
                yield Static("", classes="profile-spacer")
                yield Static(bio, classes="profile-bio")
            if created:
                yield Static(f"[dim]member since {created}[/]", classes="profile-field")
            if self._is_me:
                yield Static("", classes="profile-spacer")
                yield Button("edit profile", id="edit-profile-btn", variant="primary")

    def on_key(self, event: Key) -> None:
        if event.key == "escape":
            event.stop()
            event.prevent_default()
            self.dismiss(None)

    @on(Button.Pressed, "#edit-profile-btn")
    def on_edit(self) -> None:
        self.dismiss("edit")


class ProfileEditScreen(ModalScreen[dict | None]):
    """Edit your profile."""

    def __init__(self, user: dict) -> None:
        super().__init__()
        self._user = user

    def compose(self) -> ComposeResult:
        u = self._user
        with Vertical(id="profile-modal"):
            yield Label("EDIT PROFILE", id="modal-title")
            yield Static("[dim]display name[/]", classes="profile-label")
            yield Input(
                value=u.get("display_name", ""),
                placeholder="display name",
                id="edit-display-name",
            )
            yield Static("[dim]pronouns[/]", classes="profile-label")
            yield Input(
                value=u.get("pronouns") or "",
                placeholder="e.g. they/them",
                id="edit-pronouns",
            )
            yield Static("[dim]bio[/]", classes="profile-label")
            yield Input(
                value=u.get("bio") or "",
                placeholder="tell us about yourself",
                id="edit-bio",
            )
            yield Static("", classes="profile-spacer")
            yield Button("save", id="save-profile-btn", variant="primary")

    def on_mount(self) -> None:
        self.query_one("#edit-display-name", Input).focus()

    def on_key(self, event: Key) -> None:
        if event.key == "escape":
            event.stop()
            event.prevent_default()
            self.dismiss(None)

    @on(Input.Submitted)
    def on_input_submitted(self) -> None:
        self._do_save()

    @on(Button.Pressed, "#save-profile-btn")
    def on_save(self) -> None:
        self._do_save()

    @work(exclusive=True)
    async def _do_save(self) -> None:
        display_name = self.query_one("#edit-display-name", Input).value.strip()
        pronouns = self.query_one("#edit-pronouns", Input).value.strip()
        bio = self.query_one("#edit-bio", Input).value.strip()

        if not display_name:
            self.notify("display name required", severity="warning")
            return

        try:
            api = self.app.api
            result = await api.update_profile(
                display_name=display_name,
                pronouns=pronouns,
                bio=bio,
            )
            self.notify("profile updated")
            self.dismiss(result)
        except Exception:
            self.notify("failed to save", severity="error")
