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

package xyz.apiote.bimba.czwek.departures

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.content.res.Configuration.UI_MODE_NIGHT_MASK
import android.content.res.Configuration.UI_MODE_NIGHT_UNDEFINED
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.TooltipCompat
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textview.MaterialTextView
import org.osmdroid.tileprovider.tilesource.TileSourceFactory
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.CustomZoomButtonsController
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.Marker
import org.osmdroid.views.overlay.TilesOverlay
import org.osmdroid.views.overlay.gestures.RotationGestureOverlay
import org.w3c.dom.Text
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.dpToPixelI
import xyz.apiote.bimba.czwek.repo.Alert
import xyz.apiote.bimba.czwek.repo.CongestionLevel
import xyz.apiote.bimba.czwek.repo.Departure
import xyz.apiote.bimba.czwek.repo.DepartureItem
import xyz.apiote.bimba.czwek.repo.OccupancyStatus
import xyz.apiote.bimba.czwek.repo.Vehicle
import xyz.apiote.bimba.czwek.units.UnitSystem
import java.time.ZoneId
import java.time.ZonedDateTime

class BimbaDepartureViewHolder(itemView: View) : ViewHolder(itemView) {
	val root: View = itemView.findViewById(R.id.departure)
	val lineIcon: ImageView = itemView.findViewById(R.id.line_icon)
	val departureTime: TextView = itemView.findViewById(R.id.departure_time)
	val lineName: TextView = itemView.findViewById(R.id.departure_line)
	val headsign: TextView = itemView.findViewById(R.id.departure_headsign)
	val timeStatus: ImageView = itemView.findViewById(R.id.time_status)

	companion object {
		fun bind(
			departure: Departure,
			holder: BimbaDepartureViewHolder?,
			context: Context?,
			showAsTime: Boolean,
			onClickListener: (Departure) -> Unit,
			showingTerminusArrivals: String
		) {
			holder?.root?.setOnClickListener {
				onClickListener(departure)
			}
			holder?.lineIcon?.setImageDrawable(departure.vehicle.Line.icon(context!!))
			holder?.lineIcon?.contentDescription = departure.vehicle.Line.kind.name
			holder?.lineName?.text = departure.vehicle.Line.name
			holder?.headsign?.text =
				context?.getString(R.string.departure_headsign, departure.vehicle.Headsign)
			holder?.headsign?.contentDescription =
				context?.getString(
					R.string.departure_headsign_content_description,
					departure.vehicle.Headsign
				)

			when {
				departure.isRealtime -> {
					holder?.timeStatus?.setImageResource(R.drawable.radar)
					holder?.timeStatus?.contentDescription =
						context?.getString(R.string.realtime_content_description)
					holder?.timeStatus?.let {
						TooltipCompat.setTooltipText(
							it,
							context?.getString(R.string.realtime_content_description)
						)
					}
				}

				departure.exact -> {
					holder?.timeStatus?.setImageResource(R.drawable.calendar)
					holder?.timeStatus?.contentDescription =
						context?.getString(R.string.exact_content_description)
					holder?.timeStatus?.let {
						TooltipCompat.setTooltipText(
							it,
							context?.getString(R.string.exact_content_description)
						)
					}
				}

				else -> {
					holder?.timeStatus?.setImageResource(R.drawable.inexact)
					holder?.timeStatus?.contentDescription =
						context?.getString(R.string.inexact_content_description)
					holder?.timeStatus?.let {
						TooltipCompat.setTooltipText(
							it,
							context?.getString(R.string.inexact_content_description)
						)
					}
				}
			}

			holder?.departureTime?.text = departure.statusText(context, showAsTime)
			holder?.root?.alpha =
				if (departure.terminusArrival && showingTerminusArrivals == BimbaDeparturesAdapter.TERMINUS_ARRIVAL_GREY_OUT) {
					.5f
				} else {
					1f
				}
		}
	}
}

class BimbaAlertViewHolder(itemView: View) : ViewHolder(itemView) {
	val root: View = itemView.findViewById(R.id.alerts)
	val text: TextView = itemView.findViewById(R.id.alerts_text)
	val moreButton: Button = itemView.findViewById(R.id.more_button)

	companion object {
		fun bind(
			alerts: List<Alert>,
			holder: BimbaAlertViewHolder?,
			context: Context?
		) {
			val alertDescriptions = alerts.map { it.description }.filter { it != "" }
				.joinToString(separator = "\n")
			holder?.moreButton?.setOnClickListener {
				MaterialAlertDialogBuilder(context!!)
					.setTitle(R.string.alerts)
					.setPositiveButton(R.string.ok) { _, _ -> }
					.setMessage(alertDescriptions)
					.show()
			}
			holder?.moreButton?.visibility = if (alertDescriptions == "") View.GONE else View.VISIBLE
			holder?.text?.text = alerts.map {
				it.header.ifEmpty {
					context!!.getString(R.string.alert_header)
				}
			}.toSet().joinToString(separator = "\n")
		}
	}
}

class BimbaDeparturesAdapter(
	private val inflater: LayoutInflater,
	private val context: Context?,
	private var items: List<DepartureItem>,
	private val onClickListener: ((Departure) -> Unit),
) :
	RecyclerView.Adapter<ViewHolder>() {

	companion object {
		const val ALERT_ITEM_ID = "alert"

		// TODO to enum
		const val TERMINUS_ARRIVAL_SHOWING_KEY = "terminus_arrival_showing"
		const val TERMINUS_ARRIVAL_GREY_OUT = "grey_out"
		const val TERMINUS_ARRIVAL_HIDE = "hide"
		const val TERMINUS_ARRIVAL_SHOW = "show"
	}

	var showingTerminusArrivals: String = context?.let {
		PreferenceManager.getDefaultSharedPreferences(
			it
		).getString(TERMINUS_ARRIVAL_SHOWING_KEY, TERMINUS_ARRIVAL_GREY_OUT)
	}
		?: TERMINUS_ARRIVAL_GREY_OUT

	var lastUpdate: ZonedDateTime =
		ZonedDateTime.of(0, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault())
		private set
	private var showAsTime: Boolean = false

	inner class DiffUtilCallback(
		private val oldDepartures: List<DepartureItem>,
		private val newDepartures: List<DepartureItem>,
		private val showAsTimeChanged: Boolean,
	) : DiffUtil.Callback() {
		override fun getOldListSize() = oldDepartures.size

		override fun getNewListSize() = newDepartures.size

		override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
			(oldDepartures[oldItemPosition].departure?.ID
				?: ALERT_ITEM_ID) == (newDepartures[newItemPosition].departure?.ID ?: ALERT_ITEM_ID)

		override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
			val oldDeparture = oldDepartures[oldItemPosition]
			val newDeparture = newDepartures[newItemPosition]
			return if (oldDeparture.departure != null && newDeparture.departure != null) {
				!oldDeparture.departure.terminusArrival &&
						oldDeparture.departure.terminusArrival == newDeparture.departure.terminusArrival &&
						oldDeparture.departure.exact == newDeparture.departure.exact &&
						oldDeparture.departure.vehicle.Line == newDeparture.departure.vehicle.Line &&
						oldDeparture.departure.vehicle.Headsign == newDeparture.departure.vehicle.Headsign &&
						oldDeparture.departure.statusText(
							context,
							false,
							lastUpdate
						) == newDeparture.departure.statusText(context, false) && !showAsTimeChanged
			} else if (oldDeparture.alert.isNotEmpty() && newDeparture.alert.isEmpty()) {
				oldDeparture.alert == newDeparture.alert
			} else {
				false
			}
		}
	}

	private var departuresPositions: MutableMap<String, Int> = HashMap()

	init {
		items.forEachIndexed { i, departure ->
			departuresPositions[departure.departure?.ID ?: ALERT_ITEM_ID] = i
		}
	}

	override fun getItemViewType(position: Int): Int {
		return if (items[position].departure != null) {
			0
		} else {
			1
		}
	}

	override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
		if (viewType == 0) {
			val rowView = inflater.inflate(R.layout.departure, parent, false)
			return BimbaDepartureViewHolder(rowView)
		} else {
			val rowView = inflater.inflate(R.layout.alert, parent, false)
			return BimbaAlertViewHolder(rowView)
		}
	}

	override fun onBindViewHolder(holder: ViewHolder, position: Int) {
		if (holder is BimbaDepartureViewHolder) {
			BimbaDepartureViewHolder.bind(
				items[position].departure!!,
				holder,
				context,
				showAsTime,
				onClickListener,
				showingTerminusArrivals
			)
		} else {
			BimbaAlertViewHolder.bind(items[position].alert, holder as BimbaAlertViewHolder, context)
		}
	}

	override fun getItemCount(): Int = items.size

	fun get(id: String): DepartureItem? {
		val position = departuresPositions[id]
		return if (position == null) {
			null
		} else {
			items[position]
		}
	}

	fun update(
		departures: List<DepartureItem>,
		showAsTime: Boolean,
		areNewObserved: Boolean = false,
		leaveAlert: Boolean = false
	) {
		val newDepartures = if (leaveAlert && items.getOrNull(0)?.alert?.isNotEmpty() == true) {
			listOf(items[0]) + departures
		} else {
			departures
		}
		val newPositions: MutableMap<String, Int> = HashMap()
		newDepartures.forEachIndexed { i, departure ->
			newPositions[departure.departure?.ID ?: ALERT_ITEM_ID] = i
		}
		val diff = DiffUtil.calculateDiff(
			DiffUtilCallback(
				this.items,
				newDepartures,
				this.showAsTime != showAsTime
			)
		)

		this.showAsTime = showAsTime

		this.items = newDepartures
		departuresPositions = newPositions
		if (areNewObserved) {
			lastUpdate = ZonedDateTime.now()
		}
		diff.dispatchUpdatesTo(this)
	}

	fun refreshItems() {
		update(this.items, showAsTime)
	}
}

class DepartureBottomSheet(private var departure: Departure) : BottomSheetDialogFragment() {
	companion object {
		const val TAG = "DepartureBottomSheet"
	}

	private var cancelCallback: (() -> Unit)? = null

	fun setOnCancel(callback: () -> Unit) {
		cancelCallback = callback
	}

	override fun onCancel(dialog: DialogInterface) {
		super.onCancel(dialog)
		cancelCallback?.let { it() }
	}

	fun departureID(): String {
		return departure.ID
	}

	fun update(departure: Departure) {
		this.departure = departure
		view?.let { context?.let { ctx -> setContent(it, ctx, true) } }
	}

	private fun setContent(view: View, ctx: Context, updating: Boolean = false) {
		view.apply {
			findViewById<TextView>(R.id.time).text = departure.timeString(ctx)
			findViewById<TextView>(R.id.local_time).visibility =
				if (departure.time.Zone == ZoneId.systemDefault().id) {
					View.GONE
				} else {
					View.VISIBLE
				}

			findViewById<ImageView>(R.id.rt_icon).apply {
				visibility = if (departure.isRealtime) {
					View.VISIBLE
				} else {
					View.GONE
				}
			}
			findViewById<ImageView>(R.id.wheelchair_icon).apply {
				visibility = if (departure.vehicle.let {
						it.getCapability(Vehicle.Capability.LOW_FLOOR) || it.getCapability(Vehicle.Capability.LOW_ENTRY) || it.getCapability(
							Vehicle.Capability.RAMP
						)
					}) {
					View.VISIBLE
				} else {
					View.GONE
				}
			}

			findViewById<TextView>(R.id.line).apply {
				contentDescription = getString(
					R.string.vehicle_headsign_content_description,
					departure.vehicle.Line.name,
					departure.vehicle.Headsign
				)
				text = getString(
					R.string.vehicle_headsign,
					departure.vehicle.Line.name,
					departure.vehicle.Headsign
				)
			}


			departure.boardingText(ctx).let {
				findViewById<TextView>(R.id.boarding_text).text = it
					findViewById<ImageView>(R.id.boarding_icon).visibility = if (it == "") {
						View.GONE
					} else {
						View.VISIBLE
					}
			}
			UnitSystem.getSelected(requireContext()).let { us ->
				findViewById<TextView>(R.id.speed_text).apply {
					text =
						us.toString(context, us.speedUnit(departure.vehicle.Speed))
					contentDescription =
						us.speedUnit(departure.vehicle.Speed).contentDescription(requireContext(), us.base)
				}
			}

			findViewById<LinearLayout>(R.id.congestion).visibility =
				if (departure.vehicle.congestionLevel == CongestionLevel.UNKNOWN) View.GONE else View.VISIBLE
			findViewById<TextView>(R.id.congestion_text).text = departure.vehicle.congestion(ctx)

			findViewById<LinearLayout>(R.id.occupancy).visibility =
				if (departure.vehicle.occupancyStatus == OccupancyStatus.UNKNOWN) View.GONE else View.VISIBLE
			findViewById<TextView>(R.id.occupancy_text).text = departure.vehicle.occupancy(ctx)

			findViewById<ImageView>(R.id.ac).let {
				TooltipCompat.setTooltipText(
					it,
					getString(R.string.air_condition_content_description)
				)
				it.visibility =
					if (departure.vehicle.getCapability(Vehicle.Capability.AC)) View.VISIBLE else View.GONE
			}

			findViewById<ImageView>(R.id.bike).let {
				TooltipCompat.setTooltipText(
					it,
					getString(R.string.bicycles_allowed_content_description)
				)
				it.visibility =
					if (departure.vehicle.getCapability(Vehicle.Capability.BIKE)) {
						View.VISIBLE
					} else {
						View.GONE
					}
			}

			findViewById<ImageView>(R.id.voice).let {
				TooltipCompat.setTooltipText(
					it,
					getString(R.string.voice_announcements_content_description)
				)
				it.visibility =
					if (departure.vehicle.getCapability(Vehicle.Capability.VOICE)) {
						View.VISIBLE
					} else {
						View.GONE
					}
			}
			findViewById<ImageView>(R.id.ticket).let { ticketImage ->
				TooltipCompat.setTooltipText(
					ticketImage,
					getString(R.string.tickets_sold_content_description)
				)
				ticketImage.visibility = if (departure.vehicle.let {
						it.getCapability(Vehicle.Capability.TICKET_DRIVER) || it.getCapability(Vehicle.Capability.TICKET_MACHINE)
					}) {
					View.VISIBLE
				} else {
					View.GONE
				}
			}
			findViewById<ImageView>(R.id.usb).let {
				TooltipCompat.setTooltipText(
					it,
					getString(R.string.usb_charging_content_description)
				)
				it.visibility =
					if (departure.vehicle.getCapability(Vehicle.Capability.USB_CHARGING)) {
						View.VISIBLE
					} else {
						View.GONE
					}
			}

			if (departure.alerts.isNotEmpty()) {
				findViewById<MaterialTextView>(R.id.alerts_text).text = departure.alerts.map {
					it.header.ifEmpty {
						getString(R.string.alert_header)
					}
				}.toSet().joinToString(separator = "\n")
				findViewById<LinearLayout>(R.id.alerts).apply {
					visibility = View.VISIBLE
					setOnClickListener {
						MaterialAlertDialogBuilder(context)
							.setTitle(R.string.alerts)
							.setPositiveButton(R.string.ok) { _, _ -> }
							.setMessage(departure.alerts.map { it.description }.filter { it != "" }
								.joinToString(separator = "\n"))
							.show()
					}
				}
			}

			findViewById<MapView>(R.id.map).let { map ->
				if (departure.vehicle.Position.isZero()) {
					map.visibility = View.GONE
					return@let
				}
				map.controller.apply {
					GeoPoint(
						departure.vehicle.location().latitude,
						departure.vehicle.location().longitude
					).let { geoPoint ->
						if (updating) {
							animateTo(
								geoPoint, 19.0f.toDouble(), 3 * 1000
							)
						} else {
							setCenter(geoPoint)
							setZoom(19f.toDouble())
						}
					}
				}

				map.overlays.removeAll { marker ->
					marker is Marker
				}
				val marker = Marker(map).apply {
					position =
						GeoPoint(
							departure.vehicle.location().latitude,
							departure.vehicle.location().longitude
						)
					setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
					icon = context?.let { ctx -> departure.vehicle.icon(ctx, 2f) }
					setOnClickListener {}
				}
				map.overlays.add(marker)
				map.invalidate()
			}
		}
	}

	@SuppressLint("ClickableViewAccessibility")
	override fun onCreateView(
		inflater: LayoutInflater,
		container: ViewGroup?,
		savedInstanceState: Bundle?
	): View {
		val content = inflater.inflate(R.layout.departure_bottom_sheet, container, false)

		context?.let { ctx ->
			content.apply {
				findViewById<MapView>(R.id.map).let { map ->
					map.setTileSource(TileSourceFactory.MAPNIK)
					if (((context?.resources?.configuration?.uiMode ?: UI_MODE_NIGHT_UNDEFINED)
								and UI_MODE_NIGHT_MASK) == UI_MODE_NIGHT_YES
					) {
						map.overlayManager.tilesOverlay.setColorFilter(TilesOverlay.INVERT_COLORS)
					}
					map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)
					map.setOnTouchListener { _, _ -> true }
					map.setMultiTouchControls(true)
					map.overlays.add(RotationGestureOverlay(map).apply { isEnabled = true })
				}

				setContent(this, ctx)

				(dialog as BottomSheetDialog).behavior.peekHeight = dpToPixelI(180f)

			}
		}
		return content
	}
}