package id.iiyh.inatrading.feature.auth.presentation

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.animateScrollBy
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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Visibility
import androidx.compose.material.icons.outlined.VisibilityOff
import androidx.compose.material.icons.outlined.VerifiedUser
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.ripple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.components.InaInnerTopAppBar
import id.iiyh.inatrading.core.ui.components.InaPrimaryButton
import id.iiyh.inatrading.core.ui.components.InaTextField
import id.iiyh.inatrading.core.ui.theme.AccentBlue
import id.iiyh.inatrading.core.ui.theme.AccentPurple
import id.iiyh.inatrading.core.ui.theme.AccentPurpleContainer
import id.iiyh.inatrading.core.ui.theme.Background
import id.iiyh.inatrading.core.ui.theme.BrandRed
import id.iiyh.inatrading.core.ui.theme.BrandRedLight
import id.iiyh.inatrading.core.ui.theme.InterFontFamily
import id.iiyh.inatrading.core.ui.theme.ManropeFontFamily
import id.iiyh.inatrading.core.ui.theme.OnSurface
import id.iiyh.inatrading.core.ui.theme.OnSurfaceVariant
import id.iiyh.inatrading.core.ui.theme.OutlineVariant
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLow
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLowest
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun LoginScreen(
    onBack: () -> Unit,
    onLoginSuccess: () -> Unit,
    onForgotPassword: () -> Unit,
    onRegister: () -> Unit,
    viewModel: LoginViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()
    val coroutineScope = rememberCoroutineScope()
    val scrollState = rememberScrollState()
    val density = LocalDensity.current
    val desiredFieldTopPx = with(density) { 96.dp.toPx() }
    var emailTopPx by remember { mutableFloatStateOf(0f) }
    var passwordTopPx by remember { mutableFloatStateOf(0f) }

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

    Scaffold(
        topBar = { InaInnerTopAppBar(onBack = onBack) },
        containerColor = Background,
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Background)
                .padding(innerPadding)
                .verticalScroll(scrollState),
        ) {
            // ── Hero Section ──────────────────────────────────────────────
            HeroSection()

            // ── Login Card (overlap hero) ─────────────────────────────────
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp)
                    .offset(y = (-32).dp), // -mt-8 sesuai desain
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(12.dp))
                        .background(SurfaceContainerLowest)
                        .padding(28.dp),
                    verticalArrangement = Arrangement.spacedBy(20.dp),
                ) {
                    // Email
                    InaTextField(
                        value         = uiState.email,
                        onValueChange = viewModel::onEmailChange,
                        label         = stringResource(R.string.login_email_label),
                        placeholder   = stringResource(R.string.login_email_placeholder),
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
                        modifier = Modifier.onGloballyPositioned {
                            emailTopPx = it.positionInRoot().y
                        },
                        onFocusChanged = {
                            if (it.isFocused) {
                                coroutineScope.launch {
                                    delay(150)
                                    scrollFieldNearTop(
                                        scrollState = scrollState,
                                        fieldTopPx = emailTopPx,
                                        desiredTopPx = desiredFieldTopPx,
                                    )
                                }
                            }
                        },
                    )

                    // Password
                    Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
                        Row(
                            modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            Text(
                                text  = stringResource(R.string.login_password_label).uppercase(),
                                style = MaterialTheme.typography.labelMedium,
                                color = OnSurfaceVariant,
                                letterSpacing = 1.sp,
                            )
                            Text(
                                text = stringResource(R.string.login_forgot_password),
                                style = MaterialTheme.typography.labelMedium,
                                color = AccentBlue,
                                fontWeight = FontWeight.Medium,
                                modifier = Modifier.clickable(
                                    interactionSource = remember { MutableInteractionSource() },
                                    indication = ripple(bounded = false),
                                    onClick = onForgotPassword,
                                ),
                            )
                        }

                        InaTextField(
                            value         = uiState.password,
                            onValueChange = viewModel::onPasswordChange,
                            placeholder   = stringResource(R.string.login_password_placeholder),
                            isPassword    = !uiState.isPasswordVisible,
                            modifier = Modifier.onGloballyPositioned {
                                passwordTopPx = it.positionInRoot().y
                            },
                            trailingIcon  = {
                                Icon(
                                    imageVector = if (uiState.isPasswordVisible)
                                        Icons.Outlined.VisibilityOff
                                    else
                                        Icons.Outlined.Visibility,
                                    contentDescription = if (uiState.isPasswordVisible)
                                        stringResource(R.string.login_hide_password)
                                    else
                                        stringResource(R.string.login_show_password),
                                    tint = OnSurfaceVariant,
                                    modifier = Modifier
                                        .size(20.dp)
                                        .clickable(onClick = viewModel::togglePasswordVisibility),
                                )
                            },
                            onFocusChanged = {
                                if (it.isFocused) {
                                    coroutineScope.launch {
                                        delay(150)
                                        scrollFieldNearTop(
                                            scrollState = scrollState,
                                            fieldTopPx = passwordTopPx,
                                            desiredTopPx = desiredFieldTopPx,
                                        )
                                    }
                                }
                            },
                        )
                    }

                    // API error
                    if (uiState.errorMessage != null) {
                        Text(
                            text  = uiState.errorMessage!!,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.error,
                            textAlign = TextAlign.Center,
                            modifier  = Modifier.fillMaxWidth(),
                        )
                    }

                    // CTA
                    InaPrimaryButton(
                        text      = stringResource(R.string.login_cta),
                        onClick   = viewModel::login,
                        isLoading = uiState.isLoading,
                        enabled   = uiState.email.isNotBlank() && uiState.password.isNotBlank(),
                    )

                    // Divider
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp),
                    ) {
                        HorizontalDivider(
                            modifier = Modifier.weight(1f),
                            color    = OutlineVariant.copy(alpha = 0.25f),
                        )
                        Text(
                            text  = stringResource(R.string.login_or_with).uppercase(),
                            style = MaterialTheme.typography.labelSmall,
                            color = OnSurfaceVariant.copy(alpha = 0.5f),
                            letterSpacing = 1.5.sp,
                        )
                        HorizontalDivider(
                            modifier = Modifier.weight(1f),
                            color    = OutlineVariant.copy(alpha = 0.25f),
                        )
                    }

                    // Google Sign-In
                    GoogleSignInButton(onClick = viewModel::loginWithGoogle)

                    // Register link
                    Box(
                        modifier = Modifier.fillMaxWidth(),
                        contentAlignment = Alignment.Center,
                    ) {
                        Text(
                            text = buildAnnotatedString {
                                withStyle(SpanStyle(
                                    fontFamily = InterFontFamily,
                                    fontSize   = 13.sp,
                                    color      = OnSurfaceVariant,
                                )) { append(stringResource(R.string.login_no_account).replace("<b>", "").replace("</b>", "")) }
                            },
                            modifier = Modifier.clickable(
                                interactionSource = remember { MutableInteractionSource() },
                                indication = null,
                                onClick = onRegister,
                            ),
                        )
                    }
                }
            }

            // ── Security Badge ────────────────────────────────────────────
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 24.dp),
                contentAlignment = Alignment.Center,
            ) {
                Row(
                    modifier = Modifier
                        .clip(RoundedCornerShape(9999.dp))
                        .background(AccentPurpleContainer.copy(alpha = 0.15f))
                        .padding(horizontal = 16.dp, vertical = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Icon(
                        Icons.Outlined.VerifiedUser,
                        contentDescription = null,
                        tint     = AccentPurple,
                        modifier = Modifier.size(16.dp),
                    )
                    Text(
                        text  = stringResource(R.string.login_security_badge).uppercase(),
                        style = MaterialTheme.typography.labelSmall,
                        color = AccentPurple,
                        letterSpacing = 1.sp,
                    )
                }
            }

            // ── Footer ────────────────────────────────────────────────────
            LoginFooter(
                onHelp  = {},
                onTerms = {},
            )
        }
    }
}

private suspend fun scrollFieldNearTop(
    scrollState: androidx.compose.foundation.ScrollState,
    fieldTopPx: Float,
    desiredTopPx: Float,
) {
    if (fieldTopPx <= 0f) return

    val scrollDelta = fieldTopPx - desiredTopPx
    if (scrollDelta > 0f) {
        scrollState.animateScrollBy(scrollDelta)
    }
}

// ─── Hero Section ─────────────────────────────────────────────────────────────
@Composable
private fun HeroSection() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(280.dp)
            .graphicsLayer {
                // Brand slope clip-path: polygon(0 0, 100% 0, 100% 85%, 0 100%)
                clip = true
                shape = BrandSlopeShape
            },
    ) {
        // Hero image (placeholder)
        AsyncImage(
            model              = null, // TODO: ganti dengan URL gambar marketplace
            contentDescription = null,
            contentScale       = ContentScale.Crop,
            modifier           = Modifier
                .fillMaxSize()
                .background(SurfaceContainerLow), // fallback placeholder color
        )

        // Gradient overlay bawah ke atas
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.verticalGradient(
                        colors = listOf(Color.Transparent, Background),
                        startY = 80f,
                    )
                )
        )

        // Text overlay
        Column(
            modifier = Modifier
                .align(Alignment.BottomStart)
                .padding(start = 24.dp, bottom = 48.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp),
        ) {
            Text(
                text  = stringResource(R.string.login_welcome_label).uppercase(),
                style = MaterialTheme.typography.labelSmall,
                color = BrandRed,
                fontWeight   = FontWeight.Bold,
                letterSpacing = 2.sp,
            )
            Text(
                text = buildAnnotatedString {
                    val lines = stringResource(R.string.login_hero_headline).split("\n")
                    withStyle(SpanStyle(
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.ExtraBold,
                        fontSize   = 36.sp,
                        color      = OnSurface,
                    )) { append(lines.firstOrNull() ?: "") }
                    append("\n")
                    withStyle(SpanStyle(
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.ExtraBold,
                        fontSize   = 36.sp,
                        color      = BrandRed,
                    )) { append(lines.getOrNull(1) ?: "") }
                },
            )
        }
    }
}

// ─── Brand Slope Shape ────────────────────────────────────────────────────────
private val BrandSlopeShape = object : androidx.compose.ui.graphics.Shape {
    override fun createOutline(
        size: androidx.compose.ui.geometry.Size,
        layoutDirection: androidx.compose.ui.unit.LayoutDirection,
        density: androidx.compose.ui.unit.Density,
    ): androidx.compose.ui.graphics.Outline {
        val path = androidx.compose.ui.graphics.Path().apply {
            moveTo(0f, 0f)
            lineTo(size.width, 0f)
            lineTo(size.width, size.height * 0.85f)
            lineTo(0f, size.height)
            close()
        }
        return androidx.compose.ui.graphics.Outline.Generic(path)
    }
}

// ─── Google Sign-In Button ────────────────────────────────────────────────────
@Composable
private fun GoogleSignInButton(onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(SurfaceContainerLow)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(color = OnSurface.copy(alpha = 0.06f)),
                onClick    = onClick,
            )
            .padding(vertical = 14.dp),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        // Google G logo (SVG re-created via Canvas)
        GoogleLogo(modifier = Modifier.size(20.dp))
        Spacer(modifier = Modifier.size(12.dp))
        Text(
            text  = stringResource(R.string.login_google),
            style = MaterialTheme.typography.labelLarge,
            fontWeight = FontWeight.SemiBold,
            color = OnSurface,
        )
    }
}

@Composable
private fun GoogleLogo(modifier: Modifier = Modifier) {
    androidx.compose.foundation.Canvas(modifier = modifier) {
        val w = size.width
        val h = size.height

        // Blue path (top-right)
        drawArc(
            color      = Color(0xFF4285F4),
            startAngle = -90f, sweepAngle = 90f, useCenter = false,
            size       = androidx.compose.ui.geometry.Size(w, h),
            style      = androidx.compose.ui.graphics.drawscope.Stroke(width = w * 0.22f),
        )
        // Green path (bottom)
        drawArc(
            color      = Color(0xFF34A853),
            startAngle = 0f, sweepAngle = 90f, useCenter = false,
            size       = androidx.compose.ui.geometry.Size(w, h),
            style      = androidx.compose.ui.graphics.drawscope.Stroke(width = w * 0.22f),
        )
        // Yellow path (left)
        drawArc(
            color      = Color(0xFFFBBC05),
            startAngle = 90f, sweepAngle = 90f, useCenter = false,
            size       = androidx.compose.ui.geometry.Size(w, h),
            style      = androidx.compose.ui.graphics.drawscope.Stroke(width = w * 0.22f),
        )
        // Red path (top-left)
        drawArc(
            color      = Color(0xFFEA4335),
            startAngle = 180f, sweepAngle = 90f, useCenter = false,
            size       = androidx.compose.ui.geometry.Size(w, h),
            style      = androidx.compose.ui.graphics.drawscope.Stroke(width = w * 0.22f),
        )
    }
}

// ─── Footer ───────────────────────────────────────────────────────────────────
@Composable
private fun LoginFooter(
    onHelp: () -> Unit,
    onTerms: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color(0xFFF8FAFC))
            .padding(vertical = 28.dp, horizontal = 24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Text(
            text       = "INA Trading",
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Black,
            fontSize   = 15.sp,
            color      = OnSurface,
        )
        Text(
            text  = stringResource(R.string.footer_copyright).uppercase(),
            style = MaterialTheme.typography.labelSmall,
            color = OnSurfaceVariant.copy(alpha = 0.5f),
            letterSpacing = 0.5.sp,
        )
        Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) {
            Text(
                text = stringResource(R.string.footer_help).uppercase(),
                style = MaterialTheme.typography.labelSmall,
                color = OnSurfaceVariant.copy(alpha = 0.5f),
                letterSpacing = 1.sp,
                modifier = Modifier.clickable(onClick = onHelp),
            )
            Text(
                text = stringResource(R.string.footer_terms).uppercase(),
                style = MaterialTheme.typography.labelSmall,
                color = OnSurfaceVariant.copy(alpha = 0.5f),
                letterSpacing = 1.sp,
                modifier = Modifier.clickable(onClick = onTerms),
            )
        }
    }
}

// ─── Extension helper ─────────────────────────────────────────────────────────
@Composable
private fun Spacer(modifier: Modifier) {
    androidx.compose.foundation.layout.Spacer(modifier = modifier)
}
