package com.prodhack.moscow2025.presentation.screens.register

import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
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.TTPasswordField
import com.prodhack.moscow2025.presentation.components.standart.TTTextField
import com.prodhack.moscow2025.presentation.utils.ErrorCollectorScope
import com.prodhack.moscow2025.presentation.utils.UIState
import org.koin.androidx.compose.koinViewModel

@Composable
fun ErrorCollectorScope.RegisterScreen(
	modifier: Modifier = Modifier,
	snackbarHostState: SnackbarHostState,
	onLoginClick: () -> Unit,
	onSuccess: () -> Unit,
	viewModel: RegisterViewModel = koinViewModel()
) {
	val typography = MaterialTheme.typography
	val colorScheme = MaterialTheme.colorScheme

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

	if (isGeneratorDialogVisible) {
		AlertDialog(
			onDismissRequest = { isGeneratorDialogVisible = false },
			title = { Text("Генерация данных") },
			text = { Text("Случайный email и пароль будут подставлены в поля.") },
			confirmButton = {
				TextButton(
					onClick = {
						viewModel.fillRandomCredentials()
						isGeneratorDialogVisible = false
					}
				) {
					Text("Сгенерировать данные")
				}
			},
			dismissButton = {
				TextButton(onClick = { isGeneratorDialogVisible = false }) {
					Text("Отмена")
				}
			}
		)
	}

	LaunchedEffect(registerState) {
		if (registerState is UIState.Success) {
			onSuccess()
		}
	}

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

	Box(
		modifier = modifier
			.fillMaxSize()
			.imePadding()
			.systemBarsPadding(),
		contentAlignment = Alignment.BottomStart
	) {
		Image(
			painter = painterResource(R.drawable.lottie),
			contentDescription = null,
			modifier = Modifier.width(130.dp),
			contentScale = ContentScale.Crop
		)

		Column(
			modifier = Modifier
				.fillMaxSize()
				.padding(start = 30.dp, end = 30.dp)
				.verticalScroll(rememberScrollState()),
			horizontalAlignment = Alignment.CenterHorizontally
		) {
            Icon(
                painter = painterResource(R.drawable.app_logo),
                contentDescription = null,
                modifier = Modifier
                    .size(200.dp)
                    .clickable { isGeneratorDialogVisible = true }
            )
            Text(
                text = "Регистрация",
                style = MaterialTheme.typography.titleLarge,
                fontSize = 40.sp
            )
            Spacer(modifier = Modifier.height(10.dp))
			TTTextField(
				value = formState.email,
				onValueChange = viewModel::onEmailChange,
				label = "Ваш email",
				error = formState.errors[AuthField.Email],
			)
			Spacer(Modifier.height(12.dp))
			TTPasswordField(
				value = formState.password,
				onValueChange = viewModel::onPasswordChange,
				label = "Пароль",
				error = formState.errors[AuthField.Password]
			)
			Spacer(Modifier.height(12.dp))
			TTPasswordField(
				value = formState.confirmPassword,
				onValueChange = viewModel::onConfirmPasswordChange,
				label = "Повторите пароль",
				error = formState.errors[AuthField.ConfirmPassword],
				keyboardOptions = KeyboardOptions(
					keyboardType = KeyboardType.Text,
					imeAction = ImeAction.Done
				),
				onDone = viewModel::submit
			)
			Spacer(modifier = Modifier.height(20.dp))
			BigButton(
				onClick = viewModel::submit,
				modifier = Modifier.fillMaxWidth(),
				buttonText = "Зарегистрироваться",
				isLoading = registerState is UIState.Loading
			)
			Spacer(modifier = Modifier.height(20.dp))
			TextButton(
				onClick = onLoginClick,
				modifier = Modifier.fillMaxWidth()
			) {
				Text(
					text = "Уже есть аккаунт?",
					style = typography.labelMedium,
					color = colorScheme.onBackground,
					fontSize = 24.sp
				)
			}
			Spacer(Modifier.height(80.dp))
		}
	}
}
