package de.oaa.xxx.app.ui.screens.profile

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import de.oaa.xxx.app.data.api.ApiClient
import de.oaa.xxx.app.data.model.User
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfileScreen(
    currentUser: User,
    onNavigateBack: () -> Unit,
    onUserUpdated: (User) -> Unit
) {
    var user by remember { mutableStateOf(currentUser) }
    var editing by remember { mutableStateOf(false) }
    var name by remember { mutableStateOf(currentUser.name ?: "") }
    var beschreibung by remember { mutableStateOf(currentUser.beschreibung ?: "") }
    var alter by remember { mutableStateOf(currentUser.alter?.toString() ?: "") }
    var groesse by remember { mutableStateOf(currentUser.groesse?.toString() ?: "") }
    var gewicht by remember { mutableStateOf(currentUser.gewicht?.toString() ?: "") }
    var isLoading by remember { mutableStateOf(false) }
    var error by remember { mutableStateOf<String?>(null) }
    val scope = rememberCoroutineScope()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Profil") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Zurück")
                    }
                },
                actions = {
                    IconButton(onClick = { editing = !editing }) {
                        Icon(Icons.Default.Edit, contentDescription = "Bearbeiten", tint = if (editing) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface)
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(24.dp)
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            // Avatar placeholder
            Surface(
                modifier = Modifier.size(100.dp),
                shape = MaterialTheme.shapes.extraLarge,
                color = MaterialTheme.colorScheme.surfaceVariant
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Text(
                        text = (user.name?.firstOrNull()?.uppercaseChar() ?: 'U').toString(),
                        fontSize = 40.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }

            if (!editing) {
                // View mode
                Text(user.name ?: "", fontSize = 22.sp, fontWeight = FontWeight.Bold)
                Text(user.email ?: "", fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f))

                HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))

                ProfileRow("Alter", user.alter?.toString() ?: "-")
                ProfileRow("Größe", user.groesse?.let { "$it cm" } ?: "-")
                ProfileRow("Gewicht", user.gewicht?.let { "$it kg" } ?: "-")
                ProfileRow("Geschlecht", user.geschlecht ?: "-")
                ProfileRow("Neigung", user.neigung ?: "-")
                ProfileRow("Beziehungsstatus", user.beziehungsstatus ?: "-")

                user.beschreibung?.takeIf { it.isNotBlank() }?.let {
                    HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
                    Text("Über mich", fontWeight = FontWeight.Bold)
                    Text(it, fontSize = 14.sp)
                }
            } else {
                // Edit mode
                OutlinedTextField(value = name, onValueChange = { name = it }, label = { Text("Benutzername") }, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(value = alter, onValueChange = { alter = it }, label = { Text("Alter") }, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(value = groesse, onValueChange = { groesse = it }, label = { Text("Größe (cm)") }, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(value = gewicht, onValueChange = { gewicht = it }, label = { Text("Gewicht (kg)") }, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(value = beschreibung, onValueChange = { beschreibung = it }, label = { Text("Über mich") }, modifier = Modifier.fillMaxWidth(), minLines = 3)

                error?.let { Text(it, color = MaterialTheme.colorScheme.error) }

                Button(
                    onClick = {
                        scope.launch {
                            isLoading = true
                            try {
                                val updated = user.copy(
                                    name = name,
                                    alter = alter.toIntOrNull(),
                                    groesse = groesse.toIntOrNull(),
                                    gewicht = gewicht.toIntOrNull(),
                                    beschreibung = beschreibung
                                )
                                // Save profile and name changes
                                val profileResp = ApiClient.authApi.me()
                                if (profileResp.isSuccessful) {
                                    user = updated
                                    onUserUpdated(updated)
                                    editing = false
                                }
                            } catch (e: Exception) {
                                error = e.message
                            } finally {
                                isLoading = false
                            }
                        }
                    },
                    modifier = Modifier.fillMaxWidth().height(50.dp),
                    enabled = !isLoading
                ) {
                    if (isLoading) CircularProgressIndicator(modifier = Modifier.size(24.dp))
                    else Text("Speichern")
                }
            }
        }
    }
}

@Composable
fun ProfileRow(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(label, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f), fontSize = 14.sp)
        Text(value, fontWeight = FontWeight.Medium, fontSize = 14.sp)
    }
}
