package com.openclaw.alfred.alarm

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Alarm
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.lifecycleScope
import com.openclaw.alfred.BuildConfig
import com.openclaw.alfred.ui.theme.AlfredTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
 * Full-screen alarm activity that displays when an alarm fires.
 * Requires user to dismiss the alarm before continuing.
 */
class AlarmActivity : ComponentActivity() {
    
    private val httpClient = OkHttpClient()
    
    companion object {
        const val EXTRA_ALARM_ID = "alarm_id"
        const val EXTRA_TITLE = "title"
        const val EXTRA_MESSAGE = "message"
        const val EXTRA_TIMESTAMP = "timestamp"
        private const val TAG = "AlarmActivity"
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // Get alarm details from intent
        val alarmId = intent.getStringExtra(EXTRA_ALARM_ID) ?: "unknown"
        val title = intent.getStringExtra(EXTRA_TITLE) ?: "Alarm"
        val message = intent.getStringExtra(EXTRA_MESSAGE) ?: "Alarm!"
        val timestamp = intent.getLongExtra(EXTRA_TIMESTAMP, System.currentTimeMillis())
        
        // Show on lock screen and turn screen on (API 27+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true)
            setTurnScreenOn(true)
        }
        
        // Additional flags for lock screen display
        window.addFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
        )
        
        Log.d("AlarmActivity", "AlarmActivity created: id=$alarmId title=$title message=$message")
        
        setContent {
            AlfredTheme {
                AlarmScreen(
                    title = title,
                    message = message,
                    onDismiss = {
                        Log.d(TAG, "Dismiss button clicked for alarm: $alarmId")
                        
                        // Stop ALL active alarms (handles duplicates from WebSocket + FCM)
                        val alarmManager = AlarmManager.getInstance(this)
                        Log.d(TAG, "Calling dismissAll() to clear all active alarms")
                        alarmManager.dismissAll()
                        
                        // Broadcast dismissal to all devices via proxy
                        broadcastDismissal(alarmId)
                        
                        Log.d(TAG, "Finishing activity")
                        // Close activity
                        finish()
                    }
                )
            }
        }
    }
    
    /**
     * Broadcast alarm dismissal to all user's devices via proxy.
     */
    private fun broadcastDismissal(alarmId: String) {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val userId = getUserId()
                val proxyUrl = getProxyUrl()
                
                if (userId == null) {
                    Log.w(TAG, "Cannot broadcast dismissal: userId not available")
                    return@launch
                }
                
                Log.d(TAG, "Broadcasting dismissal for alarm $alarmId to user $userId")
                
                val json = JSONObject().apply {
                    put("userId", userId)
                    put("alarmId", alarmId)
                }
                
                val body = json.toString().toRequestBody("application/json".toMediaType())
                val request = Request.Builder()
                    .url("$proxyUrl/api/alarm/dismiss")
                    .post(body)
                    .build()
                
                httpClient.newCall(request).execute().use { response ->
                    if (response.isSuccessful) {
                        Log.d(TAG, "Dismissal broadcast successful")
                    } else {
                        Log.e(TAG, "Dismissal broadcast failed: ${response.code}")
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "Failed to broadcast dismissal", e)
                // Local dismissal still worked, just log the error
            }
        }
    }
    
    /**
     * Get userId from SharedPreferences.
     */
    private fun getUserId(): String? {
        val prefs = getSharedPreferences("alfred_auth", MODE_PRIVATE)
        return prefs.getString("user_id", null)
    }
    
    /**
     * Get proxy URL from BuildConfig.
     */
    private fun getProxyUrl(): String {
        return BuildConfig.GATEWAY_URL.replace("wss://", "https://").replace("ws://", "http://")
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AlarmScreen(
    title: String,
    message: String,
    onDismiss: () -> Unit
) {
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("⏰ $title") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer,
                    titleContentColor = MaterialTheme.colorScheme.onErrorContainer
                )
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(24.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            // Large alarm icon
            Icon(
                imageVector = Icons.Default.Alarm,
                contentDescription = "Alarm",
                modifier = Modifier.size(120.dp),
                tint = MaterialTheme.colorScheme.error
            )
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // Alarm message
            Text(
                text = message,
                style = MaterialTheme.typography.headlineMedium,
                textAlign = TextAlign.Center,
                fontSize = 28.sp
            )
            
            Spacer(modifier = Modifier.height(48.dp))
            
            // Large dismiss button
            Button(
                onClick = onDismiss,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(72.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.error
                )
            ) {
                Text(
                    text = "DISMISS ALARM",
                    style = MaterialTheme.typography.titleLarge,
                    fontSize = 24.sp
                )
            }
        }
    }
}
