package com.atridad.ascently.ui.health

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.atridad.ascently.data.health.HealthConnectManager
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HealthConnectCard(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val healthConnectManager = remember { HealthConnectManager(context) }
    val coroutineScope = rememberCoroutineScope()

    // State tracking
    var isHealthConnectAvailable by remember { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }

    // Collect flows
    val isEnabled by healthConnectManager.isEnabled.collectAsState(initial = false)
    val hasPermissions by healthConnectManager.hasPermissions.collectAsState(initial = false)

    val isCompatible by healthConnectManager.isCompatible.collectAsState(initial = true)

    // Permission launcher
    val permissionLauncher =
        rememberLauncherForActivityResult(
            contract = healthConnectManager.getPermissionRequestContract(),
        ) { _ ->
            coroutineScope.launch {
                val allGranted = healthConnectManager.hasAllPermissions()
                if (!allGranted) {
                    errorMessage =
                        "Some Health Connect permissions were not granted. Please grant all permissions to enable syncing."
                } else {
                    errorMessage = null
                }
            }
        }

    // Check Health Connect availability on first load
    LaunchedEffect(Unit) {
        coroutineScope.launch {
            try {
                healthConnectManager.isHealthConnectAvailable().collect { available ->
                    isHealthConnectAvailable = available
                    isLoading = false

                    if (!available && isCompatible) {
                        errorMessage = "Health Connect is not available on this device"
                    } else if (!isCompatible) {
                        errorMessage =
                            "Health Connect API compatibility issue. Please update your device or the app."
                    }
                }
            } catch (e: Exception) {
                isLoading = false
                errorMessage = "Error checking Health Connect availability: ${e.message}"
            }
        }
    }

    Card(
        modifier = modifier.fillMaxWidth(),
        shape = RoundedCornerShape(16.dp),
        colors =
        CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant,
        ),
    ) {
        Column(
            modifier = Modifier.fillMaxWidth().padding(20.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            // Header with icon and title
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Icon(
                    imageVector = Icons.Default.HealthAndSafety,
                    contentDescription = null,
                    modifier = Modifier.size(32.dp),
                    tint =
                    if (isHealthConnectAvailable && isEnabled && hasPermissions) {
                        MaterialTheme.colorScheme.primary
                    } else {
                        MaterialTheme.colorScheme.onSurfaceVariant
                    },
                )

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

                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = "Health Connect",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )

                    Text(
                        text =
                        when {
                            isLoading -> "Checking availability..."
                            !isCompatible -> "API Issue"
                            !isHealthConnectAvailable -> "Not available"
                            isEnabled && hasPermissions -> "Connected"
                            isEnabled && !hasPermissions -> "Needs permissions"
                            else -> "Disabled"
                        },
                        style = MaterialTheme.typography.bodySmall,
                        color =
                        when {
                            isLoading ->
                                MaterialTheme.colorScheme.onSurfaceVariant.copy(
                                    alpha = 0.7f,
                                )

                            !isCompatible -> MaterialTheme.colorScheme.error
                            !isHealthConnectAvailable -> MaterialTheme.colorScheme.error
                            isEnabled && hasPermissions ->
                                MaterialTheme.colorScheme.primary

                            isEnabled && !hasPermissions ->
                                MaterialTheme.colorScheme.tertiary

                            else ->
                                MaterialTheme.colorScheme.onSurfaceVariant.copy(
                                    alpha = 0.7f,
                                )
                        },
                    )
                }

                // Main toggle switch
                Switch(
                    checked = isEnabled,
                    onCheckedChange = { enabled ->
                        coroutineScope.launch {
                            if (enabled && isHealthConnectAvailable) {
                                healthConnectManager.setEnabled(true)
                                try {
                                    val permissionSet =
                                        healthConnectManager.getRequiredPermissions()
                                    if (permissionSet.isNotEmpty()) {
                                        permissionLauncher.launch(permissionSet)
                                    }
                                } catch (e: Exception) {
                                    errorMessage = "Error requesting permissions: ${e.message}"
                                }
                            } else {
                                healthConnectManager.setEnabled(false)
                                errorMessage = null
                            }
                        }
                    },
                    enabled = isHealthConnectAvailable && !isLoading && isCompatible,
                )
            }

            if (isEnabled) {
                Spacer(modifier = Modifier.height(16.dp))

                Text(
                    text = "Climbing sessions will be automatically added to Health Connect when completed.",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.fillMaxWidth(),
                )

                if (!hasPermissions) {
                    Spacer(modifier = Modifier.height(12.dp))
                    Card(
                        shape = RoundedCornerShape(12.dp),
                        colors =
                        CardDefaults.cardColors(
                            containerColor =
                            MaterialTheme.colorScheme.errorContainer.copy(
                                alpha = 0.3f,
                            ),
                        ),
                    ) {
                        Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                Icon(
                                    imageVector = Icons.Default.Warning,
                                    contentDescription = null,
                                    modifier = Modifier.size(20.dp),
                                    tint = MaterialTheme.colorScheme.error,
                                )

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

                                Text(
                                    text = "Permissions needed",
                                    style = MaterialTheme.typography.bodyMedium,
                                    fontWeight = FontWeight.Medium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                )
                            }

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

                            Text(
                                text =
                                "Grant Health Connect permissions to sync your climbing sessions",
                                style = MaterialTheme.typography.bodySmall,
                                color =
                                MaterialTheme.colorScheme.onSurfaceVariant.copy(
                                    alpha = 0.8f,
                                ),
                            )

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

                            OutlinedButton(
                                onClick = {
                                    coroutineScope.launch {
                                        try {
                                            val permissionSet =
                                                healthConnectManager
                                                    .getRequiredPermissions()
                                            if (permissionSet.isNotEmpty()) {
                                                permissionLauncher.launch(permissionSet)
                                            }
                                        } catch (e: Exception) {
                                            errorMessage =
                                                "Error requesting permissions: ${e.message}"
                                        }
                                    }
                                },
                                modifier = Modifier.fillMaxWidth(),
                            ) { Text("Grant Permissions") }
                        }
                    }
                } else {
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text =
                        "Sync your climbing sessions to Samsung Health, Google Fit, and other fitness apps through Health Connect.",
                        style = MaterialTheme.typography.bodyMedium,
                        textAlign = TextAlign.Center,
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f),
                    )
                }
                errorMessage?.let { error ->
                    Spacer(modifier = Modifier.height(12.dp))

                    Card(
                        shape = RoundedCornerShape(8.dp),
                        colors =
                        CardDefaults.cardColors(
                            containerColor =
                            MaterialTheme.colorScheme.errorContainer.copy(
                                alpha = 0.5f,
                            ),
                        ),
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth().padding(12.dp),
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            Icon(
                                imageVector = Icons.Default.Warning,
                                contentDescription = null,
                                modifier = Modifier.size(16.dp),
                                tint = MaterialTheme.colorScheme.error,
                            )

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

                            Text(
                                text = error,
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onErrorContainer,
                            )
                        }
                    }
                }
            }
        }
    }
}
