package com.tomhempel.rbarometer.questionnaire.handlers

import android.content.Context
import android.view.View
import android.widget.*
import kotlinx.coroutines.*
import com.tomhempel.rbarometer.questionnaire.AnswerLookup
import com.tomhempel.rbarometer.questionnaire.AnswerRestoreHelper
import com.tomhempel.rbarometer.questionnaire.QuestionFlowResolver
import com.tomhempel.rbarometer.questionnaire.SpinnerAnswerRules
import com.tomhempel.rbarometer.questionnaire.SpinnerSelectionHelper
import com.tomhempel.rbarometer.LanguageManager
import com.tomhempel.rbarometer.questionnaire.QuestionHandler
import com.tomhempel.rbarometer.questionnaire.QuestionItem
import com.tomhempel.rbarometer.questionnaire.QuestionNotesHelper
import com.tomhempel.rbarometer.R
import com.tomhempel.rbarometer.utils.ViewUtils

class HandlerValueSpinner(
    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.ValueSpinnerQuestion
    private lateinit var spinnerItems: List<String>

    private var spinnerAdapterReady = false

    override fun bind(layout: View, question: QuestionItem) {
        if (question !is QuestionItem.ValueSpinnerQuestion) 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.value_spinner)

        QuestionNotesHelper.bind(layout, languageID, question.noteBeforeKey, question.noteAfterKey)

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

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

        val prompt = LanguageManager.getText(languageID, "choose_answer")
        spinnerItems = listOf(prompt) + if (question.range != null) {
            (question.range.min..question.range.max).map { it.toString() }
        } else {
            (question.options ?: emptyList()).map { it.value.toString() }
        }

        val answerMapKey = question.question
        val savedValue = AnswerLookup.valueSpinnerValue(answers, question)
        applySpinnerSelection(spinner, savedValue)

        if (savedValue.isNullOrBlank()) {
            AnswerRestoreHelper.restoreIfMissing(
                CoroutineScope(Dispatchers.Main),
                questionnaireMeta,
                answerMapKey,
            ) { dbAnswer ->
                answers[answerMapKey] = dbAnswer
                answers[question.id] = dbAnswer
                applySpinnerSelection(spinner, dbAnswer)
            }
        }

        layout.findViewById<Button>(R.id.Qnext)?.setOnClickListener {
            if (validate()) {
                saveAnswer()
                val selectedValue = (spinner.selectedItem as? String)?.toIntOrNull()
                val nextId = QuestionFlowResolver.nextQuestionIdForValueSpinner(question, selectedValue)
                if (!nextId.isNullOrEmpty()) {
                    goToQuestionById(nextId)
                } else {
                    goToNextQuestion()
                }
            }
        }

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

    fun restoreSelectionFromAnswers() {
        if (!::layout.isInitialized) return
        val spinner = layout.findViewById<Spinner>(R.id.value_spinner) ?: return
        applySpinnerSelection(spinner, AnswerLookup.valueSpinnerValue(answers, question))
    }

    override fun validate(): Boolean {
        val spinner = layout.findViewById<Spinner>(R.id.value_spinner)
        val selected = spinner.selectedItem as? String
        return if (SpinnerAnswerRules.isUnselected(languageID, selected)) {
            showToast(LanguageManager.getText(languageID, "select_one_answer"))
            false
        } else {
            true
        }
    }

    private fun applySpinnerSelection(spinner: Spinner, saved: String?) {
        ensureSpinnerAdapter(spinner)
        val index = selectionIndexForValue(saved) ?: return
        if ((spinner.adapter?.count ?: 0) > index) {
            spinner.setSelection(index, false)
        }
    }

    private fun ensureSpinnerAdapter(spinner: Spinner) {
        if (spinnerAdapterReady && spinner.adapter != null) return
        ViewUtils.setupResponsiveSpinner(context, spinner, spinnerItems, null)
        spinnerAdapterReady = true
    }

    private fun selectionIndexForValue(saved: String?): Int? {
        SpinnerSelectionHelper.indexForSavedValue(languageID, spinnerItems, saved)
            .takeIf { it >= 0 }
            ?.let { return it }
        val numeric = saved?.trim()?.toDoubleOrNull()?.toInt() ?: return null
        val idx = spinnerItems.indexOfFirst { it.trim().toIntOrNull() == numeric }
        return idx.takeIf { it >= 0 }
    }

    override fun saveAnswer() {
        val spinner = layout.findViewById<Spinner>(R.id.value_spinner)
        val selected = spinner.selectedItem as? String ?: return
        if (SpinnerAnswerRules.isUnselected(languageID, selected)) return
        val stored = selected.trim()
        answers[question.question] = stored
        answers[question.id] = stored
    }
}
