package com.dano.test1.ui

import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.dano.test1.LanguageManager
import com.dano.test1.MainActivity
import com.dano.test1.MyApp
import kotlinx.coroutines.*
import com.dano.test1.data.CompletedQuestionnaire
import com.dano.test1.questionnaire.GlobalValues

class EditButtonHandler(
    private val activity: MainActivity,
    private val editButton: Button,
    private val editText: EditText,
    private val languageIDProvider: () -> String,
    private val questionnaireFiles: Map<Button, String>,
    private val buttonPoints: MutableMap<String, Int>,
    private val updateButtonTexts: () -> Unit,
    private val setButtonsEnabled: (List<Button>, Boolean) -> Unit,
    private val setUiFreeze: (Boolean) -> Unit,
    private val triggerLoad: () -> Unit
) {

    fun setup() {
        editButton.text = LanguageManager.getText(languageIDProvider(), "edit")
        editButton.setOnClickListener { handleEditButtonClick() }
    }

    private fun handleEditButtonClick() {
        val typed = editText.text.toString().trim()
        val desiredCode = when {
            typed.isNotBlank() -> typed
            !GlobalValues.LOADED_CLIENT_CODE.isNullOrBlank() -> GlobalValues.LOADED_CLIENT_CODE!!
            else -> ""
        }

        if (desiredCode.isBlank()) {
            val message = LanguageManager.getText(languageIDProvider(), "please_client_code")
            Toast.makeText(activity, message, Toast.LENGTH_SHORT).show()
            return
        }

        GlobalValues.LAST_CLIENT_CODE = desiredCode

        val needLoad = GlobalValues.LOADED_CLIENT_CODE?.equals(desiredCode) != true
        if (needLoad) {
            setUiFreeze(true)  // Zwischenzustände unterdrücken
            triggerLoad()
        }

        CoroutineScope(Dispatchers.IO).launch {
            val loadedOk = waitUntilClientLoaded(desiredCode, timeoutMs = 2500, stepMs = 50)
            if (!loadedOk) {
                withContext(Dispatchers.Main) {
                    val msg = LanguageManager.getText(languageIDProvider(), "open_client_via_load")
                    Toast.makeText(activity, msg, Toast.LENGTH_LONG).show()
                    setUiFreeze(false)
                }
                return@launch
            }

            val completedEntries: List<CompletedQuestionnaire> =
                MyApp.database.completedQuestionnaireDao().getAllForClient(desiredCode)

            val completedFiles = completedEntries.filter { it.isDone }.map { it.questionnaireId.lowercase() }

            buttonPoints.clear()
            for (entry in completedEntries) {
                if (entry.isDone) {
                    buttonPoints[entry.questionnaireId] = entry.sumPoints ?: 0
                }
            }

            withContext(Dispatchers.Main) {
                updateButtonTexts()
                val enabledButtons = questionnaireFiles.filter { (_, fileName) ->
                    completedFiles.any { completedId -> fileName.lowercase().contains(completedId) }
                }.keys.toList()
                setButtonsEnabled(enabledButtons, true)
                setUiFreeze(false)
            }
        }
    }

    private suspend fun waitUntilClientLoaded(expectedCode: String, timeoutMs: Long, stepMs: Long): Boolean {
        if (GlobalValues.LOADED_CLIENT_CODE?.equals(expectedCode) == true) return true
        var waited = 0L
        while (waited < timeoutMs) {
            delay(stepMs)
            waited += stepMs
            if (GlobalValues.LOADED_CLIENT_CODE?.equals(expectedCode) == true) return true
        }
        return GlobalValues.LOADED_CLIENT_CODE?.equals(expectedCode) == true
    }
}
