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

package xyz.apiote.bimba.czwek.search

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import xyz.apiote.bimba.czwek.databinding.ActivityLineGraphBinding
import xyz.apiote.bimba.czwek.repo.OnlineRepository
import xyz.apiote.bimba.czwek.repo.TrafficResponseException
import xyz.apiote.bimba.czwek.search.ui.SectionsPagerAdapter

class LineGraphActivity : AppCompatActivity() {

	private lateinit var binding: ActivityLineGraphBinding
	private lateinit var sectionsPagerAdapter: SectionsPagerAdapter

	override fun onCreate(savedInstanceState: Bundle?) {
		enableEdgeToEdge()
		super.onCreate(savedInstanceState)

		binding = ActivityLineGraphBinding.inflate(layoutInflater)
		setContentView(binding.root)

		ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, windowInsets ->
			val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
			v.updatePadding(top = insets.top, left = insets.left, right = insets.right)
			windowInsets
		}

		val lineName = intent.getStringExtra("lineName")!!
		val lineID = intent.getStringExtra("lineID")!!
		val feedID = intent.getStringExtra("feedID")!!
		binding.title.text = lineName
		getGraph(lineName, lineID, feedID)
	}

	private fun getGraph(
		lineName: String,
		lineID: String,
		feedID: String,
	) {
		MainScope().launch {
			try {
				val repository = OnlineRepository()
				val line = repository.getLine(this@LineGraphActivity, feedID, lineName, lineID)
				line?.let {
					sectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager, it)
					val viewPager: ViewPager = binding.viewPager
					viewPager.adapter = sectionsPagerAdapter
					val tabs: TabLayout = binding.tabs
					// todo [optimisation] hangs before changing progress to graph
					tabs.setupWithViewPager(viewPager)
					binding.lineOverlay.visibility = View.GONE
					binding.viewPager.visibility = View.VISIBLE
				}
			} catch (e: TrafficResponseException) {
				showError(e.error)
				Log.w("Line", "$e")
			}
		}
	}

	private fun showError(e: xyz.apiote.bimba.czwek.api.Error) {
		binding.lineProgress.visibility = View.GONE
		binding.errorImage.visibility = View.VISIBLE
		binding.errorText.visibility = View.VISIBLE
		binding.errorText.text = getString(e.stringResource)
		binding.errorImage.setImageDrawable(AppCompatResources.getDrawable(this, e.imageResource))
	}
}