package com.example.smarthome.ui

import android.content.Context
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

data class Automation(
    val id: String = java.util.UUID.randomUUID().toString(),
    val name: String,
    val trigger: String,
    val action: String,
    var isEnabled: Boolean = true
)

@Composable
fun AutomationScreen() {
    val context = LocalContext.current
    val prefs = remember { context.getSharedPreferences("automations", Context.MODE_PRIVATE) }
    val gson = remember { Gson() }
    
    // 加载保存的自动化列表
    val savedAutomations = remember {
        val json = prefs.getString("automation_list", null)
        if (json != null) {
            val type = object : TypeToken<List<Automation>>() {}.type
            gson.fromJson<List<Automation>>(json, type)
        } else {
            listOf(
                Automation(name = "早安自动化", trigger = "每天 7:00", action = "开启卧室灯光，播放音乐", isEnabled = true),
                Automation(name = "离家自动化", trigger = "检测到离家", action = "关闭所有灯光和空调，开启安防", isEnabled = true),
                Automation(name = "回家自动化", trigger = "检测到回家", action = "开启客厅灯光和空调", isEnabled = true),
                Automation(name = "晚安自动化", trigger = "每天 23:00", action = "关闭所有灯光，空调调至睡眠模式", isEnabled = false),
                Automation(name = "温度控制", trigger = "温度 > 28°C", action = "自动开启空调", isEnabled = true),
                Automation(name = "安全警报", trigger = "检测到异常", action = "发送通知并开启警报", isEnabled = true)
            )
        }
    }
    
    var automations by remember { mutableStateOf(savedAutomations) }
    var showAddDialog by remember { mutableStateOf(false) }
    
    // 保存到SharedPreferences
    fun saveAutomations() {
        val json = gson.toJson(automations)
        prefs.edit().putString("automation_list", json).apply()
    }
    
    fun toggleAutomation(automation: Automation) {
        automations = automations.map {
            if (it.id == automation.id) it.copy(isEnabled = !it.isEnabled) else it
        }
        saveAutomations()
    }
    
    fun addAutomation(name: String, trigger: String, action: String) {
        automations = automations + Automation(name = name, trigger = trigger, action = action)
        saveAutomations()
    }
    
    fun deleteAutomation(automation: Automation) {
        automations = automations.filter { it.id != automation.id }
        saveAutomations()
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column {
                Text(
                    text = "自动化",
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Bold,
                    color = Color.White
                )
                Text(
                    text = "${automations.count { it.isEnabled }} 个自动化运行中",
                    fontSize = 14.sp,
                    color = Color(0xFF9AA0A6),
                    modifier = Modifier.padding(top = 4.dp)
                )
            }
            
            Box(
                modifier = Modifier
                    .height(40.dp)
                    .clip(RoundedCornerShape(20.dp))
                    .background(
                        Brush.linearGradient(
                            listOf(Color(0xFFA9F0FF), Color(0xFFB89CFF))
                        )
                    )
                    .clickable(
                        indication = null,
                        interactionSource = remember { MutableInteractionSource() }
                    ) { showAddDialog = true }
                    .padding(horizontal = 20.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "+ 新建",
                    color = Color.Black,
                    fontWeight = FontWeight.Medium,
                    fontSize = 14.sp
                )
            }
        }
        
        Spacer(modifier = Modifier.height(24.dp))
        
        LazyColumn(
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            items(automations) { automation ->
                AutomationCard(
                    automation = automation,
                    onToggle = { toggleAutomation(automation) },
                    onDelete = { deleteAutomation(automation) }
                )
            }
        }
    }
    
    if (showAddDialog) {
        AddAutomationDialog(
            onDismiss = { showAddDialog = false },
            onConfirm = { name, trigger, action ->
                addAutomation(name, trigger, action)
                showAddDialog = false
            }
        )
    }
}

@Composable
fun AutomationCard(automation: Automation, onToggle: () -> Unit, onDelete: () -> Unit) {
    var showDeleteConfirm by remember { mutableStateOf(false) }
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(20.dp))
            .background(Color(0x50121212))
            .padding(16.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = automation.name,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color.White
                )
                Spacer(modifier = Modifier.height(8.dp))
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(
                        modifier = Modifier
                            .clip(RoundedCornerShape(8.dp))
                            .background(Color(0x33A9F0FF))
                            .padding(horizontal = 8.dp, vertical = 4.dp)
                    ) {
                        Text(
                            text = automation.trigger,
                            fontSize = 11.sp,
                            color = Color(0xFFA9F0FF)
                        )
                    }
                    Text(text = "→", color = Color(0xFF9AA0A6), fontSize = 12.sp)
                    Text(
                        text = automation.action,
                        fontSize = 12.sp,
                        color = Color(0xFF9AA0A6)
                    )
                }
            }
            
            Box(
                modifier = Modifier
                    .size(52.dp, 30.dp)
                    .clip(RoundedCornerShape(15.dp))
                    .background(
                        if (automation.isEnabled) {
                            Brush.linearGradient(
                                listOf(Color(0xFFA9F0FF), Color(0xFFB89CFF))
                            )
                        } else {
                            Brush.linearGradient(
                                listOf(Color(0x33222222), Color(0x33222222))
                            )
                        }
                    )
                    .clickable(
                        indication = null,
                        interactionSource = remember { MutableInteractionSource() }
                    ) { onToggle() }
                    .padding(3.dp)
            ) {
                Box(
                    modifier = Modifier
                        .size(24.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(Color.White)
                        .align(if (automation.isEnabled) Alignment.CenterEnd else Alignment.CenterStart)
                )
            }
        }
    }
}

@Composable
fun AddAutomationDialog(
    onDismiss: () -> Unit,
    onConfirm: (String, String, String) -> Unit
) {
    var name by remember { mutableStateOf("") }
    var trigger by remember { mutableStateOf("") }
    var action by remember { mutableStateOf("") }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0x80000000))
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() }
            ) { onDismiss() },
        contentAlignment = Alignment.Center
    ) {
        Box(
            modifier = Modifier
                .width(400.dp)
                .clip(RoundedCornerShape(24.dp))
                .background(Color(0xFF1E1E1E))
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }
                ) { /* 阻止点击穿透 */ }
                .padding(24.dp)
        ) {
            Column(
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Text(
                    text = "新建自动化",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White
                )
                
                TextField(
                    value = name,
                    onValueChange = { name = it },
                    placeholder = { Text("自动化名称", color = Color(0xFF9AA0A6)) },
                    modifier = Modifier.fillMaxWidth(),
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color(0x28FFFFFF),
                        unfocusedContainerColor = Color(0x28FFFFFF),
                        focusedTextColor = Color.White,
                        unfocusedTextColor = Color.White,
                        cursorColor = Color(0xFFA9F0FF),
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent
                    ),
                    shape = RoundedCornerShape(12.dp),
                    singleLine = true
                )
                
                TextField(
                    value = trigger,
                    onValueChange = { trigger = it },
                    placeholder = { Text("触发条件（如：每天 7:00）", color = Color(0xFF9AA0A6)) },
                    modifier = Modifier.fillMaxWidth(),
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color(0x28FFFFFF),
                        unfocusedContainerColor = Color(0x28FFFFFF),
                        focusedTextColor = Color.White,
                        unfocusedTextColor = Color.White,
                        cursorColor = Color(0xFFA9F0FF),
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent
                    ),
                    shape = RoundedCornerShape(12.dp),
                    singleLine = true
                )
                
                TextField(
                    value = action,
                    onValueChange = { action = it },
                    placeholder = { Text("执行动作", color = Color(0xFF9AA0A6)) },
                    modifier = Modifier.fillMaxWidth(),
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color(0x28FFFFFF),
                        unfocusedContainerColor = Color(0x28FFFFFF),
                        focusedTextColor = Color.White,
                        unfocusedTextColor = Color.White,
                        cursorColor = Color(0xFFA9F0FF),
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent
                    ),
                    shape = RoundedCornerShape(12.dp),
                    maxLines = 2
                )
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .height(48.dp)
                            .clip(RoundedCornerShape(12.dp))
                            .background(Color(0x28FFFFFF))
                            .clickable(
                                indication = null,
                                interactionSource = remember { MutableInteractionSource() }
                            ) { onDismiss() },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "取消",
                            color = Color(0xFFB0B0B0),
                            fontWeight = FontWeight.Medium
                        )
                    }
                    
                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .height(48.dp)
                            .clip(RoundedCornerShape(12.dp))
                            .background(
                                Brush.linearGradient(
                                    listOf(Color(0xFFA9F0FF), Color(0xFFB89CFF))
                                )
                            )
                            .clickable(
                                indication = null,
                                interactionSource = remember { MutableInteractionSource() },
                                enabled = name.isNotBlank() && trigger.isNotBlank() && action.isNotBlank()
                            ) {
                                if (name.isNotBlank() && trigger.isNotBlank() && action.isNotBlank()) {
                                    onConfirm(name.trim(), trigger.trim(), action.trim())
                                }
                            }
                            .then(
                                if (name.isNotBlank() && trigger.isNotBlank() && action.isNotBlank()) {
                                    Modifier
                                } else {
                                    Modifier.alpha(0.5f)
                                }
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "确定",
                            color = Color.Black,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
        }
    }
}
