package com.prodhack.moscow2025.presentation.screens.createResume

import android.util.Log
import androidx.compose.foundation.layout.Arrangement
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.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
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.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.prodhack.moscow2025.R
import com.prodhack.moscow2025.domain.models.Education
import com.prodhack.moscow2025.domain.models.EducationGrades
import com.prodhack.moscow2025.domain.models.Project
import com.prodhack.moscow2025.domain.models.WorkExperience
import com.prodhack.moscow2025.domain.models.ResumeField
import com.prodhack.moscow2025.presentation.components.standart.BigButton
import com.prodhack.moscow2025.presentation.components.standart.TBubble
import com.prodhack.moscow2025.presentation.components.standart.TTTextField
import com.prodhack.moscow2025.presentation.components.standart.TTTextFieldWithDropdown
import com.prodhack.moscow2025.presentation.components.standart.TTTextFieldWithSearch
import com.prodhack.moscow2025.presentation.theme.Paddings
import com.prodhack.moscow2025.presentation.theme.Shapes
import com.prodhack.moscow2025.presentation.utils.ErrorCollectorScope
import com.prodhack.moscow2025.presentation.utils.toReadableText
import com.prodhack.moscow2025.presentation.utils.ui.noRippleClickable
import org.koin.androidx.compose.koinViewModel


@Composable
fun ErrorCollectorScope.CreateResumeScreen(
	goBack: () -> Unit,
	openResumeDetails: (String) -> Unit,
	viewModel: BaseCreateResumeViewModel = koinViewModel<CreateResumeViewModel>(),
	title: String = "Новое резюме",
	submitButtonText: String = "Узнать свою ЗП"
) {
	val colorScheme = MaterialTheme.colorScheme
	val typography = MaterialTheme.typography

	val formState = viewModel.formStateFillResume.collectAsState()

	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
					.rotate(180f)
					.size(24.dp)
					.noRippleClickable(goBack),
				painter = painterResource(R.drawable.ic_arr_details),
				tint = colorScheme.onBackground,
				contentDescription = "go back"
			)
			Text(text = title, style = typography.titleLarge, fontSize = 24.sp)
			Spacer(modifier = Modifier.size(24.dp))
		}
		Column(
			modifier = Modifier
				.fillMaxSize()
				.verticalScroll(rememberScrollState())
		) {

			Spacer(modifier = Modifier.height(Paddings.large))
			TTTextField(
				value = formState.value.position,
				onValueChange = viewModel::onPositionChange,
				label = "Какая должность вас интересует?",
				error = formState.value.errors[ResumeField.Position]
			)
			Spacer(modifier = Modifier.height(Paddings.medium))

			TTTextField(
				value = formState.value.city,
				onValueChange = viewModel::onCityChange,
				label = "Ваш город",
				error = formState.value.errors[ResumeField.City]
			)
			Spacer(modifier = Modifier.height(Paddings.medium))

			TTTextField(
				value = formState.value.about,
				onValueChange = viewModel::onAboutChange,
				singleLine = false,
				maxLines = Int.MAX_VALUE,
				label = "Расскажите о себе",
				error = formState.value.errors[ResumeField.Position]
			)
			Spacer(modifier = Modifier.height(Paddings.medium))

			TTTextFieldWithDropdown(
				value = formState.value.experience?.toReadableText() ?: "",
				onValueChange = {},
				singleLine = false,
				maxLines = Int.MAX_VALUE,
				label = "Какой у вас опыт в данной сфере?",
				error = formState.value.errors[ResumeField.Experience],
				dropdownItems = viewModel.experienceOptions,
				dropDownItem = {
					Text(
						text = it.toReadableText(),
						style = typography.labelLarge,
						fontSize = 16.sp
					)
				},
				onDropdownItemSelected = viewModel::onExperienceSelect
			)
			Spacer(modifier = Modifier.height(Paddings.medium))

			TTTextFieldWithSearch(
				value = viewModel.skillSearchQuery.value,
				onValueChange = {
					viewModel.skillSearchQuery.value = it
				},
				label = "Ваши навыки",
				error = formState.value.errors[ResumeField.Experience],
				dropdownItems = viewModel.suggestedSkills.collectAsState(emptyList()).value,
				dropDownItem = {
					Text(text = it, style = typography.labelLarge, fontSize = 16.sp)
				},
				onDropdownItemSelected = viewModel::onAddSkill,
				trailingIcon = {
					if (viewModel.skillSearchQuery.value.isNotBlank()) {
						Row(
							verticalAlignment = Alignment.CenterVertically,
							modifier = Modifier.noRippleClickable {
								viewModel.onAddSkill(viewModel.skillSearchQuery.value)
							}
						) {
							Text(
								"Добавить",
								style = typography.labelLarge,
								fontSize = 12.sp,
								color = colorScheme.onPrimary
							)
							Spacer(modifier = Modifier.width(Paddings.verySmall))
							Icon(
								modifier = Modifier.size(12.dp),
								painter = painterResource(R.drawable.ic_plus),
								tint = colorScheme.onPrimary,
								contentDescription = null
							)
							Spacer(modifier = Modifier.width(Paddings.medium))

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

			FlowRow(
				modifier = Modifier.fillMaxWidth(),
				horizontalArrangement = Arrangement.spacedBy(
					Paddings.small
				),
				verticalArrangement = Arrangement.spacedBy(
					Paddings.small
				)
			) {
				formState.value.keySkills.forEach { skillName ->
					TBubble(text = skillName) {
						viewModel.onRemoveSkill(skillName)
					}
				}
			}

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

			SectionCard(title = "Подробнее о вашем опыте работы:") {
				formState.value.workExperience.forEachIndexed { index, workExp ->
					WorkExperienceForm(
						index = index,
						workExp = workExp,
						errors = formState.value.errors,
						onPlaceChange = { viewModel.changeWorkExperiencePlace(index, it) },
						onDescriptionChange = {
							viewModel.changeWorkExperienceDescription(
								index,
								it
							)
						},
						onDurationChange = {
							viewModel.changeWorkExperienceMonthDuration(
								index,
								it
							)
						},
						onRemove = { viewModel.removeExperience(index) }
					)
					Spacer(modifier = Modifier.height(Paddings.medium))
				}

				if (formState.value.workExperience.isEmpty()) {
					EmptyStateText()
					Spacer(modifier = Modifier.height(Paddings.medium))
				}

				AddItemButton(
					text = "Добавить",
					onClick = viewModel::addNewExperience,
					containerColor = colorScheme.onSecondary,
					contentColor = colorScheme.secondary
				)
			}
			Spacer(modifier = Modifier.height(Paddings.large))

			SectionCard(title = "Ваше образование:") {
				formState.value.education.forEachIndexed { index, education ->
					EducationForm(
						index = index,
						education = education,
						errors = formState.value.errors,
						grades = viewModel.educationGradeOptions,
						onPlaceChange = { viewModel.changeEducationPlace(index, it) },
						onGradeChange = { viewModel.changeEducationGrade(index, it) },
						onSpecializationChange = {
							viewModel.changeEducationSpecialization(
								index,
								it
							)
						},
						onDescriptionChange = { viewModel.changeEducationDescription(index, it) },
						onRemove = { viewModel.removeEducation(index) }
					)
					Spacer(modifier = Modifier.height(Paddings.medium))
				}

				if (formState.value.education.isEmpty()) {
					EmptyStateText()
					Spacer(modifier = Modifier.height(Paddings.medium))
				}

				AddItemButton(
					text = "Добавить",
					onClick = viewModel::addNewEducation,
					containerColor = colorScheme.onSecondary,
					contentColor = colorScheme.secondary
				)
			}

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

			SectionCard(title = "Интересные проекты:") {
				formState.value.projects.forEachIndexed { index, project ->
					ProjectForm(
						index = index,
						project = project,
						errors = formState.value.errors,
						onNameChange = { viewModel.changeProjectName(index, it) },
						onDescriptionChange = { viewModel.changeProjectDescription(index, it) },
						onRemove = { viewModel.removeProject(index) }
					)
					Spacer(modifier = Modifier.height(Paddings.medium))
				}

				if (formState.value.projects.isEmpty()) {
					EmptyStateText()
					Spacer(modifier = Modifier.height(Paddings.medium))
				}

				AddItemButton(
					text = "Добавить",
					onClick = viewModel::addNewProject,
					containerColor = colorScheme.onSecondary,
					contentColor = colorScheme.secondary
				)
			}

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

			val resumeFillState = viewModel.resumeFillState.collectAsStateWithCallbacks {
				Log.d("CreateResumeScreen", it)
				openResumeDetails(it)
			}
			BigButton(
				onClick = viewModel::submit,
				buttonText = submitButtonText,
				isLoading = resumeFillState.value.isLoading
			)
			Spacer(modifier = Modifier.height(Paddings.large))
		}
	}
}

@Composable
private fun SectionCard(
	title: String,
	content: @Composable ColumnScope.() -> Unit
) {
	val typography = MaterialTheme.typography
	Card {
		Column(
			modifier = Modifier.padding(Paddings.medium),
			verticalArrangement = Arrangement.spacedBy(Paddings.medium)
		) {
			Text(
				modifier = Modifier.fillMaxWidth(),
				text = title,
				style = typography.titleMedium,
				fontSize = 20.sp,
				textAlign = TextAlign.Center
			)
			content()
		}
	}
}

@Composable
private fun WorkExperienceForm(
	index: Int,
	workExp: WorkExperience,
	errors: Map<ResumeField, String>,
	onPlaceChange: (String) -> Unit,
	onDescriptionChange: (String) -> Unit,
	onDurationChange: (String) -> Unit,
	onRemove: () -> Unit
) {
	val typography = MaterialTheme.typography
	Text(text = "№${index + 1}:", style = typography.labelLarge, fontSize = 18.sp)
	TTTextField(
		value = workExp.place,
		onValueChange = onPlaceChange,
		label = "Место работы",
		error = errors[ResumeField.WorkExperiencePlace(index)]
	)
	TTTextField(
		value = workExp.description,
		onValueChange = onDescriptionChange,
		singleLine = false,
		maxLines = 10,
		label = "Расскажите подробнее",
		error = errors[ResumeField.WorkExperienceDescription(index)]
	)
	TTTextField(
		value = workExp.monthDuration?.toString() ?: "",
		onValueChange = onDurationChange,
		label = "Продолжительность (в месяцах)",
		error = errors[ResumeField.WorkExperienceMonthDuration(index)]
	)
	DeleteItemButton(onClick = onRemove)
}

@Composable
private fun EducationForm(
	index: Int,
	education: Education,
	errors: Map<ResumeField, String>,
	grades: List<EducationGrades>,
	onPlaceChange: (String) -> Unit,
	onGradeChange: (EducationGrades) -> Unit,
	onSpecializationChange: (String) -> Unit,
	onDescriptionChange: (String) -> Unit,
	onRemove: () -> Unit
) {
	val typography = MaterialTheme.typography
	Text(text = "№${index + 1}:", style = typography.labelLarge, fontSize = 18.sp)
	TTTextField(
		value = education.place,
		onValueChange = onPlaceChange,
		label = "Учебное заведение",
		error = errors[ResumeField.EducationPlace(index)]
	)
	TTTextFieldWithDropdown(
		value = education.grade.toReadableText(),
		onValueChange = {},
		singleLine = false,
		maxLines = Int.MAX_VALUE,
		label = "Уровень образования",
		error = errors[ResumeField.EducationGrade(index)],
		dropdownItems = grades,
		dropDownItem = {
			Text(
				text = it.toReadableText(),
				style = typography.labelLarge,
				fontSize = 16.sp
			)
		},
		onDropdownItemSelected = onGradeChange
	)
	TTTextField(
		value = education.specialization,
		onValueChange = onSpecializationChange,
		label = "Специализация",
		error = errors[ResumeField.EducationSpecialization(index)]
	)
	TTTextField(
		value = education.description,
		onValueChange = onDescriptionChange,
		singleLine = false,
		maxLines = 10,
		label = "Расскажите подробнее (опционально)",
		error = errors[ResumeField.EducationDescription(index)]
	)
	DeleteItemButton(onClick = onRemove)
}

@Composable
private fun ProjectForm(
	index: Int,
	project: Project,
	errors: Map<ResumeField, String>,
	onNameChange: (String) -> Unit,
	onDescriptionChange: (String) -> Unit,
	onRemove: () -> Unit
) {
	val typography = MaterialTheme.typography
	Text(text = "№${index + 1}:", style = typography.labelLarge, fontSize = 18.sp)
	TTTextField(
		value = project.name,
		onValueChange = onNameChange,
		label = "Название проекта",
		error = errors[ResumeField.ProjectName(index)]
	)
	TTTextField(
		value = project.description,
		onValueChange = onDescriptionChange,
		singleLine = false,
		maxLines = 10,
		label = "Расскажите подробнее",
		error = errors[ResumeField.ProjectDescription(index)]
	)
	DeleteItemButton(onClick = onRemove)
}

@Composable
private fun AddItemButton(
	text: String,
	onClick: () -> Unit,
	containerColor: androidx.compose.ui.graphics.Color,
	contentColor: androidx.compose.ui.graphics.Color
) {
	Button(
		modifier = Modifier.fillMaxWidth(),
		shape = Shapes.smallRoundedBox,
		onClick = onClick,
		colors = ButtonColors(
			containerColor = containerColor,
			contentColor = contentColor,
			disabledContainerColor = containerColor,
			disabledContentColor = contentColor
		)
	) {
		Text(
			text = text,
			style = MaterialTheme.typography.labelLarge,
			fontSize = 18.sp,
		)
	}
}

@Composable
private fun DeleteItemButton(onClick: () -> Unit) {
	Button(
		modifier = Modifier.fillMaxWidth(),
		shape = Shapes.smallRoundedBox,
		onClick = onClick,
		colors = ButtonColors(
			containerColor = MaterialTheme.colorScheme.errorContainer,
			contentColor = MaterialTheme.colorScheme.onErrorContainer,
			disabledContainerColor = MaterialTheme.colorScheme.errorContainer,
			disabledContentColor = MaterialTheme.colorScheme.onErrorContainer
		)
	) {
		Text(
			text = "Удалить",
			style = MaterialTheme.typography.labelLarge,
			fontSize = 18.sp,
		)
	}
}

@Composable
private fun EmptyStateText() {
	Text(
		modifier = Modifier.fillMaxWidth(),
		text = "Пока ничего нет",
		style = MaterialTheme.typography.labelLarge,
		fontSize = 18.sp,
		textAlign = TextAlign.Center
	)
}
