package com.prodhack.moscow2025.presentation.screens.resumeDetails

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardColors
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavBackStackEntry
import android.os.Bundle
import com.prodhack.moscow2025.R
import com.prodhack.moscow2025.domain.models.Education
import com.prodhack.moscow2025.domain.models.Project
import com.prodhack.moscow2025.domain.models.ResumeModel
import com.prodhack.moscow2025.domain.models.WorkExperience
import com.prodhack.moscow2025.presentation.components.standart.TBubble
import com.prodhack.moscow2025.presentation.navigation.AppDestination
import com.prodhack.moscow2025.presentation.theme.Paddings
import com.prodhack.moscow2025.presentation.utils.ErrorCollectorScope
import com.prodhack.moscow2025.presentation.utils.toReadableText
import com.prodhack.moscow2025.presentation.utils.toSalaryRangeString
import com.prodhack.moscow2025.presentation.utils.ui.noRippleClickable
import com.prodhack.moscow2025.presentation.utils.ui.placeholders.ErrorPlaceholder
import com.prodhack.moscow2025.presentation.utils.ui.placeholders.LoadingPlaceholder
import com.prodhack.moscow2025.presentation.navigation.navigate
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf

@Composable
fun ErrorCollectorScope.ResumeDetailsScreen(
	navBackStackEntry: NavBackStackEntry,
	viewModel: ResumeDetailsViewModel = koinViewModel {
		parametersOf(
			navBackStackEntry.arguments?.getString(AppDestination.ResumeDetails.ARG_ID, "") ?: ""
		)
	}
) {
	viewModel.resumeState.FoldUIStateWithGlobalCallbacks(
		onLoading = {
			LoadingPlaceholder(
				modifier = Modifier
					.fillMaxWidth()
					.padding(Paddings.large)
			)
		},
		onError = {
			ErrorPlaceholder(
				modifier = Modifier
					.fillMaxWidth()
					.padding(Paddings.large)
			) {
				navController.popBackStack()
			}
		}
	) { resume ->
		Box {
			ResumeDetailsContent(
				resume = resume,
				onBack = { navController.navigate(AppDestination.Main.route) },
				onHistory = {
					navController.navigate(
						AppDestination.ResumeHistory.route,
						Bundle().apply {
							putString(AppDestination.ResumeHistory.ARG_ID, resume.id)
						}
					)
				}
			)
			ExtendedFloatingActionButton(
				modifier = Modifier
					.align(Alignment.BottomCenter)
					.padding(bottom = Paddings.large),
				onClick = {
					navController.navigate(
						AppDestination.ResumeEdit.route,
						Bundle().apply {
							putString(AppDestination.ResumeEdit.ARG_ID, resume.id)
						}
					)
				},
				icon = {
					Icon(
						painter = painterResource(R.drawable.ic_pen),
						"Extended floating action button."
					)
				},
				text = { Text(text = "Редактировать резюме") },
			)
		}
	}
}

@Composable
private fun ResumeDetailsContent(
	resume: ResumeModel,
	onBack: () -> Unit,
	onHistory: () -> Unit
) {
	val typography = MaterialTheme.typography
	val colorScheme = MaterialTheme.colorScheme
	val scrollState = rememberScrollState()

	Column(
		modifier = Modifier
			.fillMaxSize()
			.padding(horizontal = Paddings.large)
	) {
		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
			)
			Icon(
				modifier = Modifier
					.size(24.dp)
					.noRippleClickable(onHistory),
				painter = painterResource(R.drawable.ic_history),
				tint = colorScheme.onBackground,
				contentDescription = "open history"
			)
		}

		Column(
			modifier = Modifier
				.fillMaxSize()
				.verticalScroll(scrollState)
		) {
			Spacer(modifier = Modifier.height(Paddings.large))
			SectionContainer {
				Text(
					resume.position,
					style = typography.titleLarge,
					fontSize = 28.sp
				)

				if (resume.prediction == null) {
					CircularProgressIndicator(modifier = Modifier.size(18.dp))
				} else {
					Text(
						resume.prediction.toSalaryRangeString(),
						style = typography.titleMedium,
						fontSize = 18.sp
					)
				}

				Text(
					text = resume.city,
					style = typography.labelLarge,
					color = colorScheme.primary
				)
				Text(
					text = "Опыт: ${resume.experienceType.toReadableText()}",
					style = typography.labelMedium
				)
			}


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

			SectionContainer(title = "О себе") {
				Text(
					text = resume.about.ifBlank { "Описание отсутствует" },
					style = typography.bodyLarge,
					fontSize = 16.sp
				)
			}

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

			SectionContainer(title = "Ключевые навыки") {
				if (resume.skills.isEmpty()) {
					Text("Навыки не указаны", style = typography.bodyMedium)
				} else {
					FlowRow(
						horizontalArrangement = Arrangement.spacedBy(Paddings.small),
						verticalArrangement = Arrangement.spacedBy(Paddings.small)
					) {
						resume.skills.forEach { skill ->
							TBubble(text = skill)
						}
					}

					resume.recommendedSkills
						?.filter { it.isNotBlank() }
						?.takeIf { it.isNotEmpty() }
						?.let { skills ->
							SectionContainer(
								title = "Рекомендуем изучить",
								colors = CardDefaults.cardColors(
									containerColor = colorScheme.primaryContainer,
									contentColor = colorScheme.onPrimaryContainer
								)
							) {
								FlowRow(
									horizontalArrangement = Arrangement.spacedBy(Paddings.small),
									verticalArrangement = Arrangement.spacedBy(Paddings.small)
								) {
									skills.forEach {
										TBubble(text = it)
									}
								}
							}
						}
				}
			}

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

			SectionContainer(title = "Опыт работы") {
				if (resume.experience.isEmpty()) {
					Text("Опыт не указан", style = typography.bodyMedium)
				} else {
					resume.experience.forEachIndexed { index, work ->
						WorkExperienceCard(index = index, workExperience = work)
						if (index != resume.experience.lastIndex) {
							Spacer(modifier = Modifier.height(Paddings.small))
						}
					}
				}
			}

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

			SectionContainer(title = "Образование") {
				if (resume.education.isEmpty()) {
					Text("Не указано", style = typography.bodyMedium)
				} else {
					resume.education.forEachIndexed { index, education ->
						EducationCard(index = index, education = education)
						if (index != resume.education.lastIndex) {
							Spacer(modifier = Modifier.height(Paddings.small))
						}
					}
				}
			}

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

			SectionContainer(title = "Проекты") {
				if (resume.projects.isEmpty()) {
					Text("Проекты не указаны", style = typography.bodyMedium)
				} else {
					resume.projects.forEachIndexed { index, project ->
						ProjectCard(index = index, project = project)
						if (index != resume.projects.lastIndex) {
							Spacer(modifier = Modifier.height(Paddings.small))
						}
					}
				}
			}

			Spacer(modifier = Modifier.height(Paddings.large * 4.5f))
		}
	}
}

@Composable
private fun SectionContainer(
	modifier: Modifier = Modifier,
	title: String = "",
	colors: CardColors = CardDefaults.cardColors(),
	content: @Composable ColumnScope.() -> Unit
) {
	val typography = MaterialTheme.typography
	Card(
		modifier = modifier.fillMaxWidth(),
		colors = colors,
		shape = MaterialTheme.shapes.medium
	) {
		Column(
			modifier = Modifier
				.fillMaxWidth()
				.padding(Paddings.medium),
			verticalArrangement = Arrangement.spacedBy(Paddings.small)
		) {
			if (title.isNotBlank()) {
				Text(
					text = title,
					style = typography.titleMedium,
					fontWeight = FontWeight.Bold,
					fontSize = 18.sp
				)
			}
			content()
		}
	}
}

@Composable
private fun WorkExperienceCard(index: Int, workExperience: WorkExperience) {
	val typography = MaterialTheme.typography
	val colorScheme = MaterialTheme.colorScheme
	Column(
		verticalArrangement = Arrangement.spacedBy(Paddings.small)
	) {
		Text(
			text = "Место №${index + 1}",
			style = typography.labelLarge,
			color = colorScheme.primary
		)
		Text(workExperience.place, style = typography.titleMedium)
		Text(
			text = workExperience.description,
			style = typography.bodyMedium
		)
		Text(
			text = "Длительность: ${workExperience.monthDuration.toMonthText()}",
			style = typography.bodyMedium
		)
	}
}

@Composable
private fun EducationCard(index: Int, education: Education) {
	val typography = MaterialTheme.typography
	val colorScheme = MaterialTheme.colorScheme
	Column(
		verticalArrangement = Arrangement.spacedBy(Paddings.small)
	) {
		Text(
			text = "Учебное место №${index + 1}",
			style = typography.labelLarge,
			color = colorScheme.primary
		)
		Text(education.place, style = typography.titleMedium)
		Text(
			text = "Ступень: ${education.grade.toReadableText()}",
			style = typography.bodyMedium
		)
		Text(
			text = "Специализация: ${education.specialization}",
			style = typography.bodyMedium
		)
		Text(
			text = education.description,
			style = typography.bodyMedium
		)
	}
}

@Composable
private fun ProjectCard(index: Int, project: Project) {
	val typography = MaterialTheme.typography
	val colorScheme = MaterialTheme.colorScheme
	Column(
		verticalArrangement = Arrangement.spacedBy(Paddings.small)
	) {
		Text(
			text = "Проект №${index + 1}",
			style = typography.labelLarge,
			color = colorScheme.primary
		)
		Text(project.name, style = typography.titleMedium)
		Text(project.description, style = typography.bodyMedium)
	}
}

private fun Int?.toMonthText(): String = when {
	this == null -> "Не указано"
	this < 12 -> "$this мес."
	else -> {
		val years = this / 12
		val months = this % 12
		if (months == 0) "$years г." else "$years г. $months мес."
	}
}
