"""Select widget for enum configuration options."""

from textual.message import Message
from textual.widgets import Select


class OptionSelect(Select):
    """Select widget for enum options."""

    DEFAULT_CSS = """
    OptionSelect {
        width: 100%;
        height: 3;
    }

    OptionSelect:focus {
        border: solid $primary;
    }

    OptionSelect.-modified {
        border-left: wide $warning;
    }
    """

    class Changed(Message):
        """Message emitted when selection changes."""

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

    def __init__(
        self,
        option_name: str,
        value: str = "",
        valid_values: list[str] | tuple[str, ...] = (),
        default: str = "",
        **kwargs
    ) -> None:
        """Initialize select widget.

        Args:
            option_name: Name of the configuration option
            value: Current value
            valid_values: List of valid enum values
            default: Default value for comparison
        """
        # Build options list
        options: list[tuple[str, str]] = []
        for v in valid_values:
            # Label shows value, possibly with (default) indicator
            label = f"{v} (default)" if v == default else v
            options.append((label, v))

        # Determine initial value
        initial_value = value if value in valid_values else Select.BLANK

        super().__init__(
            options=options,
            value=initial_value,
            allow_blank=True,
            **kwargs
        )

        self.option_name = option_name
        self.valid_values = valid_values
        self.default_value = default

    def get_value(self) -> str:
        """Get the current selected value."""
        if self.value == Select.BLANK:
            return ""
        return str(self.value)

    def set_value(self, value: str) -> None:
        """Set the selected value."""
        if value in self.valid_values:
            self.value = value
        else:
            self.value = Select.BLANK

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

    def on_select_changed(self, event: Select.Changed) -> None:
        """Handle selection change."""
        value = "" if event.value == Select.BLANK else str(event.value)

        self.post_message(self.Changed(
            option_name=self.option_name,
            value=value
        ))

        # Update modified class
        if self.is_modified:
            self.add_class("-modified")
        else:
            self.remove_class("-modified")
