package com.tomhempel.rbarometer.questionnaire

import android.app.Activity
import android.content.Context
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.Spinner
import com.tomhempel.rbarometer.R
import com.tomhempel.rbarometer.ui.SystemBarInsets
import com.tomhempel.rbarometer.utils.ViewUtils

/** Reusable language dropdown — toolbar row above content so question text sits below. */
object QuestionnaireLanguagePicker {

    /**
     * Ensures a language toolbar sits above the screen content.
     * @return the inner content root (question layout) for handlers to bind against.
     */
    fun ensureToolbarLayout(
        activity: Activity,
        languageId: String,
        onLanguageChanged: (String) -> Unit,
    ): View {
        val content = activity.findViewById<ViewGroup>(android.R.id.content)
            ?: return activity.window.decorView

        val currentRoot = content.getChildAt(0) ?: return activity.window.decorView

        val questionRoot = when {
            currentRoot.findViewById<Spinner>(R.id.langSpinner) != null -> {
                wireSpinner(
                    activity,
                    currentRoot.findViewById(R.id.langSpinner)!!,
                    languageId,
                    onLanguageChanged,
                )
                contentRoot(currentRoot)
            }

            currentRoot.id == R.id.questionnaire_screen_wrapper -> {
                currentRoot.findViewById<Spinner>(R.id.langSpinner)?.let {
                    wireSpinner(activity, it, languageId, onLanguageChanged)
                }
                contentRoot(currentRoot)
            }

            else -> wrapWithLanguageToolbar(activity, content, currentRoot, languageId, onLanguageChanged)
        }

        // setContentView runs SystemBarInsets before this wrapper exists; re-apply on the live root.
        SystemBarInsets.applyToContentRoot(activity, ensureMinContentPadding = true)
        return questionRoot
    }

    private fun wrapWithLanguageToolbar(
        activity: Activity,
        content: ViewGroup,
        currentRoot: View,
        languageId: String,
        onLanguageChanged: (String) -> Unit,
    ): View {
        content.removeView(currentRoot)
        currentRoot.id = R.id.questionnaire_content_root

        val margin = ViewUtils.dp(activity, 12)
        val pickerHeight = activity.resources.getDimensionPixelSize(R.dimen.language_picker_height)

        val toolbar = LinearLayout(activity).apply {
            id = R.id.questionnaire_lang_toolbar
            orientation = LinearLayout.HORIZONTAL
            gravity = Gravity.END or Gravity.CENTER_VERTICAL
            setPadding(margin, margin, margin, margin)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
            )
        }

        val spinner = Spinner(activity).apply { id = R.id.langSpinner }
        toolbar.addView(
            spinner,
            LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                pickerHeight,
            ),
        )
        wireSpinner(activity, spinner, languageId, onLanguageChanged)

        val wrapper = LinearLayout(activity).apply {
            id = R.id.questionnaire_screen_wrapper
            orientation = LinearLayout.VERTICAL
            layoutParams = FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT,
            )
        }
        wrapper.addView(toolbar)
        wrapper.addView(
            currentRoot,
            LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                0,
                1f,
            ),
        )
        content.addView(wrapper)
        return currentRoot
    }

    /** @deprecated Use [ensureToolbarLayout]; kept for session interstitial refresh. */
    fun attach(
        root: View,
        context: Context,
        languageId: String,
        onLanguageChanged: (String) -> Unit,
    ) {
        val activity = context as? Activity
        if (activity != null) {
            ensureToolbarLayout(activity, languageId, onLanguageChanged)
            return
        }
        root.findViewById<Spinner>(R.id.langSpinner)?.let {
            wireSpinner(context, it, languageId, onLanguageChanged)
        }
    }

    fun detach(activity: Activity) {
        // setContentView replaces the tree; nothing to tear down.
    }

    fun wireSpinner(
        context: Context,
        spinner: Spinner,
        languageId: String,
        onLanguageChanged: (String) -> Unit,
    ) {
        val labels = AppLanguages.spinnerLabels(languageId)
        val selected = labels.getOrNull(AppLanguages.indexOf(languageId))
        ViewUtils.setupLanguagePickerSpinner(context, spinner, labels, selected)
        spinner.onItemSelectedListener = null
        spinner.setSelection(AppLanguages.indexOf(languageId))
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, v: View?, position: Int, id: Long) {
                val newLang = AppLanguages.ids[position]
                if (newLang == languageId) return
                spinner.post { onLanguageChanged(newLang) }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) = Unit
        }
    }

    private fun contentRoot(root: View): View {
        if (root.id == R.id.questionnaire_screen_wrapper) {
            val wrapper = root as ViewGroup
            return wrapper.findViewById(R.id.questionnaire_content_root)
                ?: wrapper.getChildAt(1)
                ?: root
        }
        return root
    }
}
