package partisan.weforge.xyz.pulse

import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
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 onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

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

        val screenHeight = getScreenHeightPx()

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

            popupEnabledCheckbox.isChecked = prefs.popupEnabled
            popupEnabledCheckbox.setOnCheckedChangeListener { _, isChecked ->
                prefs.popupEnabled = isChecked
            }

            popupPreview.setOnClickListener {
                window.preview()
            }

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

            val services = listOf(
                ServiceEntry(
                    "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.call",
                    R.string.destination_signal,
                    requireContext().isServiceEnabled("vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.call")
                ),
                ServiceEntry(
                    "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call",
                    R.string.destination_telegram,
                    requireContext().isServiceEnabled("vnd.android.cursor.item/vnd.org.telegram.messenger.android.call")
                ),
                ServiceEntry(
                    "vnd.android.cursor.item/vnd.ch.threema.app.call",
                    R.string.destination_threema,
                    requireContext().isServiceEnabled("vnd.android.cursor.item/vnd.ch.threema.app.call")
                ),
                ServiceEntry(
                    "vnd.android.cursor.item/vnd.com.whatsapp.voip.call",
                    R.string.destination_whatsapp,
                    requireContext().isServiceEnabled("vnd.android.cursor.item/vnd.com.whatsapp.voip.call")
                ),
            )

            val adapter = ServiceAdapter(
                context = requireContext(),
                services = services.toMutableList(),
                onReordered = { updatedList ->
                    updatedList.forEachIndexed { index, entry ->
                        requireContext().setServicePriority(entry.mimetype, index)
                    }
                }
            )

            serviceRecycler.adapter = adapter
            serviceRecycler.layoutManager = LinearLayoutManager(requireContext())

            val touchHelper = ItemTouchHelper(adapter.dragHelper)
            touchHelper.attachToRecyclerView(serviceRecycler)

            adapter.setDragStartListener { viewHolder ->
                touchHelper.startDrag(viewHolder)
            }
        }
    }

    private fun getScreenHeightPx(): Int {
        val metrics = DisplayMetrics()
        requireActivity().windowManager.defaultDisplay.getMetrics(metrics)
        return metrics.heightPixels
    }

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