"""
Environment switcher UI component.
"""
from .base import Component
from django.urls import reverse
from django.middleware.csrf import get_token


class Environment(Component):
    """
    A dropdown panel allowing users to switch session environments 
    (e.g., active company, branch, or semester).
    """

    def __init__(self, registry, **kwargs):
        super().__init__(**kwargs)
        self.registry = registry
    def render_html(self, **kwargs) -> str:
        request = kwargs.get("request")
        app = request.resolver_match.app_name
        fields = []
        try:
            env_class = self.registry.get(app)
            env_instance = env_class(request)
            fields = env_instance.get_field_data()
        except Exception:
            pass

        fields_html = ""
        environment_update = reverse("environment:update")
        for field in fields:
            options = "\n".join(
                [
                    f"""
                            <option value="{obj.pk}"{" selected" if field["value"] and field["value"].pk == obj.pk else ""}>
                                {obj}
                            </option>
            """
                    for obj in field["queryset"]
                ]
            )
            fields_html += f"""
                <div class="form-control" id="env-field-{field["session_key"]}">
                    <label class="label py-1">
                        <span class="label-text text-xs">{field["label"]}</span>
                    </label>
                    <select
                        name="{field["session_key"]}"
                        class="select select-bordered select-sm w-full"
                        hx-post="{environment_update}"
                        hx-trigger="change"
                        hx-target="#environment-panel"
                        hx-swap="outerHTML"
                        hx-include="[name^='env_']"
                        hx-headers='{{"X-CSRFToken": "{get_token(request)}"}}'
                    >
                        {f'<option value="">-- Select {field["label"]} --</option>' if not field["required"] else ""}
                        {options}
                    </select>
                </div>
            """
        if len(fields) == 0:
            fields_html = """<div class="text-xs text-base-content/50 italic">
                    No environment settings for this app.
                </div>"""

        return f"""
        <div id="environment-panel" class="space-y-3">
            <div class="text-sm font-semibold text-base-content/70 flex items-center gap-2">
                {{% heroicon_mini "adjustments-horizontal" %}}
                Environment
            </div>
            {fields_html}
        </div>
        """
