"""Config flow for Greenhousino Irrigation integration."""

import logging
from typing import Any

import voluptuous as vol

from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.core import HomeAssistant

from .const import (
    CONF_COMMAND_TOPIC,
    CONF_HOST,
    CONF_STATE_TOPIC,
    DEFAULT_COMMAND_TOPIC,
    DEFAULT_NAME,
    DEFAULT_STATE_TOPIC,
    DOMAIN,
)

_LOGGER = logging.getLogger(__name__)

STEP_ONE_DATA_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_HOST, description={"suggested_value": ""}): str,
    }
)

STEP_TWO_DATA_SCHEMA = vol.Schema(
    {
        vol.Required(
            CONF_COMMAND_TOPIC,
            description={"suggested_value": DEFAULT_COMMAND_TOPIC},
        ): str,
        vol.Required(
            CONF_STATE_TOPIC,
            description={"suggested_value": DEFAULT_STATE_TOPIC},
        ): str,
    }
)


class GreenhousinoConfigFlow(ConfigFlow, domain=DOMAIN):
    """Handle a config flow for Greenhousino Irrigation."""

    VERSION = 1

    async def async_step_user(
        self, user_input: dict[str, Any] | None = None
    ) -> ConfigFlowResult:
        """Handle the initial step (host)."""
        errors: dict[str, str] = {}

        if user_input is not None:
            try:
                self._tmp_data = user_input
                return await self.async_step_mqtt()
            except Exception:
                errors["base"] = "unknown"

        return self.async_show_form(
            step_id="user",
            data_schema=STEP_ONE_DATA_SCHEMA,
            errors=errors,
        )

    async def async_step_mqtt(
        self, user_input: dict[str, Any] | None = None
    ) -> ConfigFlowResult:
        """Handle the MQTT topics step."""
        errors: dict[str, str] = {}

        if user_input is not None:
            try:
                data = {**self._tmp_data, **user_input}
                title = DEFAULT_NAME
                if data.get(CONF_HOST):
                    title = f"{DEFAULT_NAME} ({data[CONF_HOST]})"

                return self.async_create_entry(title=title, data=data)
            except Exception:
                errors["base"] = "unknown"

        return self.async_show_form(
            step_id="mqtt",
            data_schema=STEP_TWO_DATA_SCHEMA,
            errors=errors,
        )
