package com.prodhack.moscow2025.presentation.screens.main

import android.Manifest
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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 androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.google.firebase.messaging.FirebaseMessaging
import com.prodhack.moscow2025.R
import com.prodhack.moscow2025.presentation.components.standart.BigButton
import com.prodhack.moscow2025.presentation.components.standart.TopLogo
import com.prodhack.moscow2025.presentation.dataModels.UIResumeBaseInfo
import com.prodhack.moscow2025.presentation.theme.Paddings
import com.prodhack.moscow2025.presentation.utils.ErrorCollectorScope
import org.koin.androidx.compose.koinViewModel


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ErrorCollectorScope.MainScreen(
	modifier: Modifier = Modifier,
	openResumeDetails: (String) -> Unit,
	openCreateResume: () -> Unit,
	requestNotifyPermissions: () -> Unit,
	viewModel: MainScreenViewModel = koinViewModel()
) {
	LaunchedEffect(Unit) {
		requestNotifyPermissions()
	}

	Box(modifier = modifier) {
		val items = viewModel.resumeList.collectAsLazyPagingItems()

		MainScreenContent(
			items = items,
			openCreateResume = openCreateResume,
			openResumeDetails = openResumeDetails
		)

		ExtendedFloatingActionButton(
			modifier = Modifier
				.align(Alignment.BottomCenter)
				.padding(bottom = Paddings.large),
			onClick = {
				openCreateResume()
			},
			icon = {
				Icon(
					painter = painterResource(R.drawable.ic_plus),
					"Extended floating action button."
				)
			},
			text = { Text(text = "Добавить резюме") },
		)
	}
}

@Composable
private fun MainScreenContent(
	modifier: Modifier = Modifier,
	items: LazyPagingItems<UIResumeBaseInfo>,
	openCreateResume: () -> Unit,
	openResumeDetails: (String) -> Unit
) {
	val typography = MaterialTheme.typography
	val colorScheme = MaterialTheme.colorScheme
	val shapes = MaterialTheme.shapes
	Column(
		modifier = modifier
			.fillMaxSize()
			.padding(horizontal = Paddings.large),
		horizontalAlignment = Alignment.CenterHorizontally
	) {
		TopLogo()
		Spacer(modifier = Modifier.height(Paddings.medium))
		Text(
			text = "Ваши резюме",
			style = typography.titleLarge,
			fontSize = 32.sp,
			color = colorScheme.onBackground
		)

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

		PullToRefreshBox(items.loadState.refresh is LoadState.Loading, onRefresh = {
			items.refresh()
		}) {
			if (items.itemCount == 0 && items.loadState.append.endOfPaginationReached) {
				Text(
					text = "Здесь пока ничего нет",
					style = typography.labelLarge,
					textAlign = TextAlign.Center,
					fontSize = 24.sp,
					color = colorScheme.onBackground
				)

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

				BigButton(
					onClick = openCreateResume,
					buttonText = "Создать резюме",
					isLoading = false
				)
			} else if (items.loadState.hasError) {
				Text(
					modifier = Modifier
						.fillMaxWidth()
						.background(colorScheme.error, shape = shapes.small)
						.padding(Paddings.medium),
					text = "Кажется что-то пошло не так, но мы уже чиним 🛠️",
					style = typography.labelLarge,
					textAlign = TextAlign.Center,
					fontSize = 24.sp,
					color = colorScheme.onError
				)

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

				BigButton(
					onClick = { items.retry() },
					buttonText = "Попробовать снова",
					isLoading = false
				)
			} else {
				LazyColumn(
					horizontalAlignment = Alignment.CenterHorizontally,
					verticalArrangement = Arrangement.spacedBy(
						Paddings.medium
					)
				) {
					items(items.itemCount) {
						items[it]?.let { resume ->
							ResumeShortInfoCard(info = resume) {
								openResumeDetails(resume.id)
							}
						}
					}

					item {
						if (items.loadState.append.endOfPaginationReached.not()) {
							CircularProgressIndicator()
						}
					}

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

@Composable
fun ResumeShortInfoCard(
	modifier: Modifier = Modifier,
	info: UIResumeBaseInfo,
	onClick: () -> Unit
) {
	val typography = MaterialTheme.typography
	Card(
		modifier = modifier.fillMaxWidth(),
		shape = MaterialTheme.shapes.small,
		onClick = onClick
	) {
		Row(
			modifier = Modifier
				.fillMaxWidth()
				.padding(Paddings.medium),
			verticalAlignment = Alignment.CenterVertically,
			horizontalArrangement = Arrangement.SpaceBetween
		) {
			Column(
				verticalArrangement = Arrangement.spacedBy(Paddings.small)
			) {
				Text(info.positionName, style = typography.labelLarge, fontSize = 20.sp)
				Row {
					Text(
						"Ожидаемая ЗП: ",
						style = typography.labelLarge,
						fontSize = 18.sp
					)
					if (info.isPredictionLoading) {
						CircularProgressIndicator(modifier = Modifier.size(18.dp))
					} else {
						Text(
							info.salary,
							style = typography.titleMedium,
							color = MaterialTheme.colorScheme.primary,
							fontSize = 18.sp
						)
					}
				}

			}

			Icon(
				modifier = Modifier.size(24.dp),
				painter = painterResource(R.drawable.ic_arr_details),
				contentDescription = "Open details"
			)
		}
	}
}
