"""Config form widgets for Step 5."""

from __future__ import annotations

from textual.app import ComposeResult
from textual.widget import Widget
from textual.widgets import Static, Input, Button
from textual.containers import Vertical, Horizontal

from easyclaw_tui.widgets.step_panel import StepPanel


class KeyPrompt(Widget):
    """Minimal single-field prompt for the OpenRouter API key.

    Shows one input field with Continue and Skip buttons.
    """

    DEFAULT_CSS = """
    KeyPrompt {
        height: auto;
        padding: 1 1;
    }
    KeyPrompt .field-label {
        color: #f59e0b;
        text-style: bold;
        height: 1;
    }
    KeyPrompt .field-hint {
        color: $text-muted;
        height: 1;
        padding: 0 0 0 2;
    }
    KeyPrompt Input {
        margin: 1 0;
    }
    KeyPrompt .btn-row {
        height: 3;
        margin: 1 0 0 0;
    }
    KeyPrompt #btn-continue {
        background: #f59e0b;
        color: $background;
        text-style: bold;
        min-width: 16;
        margin: 0 1 0 0;
    }
    KeyPrompt #btn-continue:hover {
        background: #d97706;
    }
    KeyPrompt #btn-skip {
        min-width: 16;
    }
    """

    def __init__(self) -> None:
        super().__init__()
        self._key = ""

    def compose(self) -> ComposeResult:
        with Vertical():
            yield Static("OpenRouter API Key", classes="field-label")
            yield Static("Paste your key from openrouter.ai/keys", classes="field-hint")
            yield Input(
                placeholder="sk-or-...",
                password=True,
                id="input-or-key",
            )
            with Horizontal(classes="btn-row"):
                yield Button("Continue", id="btn-continue", variant="primary")
                yield Button("Skip (use free model)", id="btn-skip", variant="default")

    @property
    def key_value(self) -> str:
        return self._key

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-continue":
            self._key = self.query_one("#input-or-key", Input).value.strip()
            self.post_message(StepPanel.FormSubmitted())
        elif event.button.id == "btn-skip":
            self._key = ""
            self.post_message(StepPanel.FormSubmitted())

    def on_input_submitted(self, event: Input.Submitted) -> None:
        # Pressing Enter in the input acts like clicking Continue
        self._key = self.query_one("#input-or-key", Input).value.strip()
        self.post_message(StepPanel.FormSubmitted())
