package com.tomhempel.rbarometer.questionnaire.handlers

import android.content.Context
import android.view.View
import android.text.Html
import android.widget.*
import kotlinx.coroutines.*
import com.tomhempel.rbarometer.questionnaire.AnswerRestoreHelper
import com.tomhempel.rbarometer.questionnaire.GlobalValues
import com.tomhempel.rbarometer.LanguageManager
import com.tomhempel.rbarometer.questionnaire.QuestionFlowResolver
import com.tomhempel.rbarometer.questionnaire.QuestionHandler
import com.tomhempel.rbarometer.questionnaire.QuestionItem
import com.tomhempel.rbarometer.R
import com.tomhempel.rbarometer.ui.SessionUi
import com.tomhempel.rbarometer.utils.ViewUtils

/*
Zweck:
- Steuert eine Einzelfrage mit genau einer auswählbaren Antwort (RadioButtons).
*/

class HandlerRadioQuestion(
    private val context: Context,
    private val answers: MutableMap<String, Any>,
    private val languageID: String,
    private val goToNextQuestion: () -> Unit,
    private val goToPreviousQuestion: () -> Unit,
    private val goToQuestionById: (String) -> Unit,
    private val showToast: (String) -> Unit,
    private val questionnaireMeta: String
) : QuestionHandler {

    private lateinit var layout: View
    private lateinit var question: QuestionItem.RadioQuestion

    override fun bind(layout: View, question: QuestionItem) {
        this.layout = layout
        this.question = question as QuestionItem.RadioQuestion

        val radioGroup = layout.findViewById<RadioGroup>(R.id.RadioGroup)
        val questionTextView = layout.findViewById<TextView>(R.id.textView)
        val questionTitle = layout.findViewById<TextView>(R.id.question)

        questionTextView.text = LanguageManager.resolvedText(languageID, question.noteBeforeKey, question.textKey)
        questionTitle.text = question.question?.let {
            Html.fromHtml(LanguageManager.getText(languageID, it), Html.FROM_HTML_MODE_LEGACY)
        } ?: ""

        ViewUtils.setTextSizePercentOfScreenHeight(questionTextView, 0.03f)
        ViewUtils.setTextSizePercentOfScreenHeight(questionTitle,   0.03f)

        radioGroup.removeAllViews()

        (question.options ?: emptyList()).forEach { option ->
            val radioButton = RadioButton(context).apply {
                text = LanguageManager.getText(languageID, option.key)
                tag = option.key

                // RadioButton-Text analog zu EditTexts: 2.5% der Bildschirmhöhe
                ViewUtils.setTextSizePercentOfScreenHeight(this, 0.025f)

                layoutParams = RadioGroup.LayoutParams(
                    RadioGroup.LayoutParams.MATCH_PARENT,
                    RadioGroup.LayoutParams.WRAP_CONTENT
                ).apply {
                    val scale = context.resources.displayMetrics.density
                    val margin = (16 * scale + 0.5f).toInt()
                    setMargins(0, 0, 0, margin)
                }

                val padding = (12 * resources.displayMetrics.density).toInt()
                setPadding(padding, padding, padding, padding)
                SessionUi.styleAnswerChoice(context, this)
            }
            radioGroup.addView(radioButton)
        }

        restorePreviousAnswer(radioGroup)

        val answerMapKey = question.question ?: (question.id ?: "")
        if (answerMapKey.isNotBlank() && !answers.containsKey(answerMapKey)) {
            AnswerRestoreHelper.restoreIfMissing(
                CoroutineScope(Dispatchers.Main),
                questionnaireMeta,
                answerMapKey,
            ) { dbAnswer ->
                for (i in 0 until radioGroup.childCount) {
                    val radioButton = radioGroup.getChildAt(i) as RadioButton
                    if (radioButton.tag == dbAnswer) {
                        radioButton.isChecked = true
                        break
                    }
                }
                answers[answerMapKey] = dbAnswer
            }
        }

        layout.findViewById<Button>(R.id.Qnext).setOnClickListener {
            if (validate()) {
                saveAnswer()

                val selectedId = radioGroup.checkedRadioButtonId
                val selectedRadioButton = layout.findViewById<RadioButton>(selectedId)
                val selectedKey = selectedRadioButton.tag.toString()

                val nextId = QuestionFlowResolver.nextQuestionIdForRadio(question, selectedKey)

                if (!nextId.isNullOrEmpty()) {
                    goToQuestionById(nextId)
                } else {
                    goToNextQuestion()
                }
            } else {
                showToast(LanguageManager.getText(languageID, "select_one_answer"))
            }
        }

        layout.findViewById<Button>(R.id.Qprev).setOnClickListener {
            goToPreviousQuestion()
        }
    }

    private fun restorePreviousAnswer(radioGroup: RadioGroup) {
        question.question?.let { questionKey ->
            val savedAnswer = answers[questionKey] as? String
            savedAnswer?.let { saved ->
                for (i in 0 until radioGroup.childCount) {
                    val radioButton = radioGroup.getChildAt(i) as RadioButton
                    if (radioButton.tag == saved) {
                        radioButton.isChecked = true
                        break
                    }
                }
            }
        }
    }

    override fun validate(): Boolean {
        return layout.findViewById<RadioGroup>(R.id.RadioGroup).checkedRadioButtonId != -1
    }

    override fun saveAnswer() {
        val radioGroup = layout.findViewById<RadioGroup>(R.id.RadioGroup)
        val selectedId = radioGroup.checkedRadioButtonId
        val selectedRadioButton = layout.findViewById<RadioButton>(selectedId)
        val answerKey = selectedRadioButton.tag.toString()

        question.question?.let { questionKey ->
            answers[questionKey] = answerKey
        }
    }
}
