package com.omixlab.lckcontrol.ui.accounts

import android.app.Activity
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.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.LinkOff
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
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.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AccountsScreen(
    viewModel: AccountsViewModel = hiltViewModel(),
) {
    val accounts by viewModel.accounts.collectAsStateWithLifecycle()
    val linkError by viewModel.linkError.collectAsStateWithLifecycle()
    val showDialog by viewModel.showCustomRtmpDialog.collectAsStateWithLifecycle()
    val customName by viewModel.customRtmpName.collectAsStateWithLifecycle()
    val customUrl by viewModel.customRtmpUrl.collectAsStateWithLifecycle()
    val customKey by viewModel.customRtmpKey.collectAsStateWithLifecycle()
    val isCreating by viewModel.isCreatingCustomRtmp.collectAsStateWithLifecycle()
    val snackbarHostState = remember { SnackbarHostState() }
    val context = LocalContext.current

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

    if (showDialog) {
        AlertDialog(
            onDismissRequest = { viewModel.dismissCustomRtmpDialog() },
            title = { Text("Add Custom RTMP") },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    OutlinedTextField(
                        value = customName,
                        onValueChange = viewModel::setCustomRtmpName,
                        label = { Text("Name") },
                        placeholder = { Text("Local Test Server") },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                    )
                    OutlinedTextField(
                        value = customUrl,
                        onValueChange = viewModel::setCustomRtmpUrl,
                        label = { Text("RTMP URL") },
                        placeholder = { Text("rtmp://192.168.1.60:1935/live") },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                    )
                    OutlinedTextField(
                        value = customKey,
                        onValueChange = viewModel::setCustomRtmpKey,
                        label = { Text("Stream Key") },
                        placeholder = { Text("test") },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                    )
                }
            },
            confirmButton = {
                TextButton(
                    onClick = { viewModel.createCustomRtmpAccount() },
                    enabled = !isCreating,
                ) {
                    Text(if (isCreating) "Saving..." else "Save")
                }
            },
            dismissButton = {
                TextButton(onClick = { viewModel.dismissCustomRtmpDialog() }) {
                    Text("Cancel")
                }
            },
        )
    }

    Scaffold(
        topBar = {
            TopAppBar(title = { Text("Linked Accounts") })
        },
        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)) }

            items(accounts, key = { it.id }) { account ->
                ElevatedCard(modifier = Modifier.fillMaxWidth()) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                            Text(account.displayName, style = MaterialTheme.typography.titleSmall)
                            Text(
                                if (account.serviceId == "CUSTOM_RTMP") account.rtmpUrl ?: "Custom RTMP"
                                else account.serviceId,
                                style = MaterialTheme.typography.bodySmall,
                            )
                        }
                        Switch(
                            checked = account.isEnabled,
                            onCheckedChange = { viewModel.toggleAccountEnabled(account.id, it) },
                        )
                        IconButton(onClick = { viewModel.unlinkAccount(account.id) }) {
                            Icon(Icons.Default.LinkOff, contentDescription = "Unlink")
                        }
                    }
                }
            }

            // Always show link buttons — users can add multiple accounts per service
            item {
                Spacer(Modifier.height(8.dp))
                Text("Add Account", style = MaterialTheme.typography.titleMedium)
                Spacer(Modifier.height(4.dp))
            }

            items(ALL_PROVIDERS, key = { it.serviceId }) { provider ->
                OutlinedButton(
                    onClick = {
                        val activity = context as? Activity ?: return@OutlinedButton
                        viewModel.linkAccount(activity, provider.serviceId)
                    },
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Icon(Icons.Default.Add, contentDescription = null)
                    Spacer(Modifier.padding(4.dp))
                    Text("Link ${provider.displayName}")
                }
            }

            item {
                OutlinedButton(
                    onClick = { viewModel.showCustomRtmpDialog() },
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Icon(Icons.Default.Add, contentDescription = null)
                    Spacer(Modifier.padding(4.dp))
                    Text("Add Custom RTMP")
                }
            }

            item { Spacer(Modifier.height(16.dp)) }
        }
    }
}
