package cy.hexor.furumi.ui.login

import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
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.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import cy.hexor.furumi.ui.theme.FurumiElectricCyan
import cy.hexor.furumi.ui.theme.FurumiHotOrange
import cy.hexor.furumi.ui.theme.FurumiInk
import cy.hexor.furumi.ui.theme.FurumiLine
import cy.hexor.furumi.ui.theme.FurumiNeonPink
import cy.hexor.furumi.ui.theme.FurumiNeonViolet
import cy.hexor.furumi.ui.theme.FurumiSurface
import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh
import cy.hexor.furumi.ui.theme.FurumiTextMuted

@Composable
fun LoginScreen(
    viewModel: LoginViewModel = hiltViewModel(),
    onLoginSuccess: () -> Unit
) {
    val uiState by viewModel.uiState.collectAsState()
    val context = LocalContext.current
    val focusManager = LocalFocusManager.current
    val loginFocusRequester = remember { FocusRequester() }
    val passwordFocusRequester = remember { FocusRequester() }
    val isSsoLoading = uiState.loadingAction == LoginLoadingAction.Sso
    val isPasswordLoading = uiState.loadingAction == LoginLoadingAction.Password
    var isPasswordLoginVisible by rememberSaveable { mutableStateOf(false) }

    LaunchedEffect(uiState.isAuthenticated) {
        if (uiState.isAuthenticated) {
            onLoginSuccess()
        }
    }

    LaunchedEffect(uiState.externalAuthUrl) {
        uiState.externalAuthUrl?.let { authUrl ->
            CustomTabsIntent.Builder()
                .build()
                .launchUrl(context, Uri.parse(authUrl))
            viewModel.onExternalAuthUrlOpened()
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
            .windowInsetsPadding(WindowInsets.safeDrawing)
            .imePadding()
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 24.dp, vertical = 28.dp),
            verticalArrangement = Arrangement.SpaceBetween
        ) {
            Column {
                BrandHeader()
                Spacer(modifier = Modifier.height(34.dp))
                AlbumTileStrip()
            }

            Spacer(modifier = Modifier.height(32.dp))

            LoginControls(
                uiState = uiState,
                isPasswordLoginVisible = isPasswordLoginVisible,
                isSsoLoading = isSsoLoading,
                isPasswordLoading = isPasswordLoading,
                loginFocusRequester = loginFocusRequester,
                passwordFocusRequester = passwordFocusRequester,
                onPasswordLoginVisibilityChange = {
                    isPasswordLoginVisible = !isPasswordLoginVisible
                    if (!isPasswordLoginVisible) {
                        focusManager.clearFocus()
                    }
                },
                onServerUrlChange = viewModel::onServerUrlChange,
                onLoginChange = viewModel::onLoginChange,
                onPasswordChange = viewModel::onPasswordChange,
                onSsoClick = {
                    focusManager.clearFocus()
                    viewModel.loginWithSSO()
                },
                onPasswordLoginClick = {
                    focusManager.clearFocus()
                    viewModel.login()
                }
            )
        }
    }
}

@Composable
private fun BrandHeader() {
    Row(
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box(
            modifier = Modifier
                .size(34.dp)
                .clip(CircleShape)
                .background(FurumiNeonPink),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "F",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onPrimary,
                fontWeight = FontWeight.ExtraBold
            )
        }

        Spacer(modifier = Modifier.width(10.dp))

        Text(
            text = "Furumi",
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.onBackground
        )
    }
}

@Composable
private fun AlbumTileStrip() {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        AlbumTile(
            modifier = Modifier.weight(1f),
            brush = Brush.linearGradient(listOf(FurumiNeonPink, FurumiSurfaceHigh))
        )
        AlbumTile(
            modifier = Modifier.weight(1f),
            brush = Brush.linearGradient(listOf(FurumiElectricCyan, FurumiInk))
        )
        AlbumTile(
            modifier = Modifier.weight(1f),
            brush = Brush.linearGradient(listOf(FurumiNeonViolet, FurumiHotOrange, FurumiSurface))
        )
    }
}

@Composable
private fun AlbumTile(
    modifier: Modifier,
    brush: Brush
) {
    Box(
        modifier = modifier
            .aspectRatio(1f)
            .clip(RoundedCornerShape(8.dp))
            .background(brush)
            .border(1.dp, Color.White.copy(alpha = 0.08f), RoundedCornerShape(8.dp))
    )
}

@Composable
private fun LoginControls(
    uiState: LoginUiState,
    isPasswordLoginVisible: Boolean,
    isSsoLoading: Boolean,
    isPasswordLoading: Boolean,
    loginFocusRequester: FocusRequester,
    passwordFocusRequester: FocusRequester,
    onPasswordLoginVisibilityChange: () -> Unit,
    onServerUrlChange: (String) -> Unit,
    onLoginChange: (String) -> Unit,
    onPasswordChange: (String) -> Unit,
    onSsoClick: () -> Unit,
    onPasswordLoginClick: () -> Unit
) {
    Column {
        LoginTextField(
            value = uiState.serverUrl,
            onValueChange = onServerUrlChange,
            label = "Server URL",
            placeholder = "https://music.hexor.cy",
            enabled = !uiState.isLoading,
            keyboardType = KeyboardType.Uri,
            imeAction = if (isPasswordLoginVisible) ImeAction.Next else ImeAction.Go,
            keyboardActions = KeyboardActions(
                onGo = { onSsoClick() },
                onNext = { loginFocusRequester.requestFocus() }
            )
        )

        if (uiState.error != null) {
            Spacer(modifier = Modifier.height(12.dp))
            Text(
                text = uiState.error,
                color = MaterialTheme.colorScheme.error,
                style = MaterialTheme.typography.bodyMedium
            )
        }

        Spacer(modifier = Modifier.height(16.dp))

        Button(
            onClick = onSsoClick,
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp),
            enabled = !uiState.isLoading,
            shape = CircleShape,
            colors = ButtonDefaults.buttonColors(
                containerColor = FurumiNeonPink,
                contentColor = MaterialTheme.colorScheme.onPrimary,
                disabledContainerColor = FurumiSurfaceHigh,
                disabledContentColor = FurumiTextMuted
            )
        ) {
            if (isSsoLoading) {
                CircularProgressIndicator(
                    modifier = Modifier.size(24.dp),
                    color = MaterialTheme.colorScheme.onPrimary,
                    strokeWidth = 2.dp
                )
            } else {
                Text("Continue with SSO")
            }
        }

        Spacer(modifier = Modifier.height(14.dp))

        TextButton(
            onClick = onPasswordLoginVisibilityChange,
            modifier = Modifier.align(Alignment.CenterHorizontally),
            enabled = !uiState.isLoading,
            colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onBackground)
        ) {
            Text(
                text = if (isPasswordLoginVisible) "Hide password login" else "Sign in with password",
                style = MaterialTheme.typography.labelSmall
            )
        }

        if (isPasswordLoginVisible) {
            Spacer(modifier = Modifier.height(8.dp))
            HorizontalDivider(color = FurumiLine)
            Spacer(modifier = Modifier.height(18.dp))

            LoginTextField(
                value = uiState.login,
                onValueChange = onLoginChange,
                label = "Username or email",
                placeholder = "name@example.com",
                enabled = !uiState.isLoading,
                keyboardType = KeyboardType.Email,
                imeAction = ImeAction.Next,
                keyboardActions = KeyboardActions(
                    onNext = { passwordFocusRequester.requestFocus() }
                ),
                modifier = Modifier.focusRequester(loginFocusRequester)
            )

            Spacer(modifier = Modifier.height(10.dp))

            LoginTextField(
                value = uiState.password,
                onValueChange = onPasswordChange,
                label = "Password",
                enabled = !uiState.isLoading,
                keyboardType = KeyboardType.Password,
                imeAction = ImeAction.Done,
                keyboardActions = KeyboardActions(
                    onDone = { onPasswordLoginClick() }
                ),
                visualTransformation = PasswordVisualTransformation(),
                modifier = Modifier.focusRequester(passwordFocusRequester)
            )

            Spacer(modifier = Modifier.height(16.dp))

            OutlinedButton(
                onClick = onPasswordLoginClick,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(54.dp),
                enabled = !uiState.isLoading,
                shape = CircleShape,
                border = BorderStroke(1.dp, MaterialTheme.colorScheme.onBackground),
                colors = ButtonDefaults.outlinedButtonColors(
                    contentColor = MaterialTheme.colorScheme.onBackground,
                    disabledContentColor = FurumiTextMuted
                )
            ) {
                if (isPasswordLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(24.dp),
                        color = MaterialTheme.colorScheme.onBackground,
                        strokeWidth = 2.dp
                    )
                } else {
                    Text("Sign in")
                }
            }
        }
    }
}

@Composable
private fun LoginTextField(
    value: String,
    onValueChange: (String) -> Unit,
    label: String,
    enabled: Boolean,
    keyboardType: KeyboardType,
    imeAction: ImeAction,
    keyboardActions: KeyboardActions,
    modifier: Modifier = Modifier,
    placeholder: String? = null,
    visualTransformation: PasswordVisualTransformation? = null
) {
    OutlinedTextField(
        value = value,
        onValueChange = onValueChange,
        label = { Text(label) },
        modifier = modifier.fillMaxWidth(),
        placeholder = placeholder?.let { { Text(it) } },
        enabled = enabled,
        singleLine = true,
        maxLines = 1,
        visualTransformation = visualTransformation ?: androidx.compose.ui.text.input.VisualTransformation.None,
        keyboardOptions = KeyboardOptions(
            keyboardType = keyboardType,
            imeAction = imeAction
        ),
        keyboardActions = keyboardActions,
        shape = RoundedCornerShape(8.dp),
        colors = OutlinedTextFieldDefaults.colors(
            focusedTextColor = MaterialTheme.colorScheme.onBackground,
            unfocusedTextColor = MaterialTheme.colorScheme.onBackground,
            disabledTextColor = FurumiTextMuted,
            focusedContainerColor = FurumiSurface,
            unfocusedContainerColor = FurumiSurface,
            disabledContainerColor = FurumiSurface,
            focusedBorderColor = FurumiNeonPink,
            unfocusedBorderColor = FurumiLine,
            disabledBorderColor = FurumiLine,
            focusedLabelColor = FurumiNeonPink,
            unfocusedLabelColor = FurumiTextMuted,
            disabledLabelColor = FurumiTextMuted,
            focusedPlaceholderColor = FurumiTextMuted,
            unfocusedPlaceholderColor = FurumiTextMuted
        )
    )
}
