package com.seven.ikar.kotlin.feature.bots

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.SmartToy
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
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.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.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.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BotEditorScreen(
    state: BotEditorUiState,
    onBackClick: () -> Unit,
    onDisplayNameChanged: (String) -> Unit,
    onUsernameChanged: (String) -> Unit,
    onAboutChanged: (String) -> Unit,
    onCommandsChanged: (String) -> Unit,
    onEnabledChanged: (Boolean) -> Unit,
    onSaveClick: () -> Unit,
    onRegenerateTokenClick: () -> Unit,
    onDeleteBotClick: () -> Unit,
    onOpenChatClick: () -> Unit
) {
    val clipboardManager = LocalClipboardManager.current
    var showDeleteConfirmation by remember { mutableStateOf(false) }
    if (showDeleteConfirmation) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirmation = false },
            title = { Text("Удалить бота?") },
            text = { Text("Бот будет удалён из управления, его токен и команды перестанут работать. История сообщений останется в чатах.") },
            confirmButton = {
                TextButton(
                    onClick = {
                        showDeleteConfirmation = false
                        onDeleteBotClick()
                    },
                    colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)
                ) {
                    Text("Удалить")
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteConfirmation = false }) {
                    Text("Отмена")
                }
            }
        )
    }
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(if (state.isExistingBot) "Редактор бота" else "Новый бот") },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(Icons.AutoMirrored.Outlined.ArrowBack, contentDescription = "Назад")
                    }
                }
            )
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(14.dp)
        ) {
            state.errorMessage?.let {
                Text(it, color = MaterialTheme.colorScheme.error)
            }
            state.infoMessage?.let {
                Text(it, color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold)
            }

            Card(modifier = Modifier.fillMaxWidth()) {
                Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    Icon(Icons.Outlined.SmartToy, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
                    OutlinedTextField(
                        value = state.displayName,
                        onValueChange = onDisplayNameChanged,
                        modifier = Modifier.fillMaxWidth(),
                        label = { Text("Отображаемое имя") }
                    )
                    OutlinedTextField(
                        value = state.username,
                        onValueChange = onUsernameChanged,
                        modifier = Modifier.fillMaxWidth(),
                        enabled = !state.isExistingBot,
                        label = { Text("Имя пользователя") },
                        prefix = { Text("@") }
                    )
                    OutlinedTextField(
                        value = state.about,
                        onValueChange = onAboutChanged,
                        modifier = Modifier.fillMaxWidth(),
                        minLines = 3,
                        label = { Text("О боте") }
                    )
                    androidx.compose.foundation.layout.Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text("Бот активен")
                        Switch(checked = state.isEnabled, onCheckedChange = onEnabledChanged)
                    }
                    OutlinedTextField(
                        value = state.commandsText,
                        onValueChange = onCommandsChanged,
                        modifier = Modifier.fillMaxWidth(),
                        minLines = 5,
                        label = { Text("Команды") },
                        supportingText = { Text("Формат: /help - описание") }
                    )
                }
            }

            Button(onClick = onSaveClick, enabled = !state.isSaving && !state.isDeleting, modifier = Modifier.fillMaxWidth()) {
                Text(if (state.isSaving) "Сохранение..." else "Сохранить")
            }

            if (state.isExistingBot) {
                OutlinedButton(
                    onClick = onRegenerateTokenClick,
                    enabled = !state.isDeleting && !state.isSaving,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text("Сгенерировать новый токен")
                }
                OutlinedButton(
                    onClick = onOpenChatClick,
                    enabled = !state.isDeleting && !state.isSaving,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text("Открыть чат с ботом")
                }
                OutlinedButton(
                    onClick = { showDeleteConfirmation = true },
                    enabled = !state.isDeleting && !state.isSaving,
                    modifier = Modifier.fillMaxWidth(),
                    colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error)
                ) {
                    Icon(Icons.Outlined.Delete, contentDescription = null)
                    Text(if (state.isDeleting) "Удаление..." else "Удалить бота")
                }
            }

            if (state.latestToken.isNotBlank()) {
                Card(modifier = Modifier.fillMaxWidth()) {
                    Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        Text("Текущий токен", fontWeight = FontWeight.SemiBold)
                        Text(state.latestToken, style = MaterialTheme.typography.bodySmall)
                        OutlinedButton(
                            onClick = { clipboardManager.setText(AnnotatedString(state.latestToken)) },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Icon(Icons.Outlined.ContentCopy, contentDescription = null)
                            Text("Скопировать токен")
                        }
                    }
                }
            }
        }
    }
}
