"""Toggle widget for boolean configuration options."""

from textual.message import Message
from textual.widgets import Switch


class OptionToggle(Switch):
    """Toggle widget for boolean options."""

    DEFAULT_CSS = """
    OptionToggle {
        width: auto;
        height: 3;
        padding: 0 1;
    }

    OptionToggle:focus {
        border: solid $primary;
    }

    OptionToggle.-on > .switch--slider {
        background: $success;
    }
    """

    class Changed(Message):
        """Message emitted when toggle value changes."""

        def __init__(self, option_name: str, value: bool) -> None:
            self.option_name = option_name
            self.value = value
            super().__init__()

    def __init__(
        self,
        option_name: str,
        value: bool = False,
        default: bool = False,
        **kwargs
    ) -> None:
        """Initialize toggle widget.

        Args:
            option_name: Name of the configuration option
            value: Current value
            default: Default value for comparison
        """
        super().__init__(value=value, **kwargs)
        self.option_name = option_name
        self.default_value = default

    def get_value(self) -> bool:
        """Get the current toggle value."""
        return self.value

    def set_value(self, value: bool) -> None:
        """Set the toggle value."""
        self.value = value

    @property
    def is_modified(self) -> bool:
        """Check if value differs from default."""
        return self.value != self.default_value

    def on_switch_changed(self, event: Switch.Changed) -> None:
        """Handle toggle state change."""
        # Post our custom message
        self.post_message(self.Changed(
            option_name=self.option_name,
            value=event.value
        ))


def parse_bool(value: str | None) -> bool:
    """Parse a string value to boolean.

    Args:
        value: String value like "true", "false", "1", "0"

    Returns:
        Boolean value
    """
    if value is None:
        return False
    return value.lower() in ("true", "1", "yes", "on")
