package com.prodhack.moscow2025.presentation.screens.profile

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.prodhack.moscow2025.R
import com.prodhack.moscow2025.domain.models.AuthField
import com.prodhack.moscow2025.presentation.components.standart.BigButton
import com.prodhack.moscow2025.presentation.components.standart.TPhoneCountryList
import com.prodhack.moscow2025.presentation.components.standart.TPhoneField
import com.prodhack.moscow2025.presentation.components.standart.TTTextField
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.UIState
import com.prodhack.moscow2025.presentation.utils.ui.SnackbarStyle
import com.prodhack.moscow2025.presentation.utils.ui.showSnackbar
import org.koin.androidx.compose.koinViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ErrorCollectorScope.ProfileScreen(
	modifier: Modifier = Modifier,
	snackbarHostState: SnackbarHostState,
	navigateToLoginScreen: () -> Unit,
	viewModel: ProfileScreenViewModel = koinViewModel()
) {
	val typography = androidx.compose.material3.MaterialTheme.typography
	val sheetState = rememberModalBottomSheetState()
	val isSheetOpen = remember { mutableStateOf(false) }

	val formState by viewModel.formStateFillProfile.collectAsState()

	var errorText by remember { mutableStateOf("") }
	val profileState by viewModel.profileState.collectAsStateWithCallbacks(
		onInputError = {
			errorText = it.error
		},
		onConnectionError = {
			errorText = "Нет подключения к сети"
		},
		onUnexpectedError = {
			errorText = it.error
		},
		onLoading = {
			errorText = ""
		},
		onSuccess = {
			errorText = ""
		}
	)

	LaunchedEffect(profileState) {
		if (profileState is UIState.Success) {
			snackbarHostState.showSnackbar(
				message = "Данные профиля обновлены",
				style = SnackbarStyle.Success,
				duration = SnackbarDuration.Short
			)
		}
	}

	LaunchedEffect(errorText) {
		if (errorText.isNotEmpty()) {
			snackbarHostState.showSnackbar(
				message = "Ошибка: $errorText",
				duration = SnackbarDuration.Short
			)
		}
	}

	Column(
		modifier = Modifier
			.fillMaxSize()
			.imePadding()
			.systemBarsPadding()
			.padding(horizontal = Paddings.large),
		horizontalAlignment = Alignment.CenterHorizontally,
		verticalArrangement = Arrangement.Top
	) {
		Spacer(Modifier.height(Paddings.large))
		Text(
			text = "Профиль",
			style = typography.titleLarge,
			fontSize = 40.sp
		)
		Spacer(Modifier.height(Paddings.large))
		TTTextField(
			value = formState.firstName,
			onValueChange = viewModel::onFirstNameChange,
			label = "Имя",
			error = formState.errors[AuthField.FirstName],
		)
		Spacer(Modifier.height(Paddings.medium))
		TTTextField(
			value = formState.lastName,
			onValueChange = viewModel::onLastNameChange,
			label = "Фамилия",
			error = formState.errors[AuthField.LastName],
		)
		Spacer(Modifier.height(Paddings.medium))
		TTTextField(
			value = formState.email,
			onValueChange = viewModel::onEmailChange,
			label = "Email",
			error = formState.errors[AuthField.Email],
			keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)
		)
		Spacer(Modifier.height(Paddings.medium))

		TPhoneField(
			currentPattern = viewModel.chosenPattern.value,
			currentPhone = formState.phone,
			onPhoneChange = viewModel::onPhoneChange,
			error = formState.errors[AuthField.Phone],
			onOpenCountryList = {
				isSheetOpen.value = true
			}
		)

		Spacer(modifier = Modifier.height(Paddings.large))
		if (viewModel.madeChanges.collectAsState().value) {
			BigButton(
				onClick = viewModel::submit,
				modifier = Modifier.fillMaxWidth(),
				buttonText = "Сохранить",
				isLoading = profileState is UIState.Loading
			)
			Spacer(Modifier.height(Paddings.medium))
			Button(
				modifier = modifier
					.fillMaxWidth()
					.height(60.dp),
				shape = Shapes.smallRoundedBox,
				onClick = viewModel::reset,
				colors = ButtonColors(
					containerColor = colorScheme.secondaryContainer,
					contentColor = colorScheme.onSecondaryContainer,
					disabledContainerColor = colorScheme.secondaryContainer,
					disabledContentColor = colorScheme.onSecondaryContainer
				)
			) {
				Text(
					text = "Отменить",
					style = typography.titleMedium,
					fontSize = 24.sp
				)
			}
			Spacer(Modifier.height(Paddings.medium))
		}
		Button(
			modifier = modifier
				.fillMaxWidth()
				.height(60.dp),
			shape = Shapes.smallRoundedBox,
			onClick = {
				viewModel.logout()
				navigateToLoginScreen()
			},
			colors = ButtonColors(
				containerColor = colorScheme.errorContainer,
				contentColor = colorScheme.onErrorContainer,
				disabledContainerColor = colorScheme.errorContainer,
				disabledContentColor = colorScheme.onErrorContainer
			)
		) {

			Row(verticalAlignment = Alignment.CenterVertically) {
				Text(
					text = "Выйти из аккаунта",
					style = typography.titleMedium,
					fontSize = 24.sp
				)
				Spacer(Modifier.width(Paddings.small))
				Icon(
					painter = painterResource(R.drawable.logout_icon),
					contentDescription = null,
					modifier = Modifier.size(24.dp)
				)
			}
		}
		Spacer(modifier = Modifier.height(Paddings.large))
	}

	TPhoneCountryList(
		isSheetOpen = isSheetOpen,
		sheetState = sheetState,
		patternList = viewModel.phoneNumberPatterns,
		setPattern = {
			viewModel.chosenPattern.value = it
		}
	)
}
