package partisan.weforge.xyz.pulse

import android.os.Bundle
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.FragmentServiceSettingsBinding

class ServiceSettingsFragment : Fragment() {

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

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

    override fun onResume() {
        super.onResume()
        (requireActivity() as? MainActivity)?.setAppBarTitle(
            getString(R.string.settings_name),
            getString(R.string.services_name)
        )
    }

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

        val available = 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 storedOrder = Preferences(requireContext()).getServiceOrder()

        val ordered = storedOrder.mapNotNull { mime ->
            available.find { it.mimetype == mime }
        }.toMutableList()

        // Add any missing services that weren't stored (e.g., first run)
        val missing = available.filterNot { s -> ordered.any { it.mimetype == s.mimetype } }
        ordered += missing

        val prefs = Preferences(requireContext())

        val adapter = ServiceAdapter(
            context = requireContext(),
            services = ordered,
            onReordered = { updatedList ->
                val newOrder = updatedList.map { it.mimetype }
                prefs.setServiceOrder(newOrder)
            }
        )

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

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

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

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