// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.settings.feeds

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.edit
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.transition.TransitionManager
import com.google.android.material.transition.MaterialFade
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.api.Server
import xyz.apiote.bimba.czwek.dashboard.MainActivity
import xyz.apiote.bimba.czwek.databinding.ActivityFeedChooserBinding
import xyz.apiote.bimba.czwek.onboarding.FirstRunActivity
import xyz.apiote.bimba.czwek.repo.FeedInfo
import xyz.apiote.bimba.czwek.settings.ServerChooserActivity

// TODO on internet connection -> getServer
// TODO swipe to refresh?

class FeedChooserActivity : AppCompatActivity() {
	companion object {
		const val PREFERENCES_NAME = "shp"
	}
	private lateinit var viewModel: FeedsViewModel
	private var _binding: ActivityFeedChooserBinding? = null
	private val binding get() = _binding!!

	private lateinit var adapter: BimbaFeedInfoAdapter

	override fun onCreate(savedInstanceState: Bundle?) {
		enableEdgeToEdge()
		super.onCreate(savedInstanceState)
		_binding = ActivityFeedChooserBinding.inflate(layoutInflater)
		setContentView(binding.root)

		ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, windowInsets ->
			windowInsets.displayCutout?.safeInsetRight?.let { binding.resultsRecycler.updatePadding(right = it) }
			windowInsets.displayCutout?.safeInsetLeft?.let { binding.resultsRecycler.updatePadding(left = it) }
			val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
			v.updatePadding(
				right = insets.right,
				left = insets.left,
				top = insets.top,
				bottom = insets.bottom
			)
			windowInsets
		}

		viewModel = ViewModelProvider(this)[FeedsViewModel::class.java]

		migrateFeedsSettings(this)
		viewModel.loadSettings(this)

		setUpRecycler()

		getServer()

		binding.searchBar.editText?.doAfterTextChanged { editable ->
			if (editable != null) {
				updateItems((viewModel.feeds.value ?: emptyMap()).values.filter {
					it.name.contains(editable, true)
				}, null)
			}
		}

		binding.button.setOnClickListener {
			moveOn()
		}
	}

	private fun showBottomSheet(feedID: String) {
		FeedBottomSheet(
			feedID,
			viewModel.feeds.value!!,
			viewModel.settings.value ?: FeedsSettings(mutableMapOf())
		) { settings ->
			if (settings != null) {
				val fade = MaterialFade().apply {
					addTarget(R.id.feed_switch_container)
					duration = 500L
				}
				TransitionManager.beginDelayedTransition(binding.root, fade)
				viewModel.setSettings(feedID, settings)
				updateItems(null, viewModel.settings.value, false)
				adapter.notifyItemChanged(adapter.getItemPosition(feedID))
			}
		}.show(supportFragmentManager, FeedBottomSheet.TAG)
	}

	private fun setUpRecycler() {
		binding.resultsRecycler.layoutManager = LinearLayoutManager(this)
		adapter =
			BimbaFeedInfoAdapter(
				layoutInflater,
				(viewModel.feeds.value ?: emptyMap()).map { it.value }.sortedBy { it.name },
				viewModel.settings.value!!,
				{
					showBottomSheet(it)
				},
				{ feedID, isEnabled -> viewModel.setEnabled(feedID, isEnabled) }
			)
		binding.resultsRecycler.adapter = adapter
	}

	private fun getServer() {
		binding.progress.visibility = View.VISIBLE
		binding.resultsRecycler.visibility = View.GONE
		viewModel.loadFeeds(this)
		viewModel.feeds.observe(this) { feeds ->
			updateItems(feeds.map { it.value }, null)
		}
		viewModel.error.observe(this) {
			showError(it.imageResource, it.stringResource)
		}
	}

	private fun moveOn() {
		viewModel.settings.value?.save(this, Server.get(this))
		val preferences = getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE)
		preferences.edit(true) {
			putBoolean(ServerChooserActivity.IN_FEEDS_TRANSACTION, false)
		}
		if (FirstRunActivity.getFirstRun(this)) {
			val intent = Intent(this, MainActivity::class.java)
			startActivity(intent)
		}
		finish()
	}

	private fun showError(image: Int, text: Int) {
		binding.progress.visibility = View.GONE
		binding.resultsRecycler.visibility = View.GONE
		binding.errorImage.apply {
			visibility = View.VISIBLE
			setImageDrawable(AppCompatResources.getDrawable(this@FeedChooserActivity, image))
		}
		binding.errorText.apply {
			visibility = View.VISIBLE
			setText(text)
		}

	}

	private fun updateItems(
		feeds: List<FeedInfo>?,
		feedsSettings: FeedsSettings?,
		notify: Boolean = true
	) {
		binding.feedsOverlay.visibility = View.GONE
		binding.resultsRecycler.visibility = View.VISIBLE
		binding.searchBar.visibility = if ((viewModel.feeds.value?.size ?: 0) > 12) {
			View.VISIBLE
		} else {
			View.GONE
		}
		binding.button.visibility = View.VISIBLE
		adapter.update(feeds, feedsSettings, notify)
		if (feeds?.isEmpty() == true) {
			showError(R.drawable.error_search, R.string.error_404)
		}
	}
}