"""Interactive config form for Step 5 — collects API keys, model, channel, bind."""

from __future__ import annotations

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

from easyclaw_tui.widgets.step_panel import StepPanel


MODELS = [
    ("minimax-m2.5", "MiniMax M2.5 — Cheapest, good quality (default)"),
    ("deepseek-v3.2", "DeepSeek V3.2 — Great value, strong coding"),
    ("claude-haiku-4.5", "Claude Haiku 4.5 — Fast, reliable"),
    ("claude-sonnet-4.5", "Claude Sonnet 4.5 — Best all-around"),
    ("gpt-4.1-mini", "GPT-4.1 Mini — Strong, affordable"),
]

CHANNELS = [
    ("none", "None — No messaging channel (default)"),
    ("whatsapp", "WhatsApp — Requires QR scan after setup"),
    ("telegram", "Telegram — Requires bot token from @BotFather"),
    ("discord", "Discord — Requires bot token from Developer Portal"),
]

BIND_MODES = [
    ("lan", "LAN — Bind to local network (default)"),
    ("loopback", "Loopback — localhost only"),
    ("auto", "Auto — Auto-detect best bind"),
    ("tailnet", "Tailnet — Tailscale network"),
]


class ConfigForm(Widget):
    """Interactive form for collecting install configuration."""

    DEFAULT_CSS = """
    ConfigForm {
        height: auto;
        padding: 0 1;
    }
    ConfigForm .field-group {
        height: auto;
        margin: 0 0 1 0;
    }
    ConfigForm .field-label {
        color: #f59e0b;
        text-style: bold;
        height: 1;
    }
    ConfigForm .field-hint {
        color: $text-muted;
        height: 1;
        padding: 0 0 0 2;
    }
    ConfigForm Input {
        margin: 0 0 0 0;
    }
    ConfigForm Select {
        margin: 0 0 0 0;
    }
    ConfigForm #btn-continue {
        background: #f59e0b;
        color: $background;
        text-style: bold;
        min-width: 20;
        margin: 1 0;
    }
    ConfigForm #btn-continue:hover {
        background: #d97706;
    }
    """

    def __init__(
        self,
        api_key: str = "",
        openrouter_key: str = "",
        openai_key: str = "",
        model: str = "minimax-m2.5",
        channel: str = "none",
        bind: str = "lan",
    ) -> None:
        super().__init__()
        self._api_key = api_key
        self._openrouter_key = openrouter_key
        self._openai_key = openai_key
        self._model = model
        self._channel = channel
        self._bind = bind

    def compose(self) -> ComposeResult:
        # API keys
        with Vertical(classes="field-group"):
            yield Static("EasyClaw API Key", classes="field-label")
            yield Static("From your dashboard (ec_live_...)", classes="field-hint")
            yield Input(
                value=self._api_key,
                placeholder="ec_live_...",
                id="input-api-key",
            )

        with Vertical(classes="field-group"):
            yield Static("OpenRouter API Key (required)", classes="field-label")
            yield Static("Get one at openrouter.ai/keys (sk-or-...)", classes="field-hint")
            yield Input(
                value=self._openrouter_key,
                placeholder="sk-or-...",
                password=True,
                id="input-openrouter-key",
            )

        with Vertical(classes="field-group"):
            yield Static("OpenAI API Key (optional — for memory search)", classes="field-label")
            yield Input(
                value=self._openai_key,
                placeholder="sk-... (press Enter to skip)",
                password=True,
                id="input-openai-key",
            )

        # Selects
        with Vertical(classes="field-group"):
            yield Static("Primary Model", classes="field-label")
            yield Select(
                [(label, value) for value, label in MODELS],
                value=self._model,
                id="select-model",
            )

        with Vertical(classes="field-group"):
            yield Static("Bind Mode", classes="field-label")
            yield Select(
                [(label, value) for value, label in BIND_MODES],
                value=self._bind,
                id="select-bind",
            )

        with Vertical(classes="field-group"):
            yield Static("Messaging Channel", classes="field-label")
            yield Select(
                [(label, value) for value, label in CHANNELS],
                value=self._channel,
                id="select-channel",
            )

        yield Button("Continue →", id="btn-continue", variant="primary")

    # ─── Value accessors ─────────────────────────────────

    @property
    def api_key(self) -> str:
        return self.query_one("#input-api-key", Input).value.strip()

    @property
    def openrouter_key(self) -> str:
        return self.query_one("#input-openrouter-key", Input).value.strip()

    @property
    def openai_key(self) -> str:
        return self.query_one("#input-openai-key", Input).value.strip()

    @property
    def model(self) -> str:
        val = self.query_one("#select-model", Select).value
        return str(val) if val != Select.BLANK else "minimax-m2.5"

    @property
    def channel(self) -> str:
        val = self.query_one("#select-channel", Select).value
        return str(val) if val != Select.BLANK else "none"

    @property
    def bind(self) -> str:
        val = self.query_one("#select-bind", Select).value
        return str(val) if val != Select.BLANK else "lan"

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-continue":
            # Validate required fields
            if not self.openrouter_key:
                self.query_one("#input-openrouter-key", Input).focus()
                return
            # Post form submitted to parent StepPanel
            self.post_message(StepPanel.FormSubmitted())
