package com.dano.test1.questionnaire.handlers

import android.content.Context
import android.view.View
import android.widget.*
import kotlinx.coroutines.*
import com.dano.test1.ui.Countries
import com.dano.test1.questionnaire.GlobalValues
import com.dano.test1.LanguageManager
import com.dano.test1.MyApp
import com.dano.test1.questionnaire.QuestionHandler
import com.dano.test1.questionnaire.QuestionItem
import com.dano.test1.R
import com.dano.test1.utils.ViewUtils

/*
Zweck:
- Steuert eine Frage mit einer einzelnen Auswahl aus einer Dropdown-Liste (Spinner).
- Baut die Optionen dynamisch auf, lokalisiert Texte, stellt responsive Typografie her und kann vorhandene Antworten aus der lokalen Room-DB restaurieren.
*/

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

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

    override fun bind(layout: View, question: QuestionItem) {
        if (question !is QuestionItem.StringSpinnerQuestion) return

        this.layout = layout
        this.question = question

        val questionTextView = layout.findViewById<TextView>(R.id.question)
        val textView = layout.findViewById<TextView>(R.id.textView)
        val spinner = layout.findViewById<Spinner>(R.id.string_spinner)

        // Texte setzen
        questionTextView.text = question.question?.let { LanguageManager.getText(languageID, it) } ?: ""
        textView.text = question.textKey?.let { LanguageManager.getText(languageID, it) } ?: ""

        // Textgrößen prozentual zur Bildschirmhöhe
        ViewUtils.setTextSizePercentOfScreenHeight(textView,         0.03f)
        ViewUtils.setTextSizePercentOfScreenHeight(questionTextView, 0.03f)

        val options = buildOptionsList()

        // vorhandene Auswahl (falls vorhanden)
        val savedSelection = question.question?.let { answers[it] as? String }

        // Spinner aufsetzen
        ViewUtils.setupResponsiveSpinner(context, spinner, options, savedSelection)

        // Falls noch keine Antwort im Map: aus DB laden
        val answerMapKey = question.question ?: (question.id ?: "")
        if (answerMapKey.isNotBlank() && !answers.containsKey(answerMapKey)) {
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val clientCode = GlobalValues.LAST_CLIENT_CODE
                    if (clientCode.isNullOrBlank()) return@launch

                    val allAnswersForClient = MyApp.database.answerDao().getAnswersForClient(clientCode)
                    val myQuestionId = questionnaireMeta + "-" + question.question
                    val dbAnswer = allAnswersForClient.find { it.questionId == myQuestionId }?.answerValue

                    if (!dbAnswer.isNullOrBlank()) {
                        withContext(Dispatchers.Main) {
                            answers[answerMapKey] = dbAnswer
                            val index = options.indexOf(dbAnswer)
                            if (index >= 0) spinner.setSelection(index)
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }

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

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

    override fun validate(): Boolean {
        val spinner = layout.findViewById<Spinner>(R.id.string_spinner)
        val selected = spinner.selectedItem as? String
        val prompt = LanguageManager.getText(languageID, "choose_answer")

        return if (selected.isNullOrEmpty() || selected == prompt) {
            showToast(LanguageManager.getText(languageID, "select_one_answer"))
            false
        } else {
            true
        }
    }

    override fun saveAnswer() {
        val spinner = layout.findViewById<Spinner>(R.id.string_spinner)
        val selected = spinner.selectedItem as? String ?: return
        question.question?.let { key -> answers[key] = selected }
    }

    private fun buildOptionsList(): List<String> {
        return if (question.id == "q11") {
            Countries.getAllCountries(languageID)
        } else {
            val prompt = LanguageManager.getText(languageID, "choose_answer")
            listOf(prompt) + question.options
        }
    }

}
