package app.closer.ui.onboarding

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
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.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.AddAPhoto
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.PhotoLibrary
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import app.closer.ui.components.CloserHeartLoader
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
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.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.core.navigation.AppRoute
import app.closer.ui.auth.AuthBackgroundBrush
import app.closer.ui.auth.AuthInk
import app.closer.ui.auth.AuthMuted
import app.closer.ui.auth.AuthOnPrimary
import app.closer.ui.auth.AuthPrimary
import app.closer.ui.auth.AuthPrimaryDeep
import app.closer.ui.auth.authTextFieldColors
import coil.compose.AsyncImage
import java.io.File

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreateProfileScreen(
    onNavigate: (String) -> Unit = {},
    viewModel: CreateProfileViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()
    val snackbar = remember { SnackbarHostState() }
    val focusManager = LocalFocusManager.current
    val context = LocalContext.current

    LaunchedEffect(state.success) {
        if (state.success) onNavigate(AppRoute.PAIR_PROMPT)
    }
    LaunchedEffect(state.error) {
        state.error?.let { snackbar.showSnackbar(it); viewModel.dismissError() }
    }

    val galleryLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickVisualMedia()
    ) { uri: Uri? ->
        uri?.let { viewModel.setPhotoUri(it.toString()) }
    }

    val cameraFile = remember(context) {
        File(context.filesDir, "photos/profile_temp.jpg").also { it.parentFile?.mkdirs() }
    }
    val cameraUri = remember(cameraFile) {
        FileProvider.getUriForFile(
            context,
            "${context.packageName}.fileprovider",
            cameraFile
        )
    }

    val cameraLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicture()
    ) { success ->
        if (success) viewModel.setPhotoUri(cameraUri.toString())
    }

    val cameraPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { granted ->
        if (granted) cameraLauncher.launch(cameraUri)
    }

    Scaffold(
        snackbarHost = { SnackbarHost(snackbar) },
        containerColor = Color.Transparent,
        modifier = Modifier.background(AuthBackgroundBrush),
        topBar = {
            if (state.currentStep != ProfileStep.NAME) {
                TopAppBar(
                    title = { Text("Create profile", color = AuthInk) },
                    navigationIcon = {
                        IconButton(onClick = viewModel::goBack) {
                            Icon(
                                Icons.AutoMirrored.Filled.ArrowBack,
                                contentDescription = "Back",
                                tint = AuthInk
                            )
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent)
                )
            }
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .imePadding()
                .verticalScroll(rememberScrollState())
                .padding(padding)
                .padding(horizontal = 28.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Spacer(Modifier.height(48.dp))

            Text(
                text = "Step ${state.currentStep.ordinal + 1} of 3",
                style = MaterialTheme.typography.labelMedium,
                color = AuthMuted,
                textAlign = TextAlign.Center
            )
            Spacer(Modifier.height(24.dp))

            when (state.currentStep) {
                ProfileStep.NAME -> NameStep(
                    state = state,
                    onNameChange = viewModel::updateDisplayName,
                    onContinue = {
                        focusManager.clearFocus()
                        viewModel.goToNextStep()
                    }
                )
                ProfileStep.SEX -> SexStep(
                    state = state,
                    onSexSelected = viewModel::selectSex,
                    onContinue = viewModel::goToNextStep
                )
                ProfileStep.PHOTO -> PhotoStep(
                    state = state,
                    onGallery = { galleryLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) },
                    onCamera = {
                        when {
                            ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED -> cameraLauncher.launch(cameraUri)
                            else -> cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
                        }
                    },
                    onSkip = viewModel::skipPhoto,
                    onContinue = viewModel::goToNextStep
                )
            }

            Spacer(Modifier.height(32.dp))
        }
    }
}

@Composable
private fun NameStep(
    state: CreateProfileUiState,
    onNameChange: (String) -> Unit,
    onContinue: () -> Unit
) {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Text(
            text = "What should your\npartner call you?",
            style = MaterialTheme.typography.headlineMedium,
            color = AuthInk,
            textAlign = TextAlign.Center
        )
        Spacer(Modifier.height(8.dp))
        Text(
            text = "This is how you'll appear to them in the app.",
            style = MaterialTheme.typography.bodyMedium,
            color = AuthMuted,
            textAlign = TextAlign.Center
        )

        Spacer(Modifier.height(40.dp))

        OutlinedTextField(
            value = state.displayName,
            onValueChange = onNameChange,
            label = { Text("Your name") },
            singleLine = true,
            modifier = Modifier.fillMaxWidth(),
            colors = authTextFieldColors(),
            isError = state.nameError != null,
            supportingText = state.nameError?.let { { Text(it, color = MaterialTheme.colorScheme.error) } },
            keyboardOptions = KeyboardOptions(
                capitalization = KeyboardCapitalization.Words,
                keyboardType = KeyboardType.Text,
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(onDone = { onContinue() })
        )

        Spacer(Modifier.height(28.dp))

        Button(
            onClick = onContinue,
            enabled = !state.isLoading,
            modifier = Modifier.fillMaxWidth().height(56.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = AuthPrimary,
                contentColor = AuthOnPrimary
            )
        ) {
            if (state.isLoading) CloserHeartLoader(size = 22.dp)
            else Text("Continue", style = MaterialTheme.typography.labelLarge)
        }
    }
}

@Composable
private fun SexStep(
    state: CreateProfileUiState,
    onSexSelected: (String) -> Unit,
    onContinue: () -> Unit
) {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Text(
            text = "What's your sex?",
            style = MaterialTheme.typography.headlineMedium,
            color = AuthInk,
            textAlign = TextAlign.Center
        )
        Spacer(Modifier.height(12.dp))
        Text(
            text = "Some questions — especially in Desire Sync — are tailored based on your sex. This just helps us show you the right ones.",
            style = MaterialTheme.typography.bodyMedium,
            color = AuthMuted,
            textAlign = TextAlign.Center
        )

        Spacer(Modifier.height(32.dp))

        SexOption(
            label = "Female",
            selected = state.sex == "female",
            onClick = { onSexSelected("female") }
        )
        Spacer(Modifier.height(12.dp))
        SexOption(
            label = "Male",
            selected = state.sex == "male",
            onClick = { onSexSelected("male") }
        )

        state.sexError?.let {
            Spacer(Modifier.height(12.dp))
            Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
        }

        Spacer(Modifier.height(28.dp))

        Button(
            onClick = onContinue,
            enabled = !state.isLoading,
            modifier = Modifier.fillMaxWidth().height(56.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = AuthPrimary,
                contentColor = AuthOnPrimary
            )
        ) {
            if (state.isLoading) CloserHeartLoader(size = 22.dp)
            else Text("Continue", style = MaterialTheme.typography.labelLarge)
        }
    }
}

@Composable
private fun SexOption(label: String, selected: Boolean, onClick: () -> Unit) {
    val background = if (selected) AuthPrimary else MaterialTheme.colorScheme.surface.copy(alpha = 0.78f)
    val contentColor = if (selected) AuthOnPrimary else AuthInk
    val borderColor = if (selected) AuthPrimary else AuthMuted.copy(alpha = 0.24f)

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(56.dp)
            .clip(RoundedCornerShape(16.dp))
            .background(background)
            .border(1.dp, borderColor, RoundedCornerShape(16.dp))
            .clickable(onClick = onClick),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyLarge,
            color = contentColor
        )
    }
}

@Composable
private fun PhotoStep(
    state: CreateProfileUiState,
    onGallery: () -> Unit,
    onCamera: () -> Unit,
    onSkip: () -> Unit,
    onContinue: () -> Unit
) {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Text(
            text = "Add a photo",
            style = MaterialTheme.typography.headlineMedium,
            color = AuthInk,
            textAlign = TextAlign.Center
        )
        Spacer(Modifier.height(8.dp))
        Text(
            text = "This is optional. Your partner will see it once you connect.",
            style = MaterialTheme.typography.bodyMedium,
            color = AuthMuted,
            textAlign = TextAlign.Center
        )

        Spacer(Modifier.height(32.dp))

        val imageUri = state.photoUri ?: state.photoUrl.takeIf { it.isNotBlank() }
        Box(
            modifier = Modifier
                .size(140.dp)
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.78f))
                .border(2.dp, AuthPrimary.copy(alpha = 0.3f), CircleShape),
            contentAlignment = Alignment.Center
        ) {
            if (imageUri != null) {
                AsyncImage(
                    model = imageUri,
                    contentDescription = "Profile photo",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop,
                    placeholder = rememberVectorPainter(Icons.Filled.Person),
                    error = rememberVectorPainter(Icons.Filled.Person)
                )
            } else {
                Icon(
                    Icons.Filled.Person,
                    contentDescription = "Profile photo",
                    modifier = Modifier.size(64.dp),
                    tint = AuthMuted
                )
            }
        }

        Spacer(Modifier.height(24.dp))

        OutlinedButton(
            onClick = onGallery,
            modifier = Modifier.fillMaxWidth().height(52.dp),
            colors = ButtonDefaults.outlinedButtonColors(
                containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.78f),
                contentColor = AuthInk
            )
        ) {
            Icon(Icons.Filled.PhotoLibrary, contentDescription = null, modifier = Modifier.padding(end = 8.dp))
            Text("Choose from gallery", style = MaterialTheme.typography.labelLarge)
        }

        Spacer(Modifier.height(12.dp))

        OutlinedButton(
            onClick = onCamera,
            modifier = Modifier.fillMaxWidth().height(52.dp),
            colors = ButtonDefaults.outlinedButtonColors(
                containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.78f),
                contentColor = AuthInk
            )
        ) {
            Icon(Icons.Filled.AddAPhoto, contentDescription = null, modifier = Modifier.padding(end = 8.dp))
            Text("Take a photo", style = MaterialTheme.typography.labelLarge)
        }

        Spacer(Modifier.height(12.dp))

        TextButton(onClick = onSkip, modifier = Modifier.fillMaxWidth()) {
            Text("Skip for now", color = AuthPrimaryDeep)
        }

        Spacer(Modifier.height(16.dp))

        Button(
            onClick = onContinue,
            enabled = !state.isLoading,
            modifier = Modifier.fillMaxWidth().height(56.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = AuthPrimary,
                contentColor = AuthOnPrimary
            )
        ) {
            if (state.isLoading) CloserHeartLoader(size = 22.dp)
            else Text("Continue", style = MaterialTheme.typography.labelLarge)
        }
    }
}
