package com.radiola.ui.auth

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.radiola.ui.theme.AppMark
import com.radiola.ui.theme.RadiolaTheme
import com.radiola.ui.theme.RadiolaWordmark

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AuthScreen(
    onAuthSuccess: () -> Unit,
    onSkip: (() -> Unit)? = null,
    viewModel: AuthViewModel = hiltViewModel()
) {
    val state by viewModel.state.collectAsState()
    val email by viewModel.email.collectAsState()
    var code by remember { mutableStateOf("") }
    var showCodeInput by remember { mutableStateOf(false) }
    // Отслеживаем фокус на полях ввода для акцентной рамки
    var emailFocused by remember { mutableStateOf(false) }
    var codeFocused by remember { mutableStateOf(false) }
    val colors = RadiolaTheme.colors

    LaunchedEffect(state) {
        when (state) {
            is AuthViewModel.AuthState.CodeSent -> showCodeInput = true
            is AuthViewModel.AuthState.Success -> onAuthSuccess()
            else -> {}
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(colors.bgBase),
        contentAlignment = Alignment.Center
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 32.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // Логотип
            AppMark(size = 84.dp)
            Spacer(Modifier.height(4.dp))
            RadiolaWordmark(fontSize = 26)
            Spacer(Modifier.height(8.dp))

            // Заголовок
            Text(
                text = if (showCodeInput) "Введите код из письма" else "Добро пожаловать",
                style = MaterialTheme.typography.headlineLarge,
                color = colors.textPrimary,
                textAlign = TextAlign.Center
            )

            // Подзаголовок
            Text(
                text = if (showCodeInput)
                    "Мы отправили 6-значный код на $email"
                else
                    "Войдите, чтобы синхронизировать избранное и историю",
                style = MaterialTheme.typography.bodyMedium,
                color = colors.textSecondary,
                textAlign = TextAlign.Center
            )

            Spacer(Modifier.height(4.dp))

            if (!showCodeInput) {
                // Поле ввода email с акцентной рамкой при фокусе
                OutlinedTextField(
                    value = email,
                    onValueChange = viewModel::onEmailChange,
                    label = { Text("Email") },
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Email,
                        imeAction = ImeAction.Done
                    ),
                    keyboardActions = KeyboardActions(onDone = { viewModel.requestCode() }),
                    modifier = Modifier
                        .fillMaxWidth()
                        .onFocusChanged { emailFocused = it.isFocused },
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = colors.accent,
                        unfocusedBorderColor = colors.border,
                        focusedLabelColor = colors.accent,
                        unfocusedLabelColor = colors.textSecondary,
                        focusedTextColor = colors.textPrimary,
                        unfocusedTextColor = colors.textPrimary,
                        cursorColor = colors.accent,
                        focusedContainerColor = colors.surface,
                        unfocusedContainerColor = colors.surface
                    ),
                    shape = RoundedCornerShape(14.dp)
                )

                Button(
                    onClick = { viewModel.requestCode() },
                    modifier = Modifier.fillMaxWidth(),
                    enabled = state !is AuthViewModel.AuthState.Loading,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = colors.accent,
                        contentColor = colors.bgBase,
                        disabledContainerColor = colors.accentDim.copy(alpha = 0.5f),
                        disabledContentColor = colors.bgBase.copy(alpha = 0.5f)
                    ),
                    shape = RoundedCornerShape(14.dp)
                ) {
                    if (state is AuthViewModel.AuthState.Loading) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            color = colors.bgBase,
                            strokeWidth = 2.dp
                        )
                    } else {
                        Text("Получить код", style = MaterialTheme.typography.labelLarge)
                    }
                }

                if (onSkip != null) {
                    TextButton(
                        onClick = onSkip,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text(
                            "Продолжить без входа",
                            color = colors.textSecondary,
                            style = MaterialTheme.typography.labelLarge
                        )
                    }
                }
            } else {
                // Поле ввода кода с акцентной рамкой при фокусе
                OutlinedTextField(
                    value = code,
                    onValueChange = { if (it.length <= 6) code = it.uppercase() },
                    label = { Text("Код подтверждения") },
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.NumberPassword,
                        imeAction = ImeAction.Done
                    ),
                    keyboardActions = KeyboardActions(onDone = { viewModel.verifyCode(code) }),
                    modifier = Modifier
                        .fillMaxWidth()
                        .onFocusChanged { codeFocused = it.isFocused },
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = colors.accent,
                        unfocusedBorderColor = colors.border,
                        focusedLabelColor = colors.accent,
                        unfocusedLabelColor = colors.textSecondary,
                        focusedTextColor = colors.textPrimary,
                        unfocusedTextColor = colors.textPrimary,
                        cursorColor = colors.accent,
                        focusedContainerColor = colors.surface,
                        unfocusedContainerColor = colors.surface
                    ),
                    shape = RoundedCornerShape(14.dp)
                )

                Button(
                    onClick = { viewModel.verifyCode(code) },
                    modifier = Modifier.fillMaxWidth(),
                    enabled = state !is AuthViewModel.AuthState.Loading && code.length == 6,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = colors.accent,
                        contentColor = colors.bgBase,
                        disabledContainerColor = colors.accentDim.copy(alpha = 0.5f),
                        disabledContentColor = colors.bgBase.copy(alpha = 0.5f)
                    ),
                    shape = RoundedCornerShape(14.dp)
                ) {
                    if (state is AuthViewModel.AuthState.Loading) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            color = colors.bgBase,
                            strokeWidth = 2.dp
                        )
                    } else {
                        Text("Войти", style = MaterialTheme.typography.labelLarge)
                    }
                }

                TextButton(
                    onClick = {
                        showCodeInput = false
                        code = ""
                        viewModel.dismissError()
                    }
                ) {
                    Text(
                        "Отправить код повторно",
                        color = colors.textSecondary,
                        style = MaterialTheme.typography.labelLarge
                    )
                }
            }
        }
    }

    // Диалог ошибки
    if (state is AuthViewModel.AuthState.Error) {
        val errorMessage = (state as AuthViewModel.AuthState.Error).message
        AlertDialog(
            onDismissRequest = viewModel::dismissError,
            containerColor = colors.elevated,
            title = { Text("Ошибка", color = colors.textPrimary) },
            text = { Text(errorMessage, color = colors.textSecondary) },
            confirmButton = {
                TextButton(
                    onClick = viewModel::dismissError,
                    colors = ButtonDefaults.textButtonColors(contentColor = colors.accent)
                ) {
                    Text("OK")
                }
            }
        )
    }
}
