package com.omixlab.lckcontrol.ui.plans

import androidx.compose.foundation.layout.Arrangement
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.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuAnchorType
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.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.omixlab.lckcontrol.shared.LinkedAccount
import com.omixlab.lckcontrol.ui.components.GameInfoRow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreatePlanScreen(
    onPlanCreated: (String) -> Unit,
    onBack: () -> Unit,
    viewModel: CreatePlanViewModel = hiltViewModel(),
) {
    val isEditMode = viewModel.isEditMode
    val planName by viewModel.planName.collectAsStateWithLifecycle()
    val executionMode by viewModel.executionMode.collectAsStateWithLifecycle()
    val gameId by viewModel.gameId.collectAsStateWithLifecycle()
    val connectedClients by viewModel.connectedClients.collectAsStateWithLifecycle()
    val destinations by viewModel.destinations.collectAsStateWithLifecycle()
    val linkedAccounts by viewModel.linkedAccounts.collectAsStateWithLifecycle()
    val isCreating by viewModel.isCreating.collectAsStateWithLifecycle()
    val error by viewModel.error.collectAsStateWithLifecycle()
    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(error) {
        error?.let {
            snackbarHostState.showSnackbar(it)
            viewModel.clearError()
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(if (isEditMode) "Edit Stream Plan" else "Create Stream Plan") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
            )
        },
        snackbarHost = { SnackbarHost(snackbarHostState) },
    ) { padding ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(horizontal = 16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            item {
                Spacer(Modifier.height(8.dp))
                OutlinedTextField(
                    value = planName,
                    onValueChange = viewModel::setPlanName,
                    label = { Text("Plan Name") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                )
            }

            item {
                Spacer(Modifier.height(8.dp))
                Text("Execution Mode", style = MaterialTheme.typography.titleMedium)
                Spacer(Modifier.height(4.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    FilterChip(
                        selected = executionMode == "IN_GAME",
                        onClick = { viewModel.setExecutionMode("IN_GAME") },
                        label = { Text("In-Game") },
                    )
                    FilterChip(
                        selected = executionMode == "APP_STREAMING",
                        onClick = { viewModel.setExecutionMode("APP_STREAMING") },
                        label = { Text("App Streaming") },
                    )
                }
                if (executionMode == "APP_STREAMING") {
                    Spacer(Modifier.height(4.dp))
                    Text(
                        "The app encodes and streams. Stream keys stay secure.",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }

            item {
                Text("Game", style = MaterialTheme.typography.titleMedium)
                Spacer(Modifier.height(4.dp))
                if (gameId.isNotBlank()) {
                    GameInfoRow(
                        packageName = gameId,
                        gameInfoProvider = viewModel.gameInfoProvider,
                        showPackageName = true,
                    )
                } else if (connectedClients.isEmpty()) {
                    Text(
                        "No game connected",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }

            item {
                Spacer(Modifier.height(8.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Text("Destinations", style = MaterialTheme.typography.titleMedium)
                    OutlinedButton(onClick = viewModel::addDestination) {
                        Icon(Icons.Default.Add, contentDescription = null)
                        Spacer(Modifier.padding(4.dp))
                        Text("Add")
                    }
                }
            }

            itemsIndexed(destinations) { index, dest ->
                DestinationCard(
                    destination = dest,
                    linkedAccounts = linkedAccounts,
                    onUpdate = { viewModel.updateDestination(index, it) },
                    onRemove = { viewModel.removeDestination(index) },
                )
            }

            item {
                Spacer(Modifier.height(16.dp))
                Button(
                    onClick = { viewModel.savePlan(onPlanCreated) },
                    modifier = Modifier.fillMaxWidth(),
                    enabled = !isCreating,
                ) {
                    Text(
                        when {
                            isCreating && isEditMode -> "Saving..."
                            isCreating -> "Creating..."
                            isEditMode -> "Save"
                            else -> "Create Plan"
                        }
                    )
                }
                Spacer(Modifier.height(16.dp))
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun DestinationCard(
    destination: DestinationInput,
    linkedAccounts: List<LinkedAccount>,
    onUpdate: (DestinationInput) -> Unit,
    onRemove: () -> Unit,
) {
    var accountExpanded by remember { mutableStateOf(false) }
    var privacyExpanded by remember { mutableStateOf(false) }

    ElevatedCard(modifier = Modifier.fillMaxWidth()) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
            ) {
                Text("Destination", style = MaterialTheme.typography.labelLarge)
                IconButton(onClick = onRemove) {
                    Icon(Icons.Default.Delete, contentDescription = "Remove")
                }
            }

            // Account picker (shows linked accounts + "Custom RTMP" option)
            ExposedDropdownMenuBox(
                expanded = accountExpanded,
                onExpandedChange = { accountExpanded = it },
            ) {
                OutlinedTextField(
                    value = destination.linkedAccountLabel.ifBlank { if (destination.isCustom) "Custom RTMP" else "" },
                    onValueChange = {},
                    readOnly = true,
                    label = { Text("Account") },
                    trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(accountExpanded) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .menuAnchor(MenuAnchorType.PrimaryNotEditable),
                )
                ExposedDropdownMenu(
                    expanded = accountExpanded,
                    onDismissRequest = { accountExpanded = false },
                ) {
                    DropdownMenuItem(
                        text = { Text("Custom RTMP") },
                        onClick = {
                            onUpdate(destination.copy(
                                isCustom = true,
                                linkedAccountId = "",
                                linkedAccountLabel = "",
                            ))
                            accountExpanded = false
                        },
                    )
                    linkedAccounts.forEach { account ->
                        val label = "${account.serviceId} - ${account.displayName}"
                        DropdownMenuItem(
                            text = { Text(label) },
                            onClick = {
                                if (account.serviceId == "CUSTOM_RTMP") {
                                    onUpdate(destination.copy(
                                        isCustom = true,
                                        linkedAccountId = account.id,
                                        linkedAccountLabel = label,
                                        rtmpUrl = account.rtmpUrl ?: "",
                                        streamKey = account.streamKey ?: "",
                                    ))
                                } else {
                                    onUpdate(destination.copy(
                                        isCustom = false,
                                        linkedAccountId = account.id,
                                        linkedAccountLabel = label,
                                        rtmpUrl = "",
                                        streamKey = "",
                                    ))
                                }
                                accountExpanded = false
                            },
                        )
                    }
                }
            }

            if (destination.isCustom) {
                OutlinedTextField(
                    value = destination.rtmpUrl,
                    onValueChange = { onUpdate(destination.copy(rtmpUrl = it)) },
                    label = { Text("RTMP URL") },
                    placeholder = { Text("rtmp://192.168.1.60:1935/live") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                )
                OutlinedTextField(
                    value = destination.streamKey,
                    onValueChange = { onUpdate(destination.copy(streamKey = it)) },
                    label = { Text("Stream Key") },
                    placeholder = { Text("test") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                )
            }

            OutlinedTextField(
                value = destination.title,
                onValueChange = { onUpdate(destination.copy(title = it)) },
                label = { Text("Stream Title") },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true,
            )

            if (!destination.isCustom) {
                OutlinedTextField(
                    value = destination.description,
                    onValueChange = { onUpdate(destination.copy(description = it)) },
                    label = { Text("Description") },
                    modifier = Modifier.fillMaxWidth(),
                    minLines = 2,
                )

                // Privacy status
                ExposedDropdownMenuBox(
                    expanded = privacyExpanded,
                    onExpandedChange = { privacyExpanded = it },
                ) {
                    OutlinedTextField(
                        value = destination.privacyStatus,
                        onValueChange = {},
                        readOnly = true,
                        label = { Text("Privacy") },
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(privacyExpanded) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(MenuAnchorType.PrimaryNotEditable),
                    )
                    ExposedDropdownMenu(
                        expanded = privacyExpanded,
                        onDismissRequest = { privacyExpanded = false },
                    ) {
                        listOf("public", "unlisted", "private").forEach { status ->
                            DropdownMenuItem(
                                text = { Text(status) },
                                onClick = {
                                    onUpdate(destination.copy(privacyStatus = status))
                                    privacyExpanded = false
                                },
                            )
                        }
                    }
                }

                OutlinedTextField(
                    value = destination.tags,
                    onValueChange = { onUpdate(destination.copy(tags = it)) },
                    label = { Text("Tags (comma-separated)") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                )
            }
        }
    }
}
