"""Reusable dialog widgets for the TUI."""

from __future__ import annotations

from typing import Optional

from textual.app import ComposeResult
from textual.containers import Horizontal, Vertical
from textual.screen import ModalScreen
from textual.widgets import Button, Input, Label, Static


class ConfirmDialog(ModalScreen[bool]):
    """Yes/No confirmation dialog."""

    DEFAULT_CSS = """
    ConfirmDialog {
        align: center middle;
    }

    ConfirmDialog > Vertical {
        width: 60;
        height: auto;
        border: thick $primary;
        background: $surface;
        padding: 1 2;
    }

    ConfirmDialog .dialog-title {
        text-align: center;
        text-style: bold;
        margin-bottom: 1;
    }

    ConfirmDialog .dialog-message {
        margin-bottom: 1;
    }

    ConfirmDialog Horizontal {
        align: center middle;
        height: auto;
        margin-top: 1;
    }

    ConfirmDialog Button {
        margin: 0 1;
    }
    """

    def __init__(
        self,
        title: str,
        message: str,
        yes_label: str = "Yes",
        no_label: str = "No",
    ) -> None:
        """Initialize confirm dialog.

        Args:
            title: Dialog title.
            message: Confirmation message.
            yes_label: Label for yes button.
            no_label: Label for no button.
        """
        super().__init__()
        self.dialog_title = title
        self.message = message
        self.yes_label = yes_label
        self.no_label = no_label

    def compose(self) -> ComposeResult:
        with Vertical():
            yield Static(self.dialog_title, classes="dialog-title")
            yield Static(self.message, classes="dialog-message")
            with Horizontal():
                yield Button(self.yes_label, id="yes", variant="primary")
                yield Button(self.no_label, id="no", variant="default")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        self.dismiss(event.button.id == "yes")


class MessageDialog(ModalScreen[None]):
    """Information/warning message dialog."""

    DEFAULT_CSS = """
    MessageDialog {
        align: center middle;
    }

    MessageDialog > Vertical {
        width: 70;
        height: auto;
        max-height: 80%;
        border: thick $primary;
        background: $surface;
        padding: 1 2;
    }

    MessageDialog .dialog-title {
        text-align: center;
        text-style: bold;
        margin-bottom: 1;
    }

    MessageDialog .dialog-message {
        margin-bottom: 1;
    }

    MessageDialog Horizontal {
        align: center middle;
        height: auto;
        margin-top: 1;
    }
    """

    def __init__(self, title: str, message: str, button_label: str = "OK") -> None:
        """Initialize message dialog.

        Args:
            title: Dialog title.
            message: Message to display.
            button_label: Label for OK button.
        """
        super().__init__()
        self.dialog_title = title
        self.message = message
        self.button_label = button_label

    def compose(self) -> ComposeResult:
        with Vertical():
            yield Static(self.dialog_title, classes="dialog-title")
            yield Static(self.message, classes="dialog-message")
            with Horizontal():
                yield Button(self.button_label, id="ok", variant="primary")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        self.dismiss(None)


class InputDialog(ModalScreen[Optional[str]]):
    """Text input dialog."""

    DEFAULT_CSS = """
    InputDialog {
        align: center middle;
    }

    InputDialog > Vertical {
        width: 60;
        height: auto;
        border: thick $primary;
        background: $surface;
        padding: 1 2;
    }

    InputDialog .dialog-title {
        text-align: center;
        text-style: bold;
        margin-bottom: 1;
    }

    InputDialog .dialog-label {
        margin-bottom: 1;
    }

    InputDialog Input {
        margin-bottom: 1;
    }

    InputDialog Horizontal {
        align: center middle;
        height: auto;
        margin-top: 1;
    }

    InputDialog Button {
        margin: 0 1;
    }
    """

    def __init__(
        self,
        title: str,
        label: str,
        default: str = "",
        placeholder: str = "",
    ) -> None:
        """Initialize input dialog.

        Args:
            title: Dialog title.
            label: Input field label.
            default: Default value.
            placeholder: Placeholder text.
        """
        super().__init__()
        self.dialog_title = title
        self.label = label
        self.default = default
        self.placeholder = placeholder

    def compose(self) -> ComposeResult:
        with Vertical():
            yield Static(self.dialog_title, classes="dialog-title")
            yield Label(self.label, classes="dialog-label")
            yield Input(
                value=self.default,
                placeholder=self.placeholder,
                id="input",
            )
            with Horizontal():
                yield Button("OK", id="ok", variant="primary")
                yield Button("Cancel", id="cancel", variant="default")

    def on_mount(self) -> None:
        self.query_one(Input).focus()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "ok":
            self.dismiss(self.query_one(Input).value)
        else:
            self.dismiss(None)

    def on_input_submitted(self, event: Input.Submitted) -> None:
        self.dismiss(event.value)


class PasswordDialog(ModalScreen[Optional[str]]):
    """Password input dialog with optional confirmation."""

    DEFAULT_CSS = """
    PasswordDialog {
        align: center middle;
    }

    PasswordDialog > Vertical {
        width: 60;
        height: auto;
        border: thick $primary;
        background: $surface;
        padding: 1 2;
    }

    PasswordDialog .dialog-title {
        text-align: center;
        text-style: bold;
        margin-bottom: 1;
    }

    PasswordDialog .dialog-label {
        margin-bottom: 1;
    }

    PasswordDialog Input {
        margin-bottom: 1;
    }

    PasswordDialog .error {
        color: $error;
        margin-bottom: 1;
    }

    PasswordDialog Horizontal {
        align: center middle;
        height: auto;
        margin-top: 1;
    }

    PasswordDialog Button {
        margin: 0 1;
    }
    """

    def __init__(
        self,
        title: str,
        label: str = "Password:",
        confirm: bool = False,
    ) -> None:
        """Initialize password dialog.

        Args:
            title: Dialog title.
            label: Password field label.
            confirm: Whether to require password confirmation.
        """
        super().__init__()
        self.dialog_title = title
        self.label = label
        self.confirm = confirm

    def compose(self) -> ComposeResult:
        with Vertical():
            yield Static(self.dialog_title, classes="dialog-title")
            yield Label(self.label, classes="dialog-label")
            yield Input(password=True, id="password")
            if self.confirm:
                yield Label("Confirm password:", classes="dialog-label")
                yield Input(password=True, id="confirm")
            yield Static("", id="error", classes="error")
            with Horizontal():
                yield Button("OK", id="ok", variant="primary")
                yield Button("Cancel", id="cancel", variant="default")

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

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "ok":
            self._validate_and_submit()
        else:
            self.dismiss(None)

    def on_input_submitted(self, event: Input.Submitted) -> None:
        if self.confirm and event.input.id == "password":
            self.query_one("#confirm", Input).focus()
        else:
            self._validate_and_submit()

    def _validate_and_submit(self) -> None:
        password = self.query_one("#password", Input).value
        error_widget = self.query_one("#error", Static)

        if not password:
            error_widget.update("Password cannot be empty")
            return

        if self.confirm:
            confirm = self.query_one("#confirm", Input).value
            if password != confirm:
                error_widget.update("Passwords do not match")
                return

        self.dismiss(password)
