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 PasswordScreen(ModalScreen[bool]):
    """Change password modal."""

    def compose(self) -> ComposeResult:
        with Vertical(id="password-modal"):
            yield Label("CHANGE PASSWORD", id="modal-title")
            yield Static("[dim]current password[/]", classes="profile-label")
            yield Input(
                placeholder="current password",
                password=True,
                id="current-password",
            )
            yield Static("[dim]new password[/]", classes="profile-label")
            yield Input(
                placeholder="new password (min 6 chars)",
                password=True,
                id="new-password",
            )
            yield Static("[dim]confirm new password[/]", classes="profile-label")
            yield Input(
                placeholder="confirm new password",
                password=True,
                id="confirm-password",
            )
            yield Label("", id="password-error")
            yield Button("change password", id="change-pw-btn", variant="primary")

    def on_mount(self) -> None:
        self.query_one("#current-password", Input).focus()

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

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

    @on(Button.Pressed, "#change-pw-btn")
    def on_change(self) -> None:
        self._do_change()

    @work(exclusive=True)
    async def _do_change(self) -> None:
        current = self.query_one("#current-password", Input).value
        new_pw = self.query_one("#new-password", Input).value
        confirm = self.query_one("#confirm-password", Input).value
        error_label = self.query_one("#password-error", Label)

        if not current:
            error_label.update("[red]enter current password[/]")
            return
        if len(new_pw) < 6:
            error_label.update("[red]new password must be at least 6 characters[/]")
            return
        if new_pw != confirm:
            error_label.update("[red]passwords don't match[/]")
            return

        try:
            await self.app.api.change_password(current, new_pw)
            self.notify("password changed")
            self.dismiss(True)
        except Exception as exc:
            msg = str(exc)
            if "400" in msg:
                error_label.update("[red]current password is incorrect[/]")
            else:
                error_label.update("[red]failed to change password[/]")
