package com.dano.test1.ui

import android.app.Dialog
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import com.dano.test1.R
import com.google.android.material.button.MaterialButton

/**
 * Branded dialogs for logout: blocked (info/warning) and confirmation before sign-out.
 */
object LogoutDialogs {

    enum class Tone { Info, Warning, Logout }

    fun showBlocked(
        activity: AppCompatActivity,
        languageId: String,
        title: String,
        message: String,
        details: String? = null,
        tone: Tone = Tone.Warning,
    ) {
        show(
            activity = activity,
            tone = tone,
            title = title,
            message = message,
            details = details,
            primaryLabel = msg(languageId, "ok", "OK"),
            secondaryLabel = null,
            onPrimary = null,
        )
    }

    fun showConfirm(
        activity: AppCompatActivity,
        languageId: String,
        onConfirm: () -> Unit,
    ) {
        show(
            activity = activity,
            tone = Tone.Logout,
            title = msg(languageId, "logout_confirm_title", "Log out?"),
            message = msg(
                languageId,
                "logout_confirm_message",
                "All data on this device will be removed. You will need to sign in again.",
            ),
            details = null,
            primaryLabel = msg(languageId, "logout_confirm_action", msg(languageId, "logout", "Log out")),
            secondaryLabel = msg(languageId, "cancel", "Cancel"),
            onPrimary = onConfirm,
        )
    }

    fun showAction(
        activity: AppCompatActivity,
        languageId: String,
        title: String,
        message: String,
        details: String? = null,
        tone: Tone = Tone.Info,
        primaryLabel: String,
        secondaryLabel: String,
        onPrimary: () -> Unit,
    ) {
        show(
            activity = activity,
            tone = tone,
            title = title,
            message = message,
            details = details,
            primaryLabel = primaryLabel,
            secondaryLabel = secondaryLabel,
            onPrimary = onPrimary,
        )
    }

    private fun show(
        activity: AppCompatActivity,
        tone: Tone,
        title: String,
        message: String,
        details: String?,
        primaryLabel: String,
        secondaryLabel: String?,
        onPrimary: (() -> Unit)?,
    ) {
        val dialog = Dialog(activity)
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        val root = LayoutInflater.from(activity).inflate(R.layout.dialog_app_message, null)
        val scroll = root.findViewById<NestedScrollView>(R.id.dialogScroll)
        val iconContainer = root.findViewById<View>(R.id.dialogIconContainer)
        val icon = root.findViewById<ImageView>(R.id.dialogIcon)
        val titleView = root.findViewById<TextView>(R.id.dialogTitle)
        val messageView = root.findViewById<TextView>(R.id.dialogMessage)
        val detailsScroll = root.findViewById<NestedScrollView>(R.id.dialogDetailsScroll)
        val detailsView = root.findViewById<TextView>(R.id.dialogDetails)
        val btnPrimary = root.findViewById<MaterialButton>(R.id.dialogBtnPrimary)
        val btnSecondary = root.findViewById<MaterialButton>(R.id.dialogBtnSecondary)

        when (tone) {
            Tone.Info -> {
                iconContainer.setBackgroundResource(R.drawable.bg_dialog_icon_info)
                icon.setImageResource(R.drawable.ic_dialog_info_24)
                icon.imageTintList = null
            }
            Tone.Warning -> {
                iconContainer.setBackgroundResource(R.drawable.bg_dialog_icon_warning)
                icon.setImageResource(R.drawable.ic_dialog_warning_24)
                icon.imageTintList = null
            }
            Tone.Logout -> {
                iconContainer.setBackgroundResource(R.drawable.bg_dialog_icon_logout)
                icon.setImageResource(R.drawable.ic_lock_24)
                icon.imageTintList = ColorStateList.valueOf(
                    ContextCompat.getColor(activity, R.color.brand_destructive_text),
                )
            }
        }

        titleView.text = title
        messageView.text = message

        if (!details.isNullOrBlank()) {
            detailsScroll.visibility = View.VISIBLE
            detailsView.text = details.trim()
            val maxDetailsHeight = activity.resources.getDimensionPixelSize(R.dimen.dialog_details_max_height)
            detailsScroll.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    detailsScroll.viewTreeObserver.removeOnGlobalLayoutListener(this)
                    if (detailsScroll.height > maxDetailsHeight) {
                        detailsScroll.layoutParams = detailsScroll.layoutParams.apply {
                            height = maxDetailsHeight
                        }
                    }
                }
            })
        } else {
            detailsScroll.visibility = View.GONE
        }

        btnPrimary.text = primaryLabel
        if (tone == Tone.Logout) {
            btnPrimary.backgroundTintList = ColorStateList.valueOf(
                ContextCompat.getColor(activity, R.color.brand_destructive_text),
            )
            btnPrimary.setTextColor(ContextCompat.getColor(activity, R.color.white))
        } else {
            btnPrimary.backgroundTintList = ColorStateList.valueOf(
                ContextCompat.getColor(activity, R.color.brand_purple),
            )
            btnPrimary.setTextColor(ContextCompat.getColor(activity, R.color.white))
        }

        btnPrimary.setOnClickListener {
            dialog.dismiss()
            onPrimary?.invoke()
        }

        if (secondaryLabel != null) {
            btnSecondary.visibility = View.VISIBLE
            btnSecondary.text = secondaryLabel
            btnSecondary.setOnClickListener { dialog.dismiss() }
            // Safer on small screens: cancel above the destructive / primary action.
            (btnPrimary.parent as? ViewGroup)?.let { buttonRow ->
                buttonRow.removeView(btnPrimary)
                buttonRow.removeView(btnSecondary)
                buttonRow.addView(btnSecondary)
                buttonRow.addView(btnPrimary)
            }
        } else {
            btnSecondary.visibility = View.GONE
        }

        dialog.setContentView(root)
        dialog.setCancelable(true)
        dialog.show()

        dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        val dm = activity.resources.displayMetrics
        val maxDialogHeight = (dm.heightPixels * 0.85f).toInt()
        scroll.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                scroll.viewTreeObserver.removeOnGlobalLayoutListener(this)
                if (scroll.height > maxDialogHeight) {
                    scroll.layoutParams = scroll.layoutParams.apply {
                        height = maxDialogHeight
                    }
                }
            }
        })
    }

    private fun msg(languageId: String, key: String, fallback: String): String =
        SessionLogout.message(languageId, key, fallback)
}
