package com.prodhack.moscow2025.presentation.screens.resumeHistory

import android.os.Bundle
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Card
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavBackStackEntry
import androidx.paging.compose.collectAsLazyPagingItems
import com.google.gson.Gson
import com.prodhack.moscow2025.R
import com.prodhack.moscow2025.domain.models.ResumeModel
import com.prodhack.moscow2025.domain.usecase.resumes.CalculateResumeDiffUseCase
import com.prodhack.moscow2025.presentation.components.standart.TBubble
import com.prodhack.moscow2025.presentation.navigation.AppDestination
import com.prodhack.moscow2025.presentation.navigation.navigate
import com.prodhack.moscow2025.presentation.theme.Paddings
import com.prodhack.moscow2025.presentation.utils.ErrorCollectorScope
import com.prodhack.moscow2025.presentation.utils.toSalaryRangeString
import com.prodhack.moscow2025.presentation.utils.ui.noRippleClickable
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf

@Composable
fun ErrorCollectorScope.ResumeHistoryScreen(
	navBackStackEntry: NavBackStackEntry,
	calculateResumeDiffUseCase: CalculateResumeDiffUseCase = CalculateResumeDiffUseCase(),
	viewModel: ResumeHistoryViewModel = koinViewModel {
		parametersOf(
			navBackStackEntry.arguments?.getString(AppDestination.ResumeHistory.ARG_ID, "") ?: ""
		)
	},
	onBack: () -> Unit
) {
	val items = viewModel.history.collectAsLazyPagingItems()

	val typography = MaterialTheme.typography
	val colorScheme = MaterialTheme.colorScheme
	val expandedState = remember { mutableStateMapOf<Int, Boolean>() }
	val selected = remember { mutableStateMapOf<String, ResumeModel>() }
	val selectedIndices = remember { mutableStateMapOf<String, Int>() }

	Box(
		modifier = Modifier.fillMaxSize()
	) {
		Column(
			modifier = Modifier
				.fillMaxSize()
				.padding(horizontal = Paddings.large),
			horizontalAlignment = Alignment.CenterHorizontally
		) {
			Spacer(modifier = Modifier.height(Paddings.large))
			Row(
				modifier = Modifier.fillMaxWidth(),
				horizontalArrangement = Arrangement.SpaceBetween,
				verticalAlignment = Alignment.CenterVertically
			) {
				Icon(
					modifier = Modifier
						.size(24.dp)
						.rotate(180f)
						.noRippleClickable(onBack),
					painter = painterResource(R.drawable.ic_arr_details),
					tint = colorScheme.onBackground,
					contentDescription = "go back"
				)
				Text(
					text = "История резюме",
					style = typography.titleLarge,
					fontSize = 22.sp
				)
				Spacer(modifier = Modifier.size(24.dp))
			}

			Spacer(modifier = Modifier.height(Paddings.large))

			viewModel.resumePosition.FoldUIStateWithGlobalCallbacks {
				Text(
					text = it,
					style = typography.titleLarge,
					fontSize = 20.sp
				)
			}

			Spacer(modifier = Modifier.height(Paddings.large))

			LazyColumn(
				verticalArrangement = Arrangement.spacedBy(Paddings.medium)
			) {
				items(items.itemCount) { index ->
					val version = items[index] ?: return@items
					val previous = if ((index + 1) < items.itemCount) items[index + 1] else null
					val expanded = expandedState[index] ?: false
					val isSelected = selected.contains(version.id)
					val canSelectMore = isSelected || selected.size < 2

					HistoryCard(
						current = version,
						previous = previous,
						expanded = expanded,
						onToggle = { expandedState[index] = !expanded },
						calculateResumeDiffUseCase = calculateResumeDiffUseCase,
						isSelected = isSelected,
						enabled = canSelectMore,
						onSelectToggle = {
							if (isSelected) {
								selected.remove(version.id)
								selectedIndices.remove(version.id)
							} else if (selected.size < 2) {
								selected[version.id] = version
								selectedIndices[version.id] = index
							}
						}
					)
				}
				item { Spacer(modifier = Modifier.height(Paddings.large * 3)) }
			}
		}

		if (selected.size > 0) {
			ExtendedFloatingActionButton(
				modifier = Modifier
					.align(Alignment.BottomCenter)
					.padding(bottom = Paddings.large),
				onClick = {
					if (selected.size == 2) {
						val ordered = selected.toList()
							.sortedByDescending { (id, _) -> selectedIndices[id] ?: Int.MIN_VALUE }
						val first = ordered.getOrNull(0)?.second
						val second = ordered.getOrNull(1)?.second
						val gson = Gson()
						navController.navigate(
							AppDestination.ResumeDiff.route,
							Bundle().apply {
								putString(AppDestination.ResumeDiff.ARG_FIRST, gson.toJson(first))
								putString(AppDestination.ResumeDiff.ARG_SECOND, gson.toJson(second))
							}
						)
					}
				},
				icon = {
					Icon(
						painter = painterResource(R.drawable.ic_checkmark),
						contentDescription = "compare"
					)
				},
				text = {
					Text(
						text = if (selected.size == 2) "Сравнить" else "Выберите ещё 1",
						style = typography.titleMedium
					)
				},
			)
		}
	}
}


@Composable
private fun HistoryCard(
	current: ResumeModel,
	previous: ResumeModel?,
	expanded: Boolean,
	onToggle: () -> Unit,
	calculateResumeDiffUseCase: CalculateResumeDiffUseCase,
	isSelected: Boolean,
	enabled: Boolean,
	onSelectToggle: () -> Unit
) {
	val typography = MaterialTheme.typography
	val colorScheme = MaterialTheme.colorScheme
	val changes = calculateResumeDiffUseCase(previous, current)
	val salaryDiff = calculateSalaryDiff(previous?.prediction, current.prediction)

	Card(
		onClick = onToggle,
		shape = MaterialTheme.shapes.medium,
		enabled = enabled || isSelected
	) {
		Row(
			modifier = Modifier
				.fillMaxWidth()
				.padding(Paddings.medium),
			horizontalArrangement = Arrangement.spacedBy(Paddings.medium),
			verticalAlignment = Alignment.Top
		) {
			Column(
				modifier = Modifier.weight(1f),
				verticalArrangement = Arrangement.spacedBy(Paddings.small)
			) {
				Row(verticalAlignment = Alignment.CenterVertically) {
					if (previous != null) {
						Text(
							salaryDiff,
							style = typography.titleMedium,
							color = colorScheme.primary,
							fontSize = 20.sp
						)
						Spacer(modifier = Modifier.width(Paddings.small))
					}
					Text(
						current.prediction.toSalaryRangeString(),
						style = typography.labelLarge,
						fontSize = 18.sp
					)
				}
				if (previous != null) {
					Text(
						"Изменено:",
						style = typography.titleMedium,
						fontSize = 16.sp
					)
					FlowRow(
						modifier = Modifier.fillMaxWidth(),
						horizontalArrangement = Arrangement.spacedBy(
							Paddings.small
						),
						verticalArrangement = Arrangement.spacedBy(
							Paddings.small
						)
					) {
						changes.changedFields.forEach { skillName ->
							TBubble(text = skillName)
						}
					}
					Spacer(modifier = Modifier.height(Paddings.small))
					if (expanded.not()) {
						Text(
							"Подробнее",
							style = typography.labelLarge,
							textDecoration = TextDecoration.Underline,
							fontSize = 14.sp
						)
					}
					AnimatedVisibility(visible = expanded) {
						Column(verticalArrangement = Arrangement.spacedBy(Paddings.small)) {
							changes.changes.forEach { change ->
								Column {
									Text(change.title, style = typography.titleMedium)
									Text(change.body, style = typography.labelLarge)
								}
							}
						}
					}
				} else {
					Text(
						"Первая версия",
						style = typography.titleMedium,
						color = colorScheme.primary,
						fontSize = 20.sp
					)
				}
			}

			Checkbox(
				checked = isSelected,
				onCheckedChange = {
					if (enabled || isSelected) onSelectToggle()
				},
				enabled = enabled || isSelected
			)
		}
	}
}

private fun calculateSalaryDiff(
	prev: Pair<Float?, Float?>?,
	current: Pair<Float?, Float?>?
): String {
	val prevAvg = prev?.let { listOfNotNull(it.first, it.second).averageOrNull() }
	val currAvg = current?.let { listOfNotNull(it.first, it.second).averageOrNull() }
	return if (prevAvg != null && currAvg != null) {
		val diff = currAvg - prevAvg
		val sign = if (diff >= 0) "+" else "-"
		"${sign}${(kotlin.math.abs(diff).toInt() / 1000) * 1000}₽"
	} else {
		"н/д"
	}
}

private fun List<Float>.averageOrNull(): Double? = if (isEmpty()) null else average()
