package partisan.weforge.xyz.pulse

import android.content.ContentResolver
import android.os.Bundle
import android.provider.ContactsContract
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.graphics.Color
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import partisan.weforge.xyz.pulse.databinding.FragmentContactsBinding

class ContactsFragment : Fragment() {

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

    private lateinit var prefs: Preferences

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

    override fun onResume() {
        super.onResume()
        (requireActivity() as? MainActivity)?.apply {
            setAppBarTitle(getString(R.string.settings_name), getString(R.string.whitelist_name))
            setupPopupToggle(true, prefs.isBlacklistEnabled) { isChecked ->
                prefs.isBlacklistEnabled = isChecked
                binding.contactRecycler.isEnabled = isChecked
                binding.contactRecycler.alpha = if (isChecked) 1f else 0.4f
            }
        }

        // Initial state
        binding.contactRecycler.isEnabled = prefs.isBlacklistEnabled
        binding.contactRecycler.alpha = if (prefs.isBlacklistEnabled) 1f else 0.4f
    }

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

    private lateinit var adapter: ContactAdapter
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        prefs = Preferences(requireContext())

        val contacts = getContacts()
        adapter = ContactAdapter(prefs, contacts)

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

        binding.contactSearch.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean = false
            override fun onQueryTextChange(newText: String?): Boolean {
                adapter.filter(newText ?: "")
                return true
            }
        })

        val searchView = binding.contactSearch

        searchView.setIconifiedByDefault(false)
        searchView.isIconified = false
        searchView.isSubmitButtonEnabled = false
        searchView.clearFocus()

        val editText = searchView.findViewById<androidx.appcompat.widget.SearchView.SearchAutoComplete>(
            androidx.appcompat.R.id.search_src_text
        )
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.setTextColor(Color.WHITE)
        editText.setHintTextColor(Color.LTGRAY)

        val searchPlate = searchView.findViewById<View>(androidx.appcompat.R.id.search_plate)
        searchPlate.setBackgroundColor(Color.TRANSPARENT)
        searchPlate.setPadding(0, 0, 0, 0)
    }

    private fun getContacts(): List<ContactEntry> {
        val results = mutableListOf<ContactEntry>()
        val resolver: ContentResolver = requireContext().contentResolver

        val projection = arrayOf(
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
        )

        val cursor = resolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection,
            null,
            null,
            "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} ASC"
        )

        cursor?.use {
            val nameIndex = it.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
            val numberIndex = it.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)

            while (it.moveToNext()) {
                val name = it.getString(nameIndex)
                val number = it.getString(numberIndex)
                if (!name.isNullOrBlank() && !number.isNullOrBlank()) {
                    results.add(ContactEntry(name, number))
                }
            }
        }

        return results
    }

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