package partisan.weforge.xyz.pulse

import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.AdapterView
import android.widget.CompoundButton
import android.widget.Spinner
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.core.content.getSystemService
import partisan.weforge.xyz.pulse.databinding.FragmentPopupSettingsBinding

class PopupSettingsFragment : Fragment() {

    private var _binding: FragmentPopupSettingsBinding? = null
    private val binding get() = _binding!!

    private lateinit var prefs: Preferences
    private lateinit var window: PopupWindow

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPopupSettingsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        updateSpinner()
        (requireActivity() as? MainActivity)?.apply {
            setAppBarTitle(getString(R.string.settings_name), getString(R.string.popup_name))
            setupPopupToggle(true, prefs.popupEnabled) { isChecked ->
                prefs.popupEnabled = isChecked
                updateControls(isChecked)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        (requireActivity() as? MainActivity)?.setupPopupToggle(false)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        prefs = Preferences(requireContext())
        window = PopupWindow(requireContext(), null)

        binding.popupPreview.setOnClickListener {
            window.preview(false)
        }
        binding.popupPreview.setOnLongClickListener {
            window.preview(true)
            true
        }

        binding.redirectionDelay.value = (prefs.redirectionDelay / 1000).toFloat()
        binding.redirectionDelay.setLabelFormatter {
            String.format("%.1f", it)
        }
        binding.redirectionDelay.addOnChangeListener { _, value, _ ->
            prefs.redirectionDelay = (value * 1000).toLong()
        }

        updateSpinner()

        val screenHeight = getScreenHeightPx()
        binding.popupHeightSlider.valueFrom = 0f
        binding.popupHeightSlider.valueTo = screenHeight.toFloat()
        binding.popupHeightSlider.value = prefs.popupPosition.toFloat()
        binding.popupHeightSlider.addOnChangeListener { _, value, _ ->
            prefs.popupPosition = value.toInt().coerceIn(0, screenHeight)
        }

        updateControls(prefs.popupEnabled)
    }

    private fun updateControls(enabled: Boolean) {
        binding.redirectionDelay.isEnabled = enabled
        binding.popupHeightSlider.isEnabled = enabled
        binding.popupPreview.isEnabled = enabled
        binding.popupEffectSpinner.isEnabled = enabled
        binding.popupEffectLabel.isEnabled = enabled
    }

    private fun getScreenHeightPx(): Int {
        val wm = requireContext().getSystemService<android.view.WindowManager>()!!
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val bounds: Rect = wm.currentWindowMetrics.bounds
            bounds.height()
        } else {
            val metrics = DisplayMetrics()
            @Suppress("DEPRECATION")
            requireActivity().windowManager.defaultDisplay.getMetrics(metrics)
            metrics.heightPixels
        }
    }

    private fun updateSpinner() {
        val allEffects = Preferences.PopupEffect.values()
        val effectLabels = resources.getStringArray(R.array.popup_effects)

        val availableEffects = prefs.getAvailablePopupEffects() + listOf(
            Preferences.PopupEffect.NONE,
            Preferences.PopupEffect.RANDOM
        )

        val displayNames = allEffects.mapIndexed { index, effect ->
            val baseName = effectLabels.getOrElse(index) { effect.name }
            if (!prefs.isDonationActivated && effect !in availableEffects)
                "$baseName 🔒"
            else
                baseName
        }

        val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, displayNames)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.popupEffectSpinner.adapter = adapter

        binding.popupEffectSpinner.setSelection(prefs.popupEffect.ordinal)

        binding.popupEffectSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
                val selectedEffect = allEffects[position]
                if (!prefs.isDonationActivated &&
                    selectedEffect !in prefs.getAvailablePopupEffects() &&
                    selectedEffect != Preferences.PopupEffect.NONE &&
                    selectedEffect != Preferences.PopupEffect.RANDOM
                ) {
                    Toast.makeText(requireContext(), getString(R.string.donate_lock), Toast.LENGTH_SHORT).show()
                    binding.popupEffectSpinner.setSelection(prefs.popupEffect.ordinal)
                } else {
                    prefs.popupEffect = selectedEffect
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
