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

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.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.Lock
import androidx.compose.material.icons.outlined.Mail
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material.icons.outlined.PhoneIphone
import androidx.compose.material.icons.outlined.Visibility
import androidx.compose.material.icons.outlined.VisibilityOff
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.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
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.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
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.Background
import id.iiyh.inatrading.core.ui.theme.BrandRed
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.SurfaceContainerHighest
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLow
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLowest

@Composable
fun RegisterScreen(
    onBack: () -> Unit,
    onRegisterSuccess: () -> Unit,
    onLoginClick: () -> Unit,
    viewModel: RegisterViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()

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

    Scaffold(
        topBar = { InaInnerTopAppBar(onBack = onBack) },
        containerColor = Background,
    ) { innerPadding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                // Brand slope background: diagonal gradient kanan bawah
                .drawBehind {
                    val breakX = size.width * 0.0f
                    val breakY = size.height * 0.6f
                    drawRect(
                        brush = Brush.linearGradient(
                            colors = listOf(Color.Transparent, SurfaceContainerHighest.copy(alpha = 0.4f)),
                            start  = Offset(breakX, breakY),
                            end    = Offset(size.width, size.height),
                        )
                    )
                }
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(innerPadding)
                    .verticalScroll(rememberScrollState())
                    .padding(horizontal = 24.dp)
                    .padding(bottom = 32.dp),
                verticalArrangement = Arrangement.spacedBy(0.dp),
            ) {
                // ── Editorial Headline ────────────────────────────────────
                Spacer(modifier = Modifier.height(32.dp))

                Text(
                    text  = stringResource(R.string.register_label).uppercase(),
                    style = MaterialTheme.typography.labelMedium,
                    color = AccentBlue,
                    fontWeight    = FontWeight.SemiBold,
                    letterSpacing = 1.5.sp,
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text       = stringResource(R.string.register_title),
                    fontFamily = ManropeFontFamily,
                    fontWeight = FontWeight.ExtraBold,
                    fontSize   = 34.sp,
                    color      = OnSurface,
                    lineHeight = 40.sp,
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text  = stringResource(R.string.register_subtitle),
                    style = MaterialTheme.typography.bodyMedium,
                    color = OnSurfaceVariant,
                )

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

                // ── Form Card ─────────────────────────────────────────────
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(12.dp))
                        .background(SurfaceContainerLowest)
                        .padding(24.dp),
                    verticalArrangement = Arrangement.spacedBy(20.dp),
                ) {
                    // Full Name
                    InaTextField(
                        value         = uiState.name,
                        onValueChange = viewModel::onNameChange,
                        label         = stringResource(R.string.register_full_name_label),
                        placeholder   = stringResource(R.string.register_full_name_placeholder),
                        isError       = uiState.errors.name != null,
                        errorMessage  = if (uiState.errors.name != null)
                            stringResource(R.string.register_error_name_empty) else "",
                        trailingIcon  = {
                            Icon(
                                Icons.Outlined.Person,
                                contentDescription = null,
                                tint     = OnSurfaceVariant.copy(alpha = 0.5f),
                                modifier = Modifier.size(20.dp),
                            )
                        },
                    )

                    // Email
                    InaTextField(
                        value         = uiState.email,
                        onValueChange = viewModel::onEmailChange,
                        label         = stringResource(R.string.login_email_label),
                        placeholder   = stringResource(R.string.login_email_placeholder),
                        isError       = uiState.errors.email != null,
                        errorMessage  = when (uiState.errors.email) {
                            "invalid" -> stringResource(R.string.register_error_invalid_email)
                            else      -> if (uiState.errors.email != null)
                                stringResource(R.string.register_error_invalid_email) else ""
                        },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
                        trailingIcon  = {
                            Icon(
                                Icons.Outlined.Mail,
                                contentDescription = null,
                                tint     = OnSurfaceVariant.copy(alpha = 0.5f),
                                modifier = Modifier.size(20.dp),
                            )
                        },
                    )

                    // Phone
                    InaTextField(
                        value         = uiState.phone,
                        onValueChange = viewModel::onPhoneChange,
                        label         = stringResource(R.string.register_phone_label),
                        placeholder   = stringResource(R.string.register_phone_placeholder),
                        isError       = uiState.errors.phone != null,
                        errorMessage  = if (uiState.errors.phone != null)
                            stringResource(R.string.register_error_phone_empty) else "",
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone),
                        trailingIcon  = {
                            Icon(
                                Icons.Outlined.PhoneIphone,
                                contentDescription = null,
                                tint     = OnSurfaceVariant.copy(alpha = 0.5f),
                                modifier = Modifier.size(20.dp),
                            )
                        },
                    )

                    // Password
                    InaTextField(
                        value         = uiState.password,
                        onValueChange = viewModel::onPasswordChange,
                        label         = stringResource(R.string.login_password_label),
                        placeholder   = stringResource(R.string.register_password_placeholder),
                        isPassword    = !uiState.isPasswordVisible,
                        isError       = uiState.errors.password != null,
                        errorMessage  = when (uiState.errors.password) {
                            "too_short" -> stringResource(R.string.register_error_password_too_short)
                            else        -> if (uiState.errors.password != null)
                                stringResource(R.string.register_error_password_too_short) else ""
                        },
                        trailingIcon  = {
                            Icon(
                                imageVector = if (uiState.isPasswordVisible)
                                    Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility,
                                contentDescription = null,
                                tint     = OnSurfaceVariant,
                                modifier = Modifier
                                    .size(20.dp)
                                    .clickable(onClick = viewModel::togglePasswordVisibility),
                            )
                        },
                    )

                    // Confirm Password
                    InaTextField(
                        value         = uiState.confirmPassword,
                        onValueChange = viewModel::onConfirmPasswordChange,
                        label         = stringResource(R.string.register_confirm_password_label),
                        placeholder   = stringResource(R.string.register_confirm_password_placeholder),
                        isPassword    = !uiState.isConfirmPasswordVisible,
                        isError       = uiState.errors.confirmPassword != null,
                        errorMessage  = if (uiState.errors.confirmPassword != null)
                            stringResource(R.string.register_error_password_mismatch) else "",
                        trailingIcon  = {
                            Icon(
                                imageVector = if (uiState.isConfirmPasswordVisible)
                                    Icons.Outlined.VisibilityOff else Icons.Outlined.Lock,
                                contentDescription = null,
                                tint     = OnSurfaceVariant.copy(
                                    alpha = if (uiState.confirmPassword.isEmpty()) 0.5f else 1f
                                ),
                                modifier = Modifier
                                    .size(20.dp)
                                    .clickable(
                                        enabled = uiState.confirmPassword.isNotEmpty(),
                                        onClick = viewModel::toggleConfirmPasswordVisibility,
                                    ),
                            )
                        },
                    )

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

                    // CTA
                    Spacer(modifier = Modifier.height(4.dp))
                    InaPrimaryButton(
                        text      = stringResource(R.string.register_cta),
                        onClick   = viewModel::register,
                        isLoading = uiState.isLoading,
                    )

                    // Divider
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp),
                    ) {
                        HorizontalDivider(
                            modifier = Modifier.weight(1f),
                            color    = OutlineVariant.copy(alpha = 0.3f),
                        )
                        Text(
                            text  = stringResource(R.string.register_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.3f),
                        )
                    }

                    // Google button (reuse dari LoginScreen)
                    RegisterGoogleButton(onClick = viewModel::registerWithGoogle)
                }

                // ── "Already have account?" ───────────────────────────────
                Spacer(modifier = Modifier.height(24.dp))
                Box(
                    modifier = Modifier.fillMaxWidth(),
                    contentAlignment = Alignment.Center,
                ) {
                    Text(
                        text = buildAnnotatedString {
                            withStyle(SpanStyle(
                                fontFamily = InterFontFamily,
                                fontSize   = 13.sp,
                                color      = OnSurfaceVariant,
                            )) { append(stringResource(R.string.register_have_account)
                                .replace("<b>", "").replace("</b>", "")) }
                        },
                        modifier = Modifier.clickable(
                            interactionSource = remember { MutableInteractionSource() },
                            indication = null,
                            onClick    = onLoginClick,
                        ),
                    )
                }

                // ── Terms of Service ──────────────────────────────────────
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = buildAnnotatedString {
                        val full  = stringResource(R.string.register_terms)
                        val terms = stringResource(R.string.settings_terms)
                        val priv  = stringResource(R.string.settings_privacy_policy)

                        // Render teks biasa, link underline untuk terms & privacy
                        val baseStyle = SpanStyle(
                            fontFamily = InterFontFamily,
                            fontSize   = 11.sp,
                            color      = OnSurfaceVariant.copy(alpha = 0.6f),
                        )
                        val linkStyle = baseStyle.copy(
                            textDecoration = TextDecoration.Underline,
                            color = OnSurfaceVariant.copy(alpha = 0.8f),
                        )
                        withStyle(baseStyle) {
                            append("Dengan mendaftar, Anda menyetujui ")
                        }
                        withStyle(linkStyle) { append(terms) }
                        withStyle(baseStyle) { append(" serta ") }
                        withStyle(linkStyle) { append(priv) }
                        withStyle(baseStyle) {
                            append(" INA Trading untuk mendukung pertumbuhan UMKM Nasional.")
                        }
                    },
                    textAlign = TextAlign.Center,
                    modifier  = Modifier.padding(horizontal = 8.dp),
                )
            }
        }
    }
}

@Composable
private fun RegisterGoogleButton(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
        androidx.compose.foundation.Canvas(modifier = Modifier.size(20.dp)) {
            val w = size.width
            val h = size.height
            val stroke = androidx.compose.ui.graphics.drawscope.Stroke(width = w * 0.22f)
            drawArc(Color(0xFF4285F4), -90f,  90f, false, size = androidx.compose.ui.geometry.Size(w, h), style = stroke)
            drawArc(Color(0xFF34A853),   0f,  90f, false, size = androidx.compose.ui.geometry.Size(w, h), style = stroke)
            drawArc(Color(0xFFFBBC05),  90f,  90f, false, size = androidx.compose.ui.geometry.Size(w, h), style = stroke)
            drawArc(Color(0xFFEA4335), 180f,  90f, false, size = androidx.compose.ui.geometry.Size(w, h), style = stroke)
        }
        Spacer(modifier = Modifier.size(12.dp))
        Text(
            text  = stringResource(R.string.login_google),
            style = MaterialTheme.typography.labelLarge,
            fontWeight = FontWeight.SemiBold,
            color = OnSurface,
        )
    }
}
