from __future__ import annotations

from textual import on, work
from textual.app import ComposeResult
from textual.containers import Center, Vertical
from textual.screen import Screen
from textual.widgets import Button, Input, Label, Static


class LoginScreen(Screen):
    BINDINGS = [("ctrl+c", "quit", "Quit")]

    def __init__(self) -> None:
        super().__init__()
        self._signup_mode = False

    def compose(self) -> ComposeResult:
        with Center():
            with Vertical(id="login-box"):
                yield Static("TERMCHAT", id="login-title")
                yield Static("secure terminal messaging", id="login-subtitle")
                yield Input(placeholder="username", id="username")
                yield Input(
                    placeholder="display name",
                    id="display_name",
                    classes="hidden",
                )
                yield Input(placeholder="password", password=True, id="password")
                yield Label("", id="login-error")
                yield Button("log in", id="submit-btn", variant="primary")
                yield Button(
                    "don't have an account? sign up",
                    id="toggle-btn",
                    variant="default",
                )

    def _toggle_mode(self) -> None:
        self._signup_mode = not self._signup_mode
        dn = self.query_one("#display_name", Input)
        btn = self.query_one("#submit-btn", Button)
        toggle = self.query_one("#toggle-btn", Button)

        if self._signup_mode:
            dn.remove_class("hidden")
            btn.label = "sign up"
            toggle.label = "already have an account? log in"
        else:
            dn.add_class("hidden")
            btn.label = "log in"
            toggle.label = "don't have an account? sign up"

    @on(Button.Pressed, "#toggle-btn")
    def on_toggle(self) -> None:
        self._toggle_mode()

    @on(Button.Pressed, "#submit-btn")
    def on_submit_pressed(self) -> None:
        self._do_submit()

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

    @work(exclusive=True)
    async def _do_submit(self) -> None:
        username = self.query_one("#username", Input).value.strip()
        password = self.query_one("#password", Input).value
        error_label = self.query_one("#login-error", Label)
        error_label.update("")

        if not username or not password:
            error_label.update("enter username and password")
            return

        api = self.app.api

        try:
            if self._signup_mode:
                display_name = (
                    self.query_one("#display_name", Input).value.strip()
                    or username
                )
                await api.register(username, display_name, password)
            else:
                await api.login(username, password)

            from termchat.screens.chat import ChatScreen
            self.app.push_screen(ChatScreen())

        except Exception as exc:
            msg = str(exc)
            if "401" in msg or "403" in msg:
                error_label.update("wrong username or password")
            elif "400" in msg or "409" in msg:
                if self._signup_mode:
                    error_label.update("username taken")
                else:
                    error_label.update("wrong username or password")
            elif "422" in msg:
                if self._signup_mode:
                    error_label.update("username must be 2-30 chars (letters, numbers, _ -)\npassword must be at least 6 chars")
                else:
                    error_label.update("invalid input")
            else:
                error_label.update("connection error — is the server running?")

    def action_quit(self) -> None:
        self.app.exit()
