@file:Suppress("AssignedValueIsNeverRead")

package eu.gaudian.translator.view.settings

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import androidx.test.core.app.ApplicationProvider
import eu.gaudian.translator.R
import eu.gaudian.translator.model.LanguageModel
import eu.gaudian.translator.model.communication.ApiProvider
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.ApiModelDropDown
import eu.gaudian.translator.view.composable.AppAlertDialog
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppDialog
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppOutlinedTextField
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppTabLayout
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.ClickableText
import eu.gaudian.translator.view.composable.PrimaryButton
import eu.gaudian.translator.view.composable.SecondaryButton
import eu.gaudian.translator.view.composable.TabItem
import eu.gaudian.translator.view.hints.HintDefinition
import eu.gaudian.translator.viewmodel.ApiKeyManagementState
import eu.gaudian.translator.viewmodel.ApiViewModel
import eu.gaudian.translator.viewmodel.ProviderState

@Composable
private fun getApiTabs(): List<TabItem> {
    return listOf(
        ApiTab(stringResource(R.string.label_providers), AppIcons.Storage),
        ApiTab(stringResource(R.string.label_tasks), AppIcons.ModelTraining)
    )
}

private data class ApiTab(override val title: String, override val icon: ImageVector) :
    TabItem

@Composable
fun ApiKeyScreen(navController: NavController) {
    val activity = LocalContext.current.findActivity()
    val apiViewModel : ApiViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val state by apiViewModel.apiKeyManagementState.collectAsStateWithLifecycle()

    val allModels by apiViewModel.allModels.collectAsStateWithLifecycle()
    val allProviders by apiViewModel.allProviders.collectAsStateWithLifecycle()
    val translationModel by apiViewModel.translationModel.collectAsStateWithLifecycle()
    val exerciseModel by apiViewModel.exerciseModel.collectAsStateWithLifecycle()
    val vocabularyModel by apiViewModel.vocabularyModel.collectAsStateWithLifecycle()
    val dictionaryModel by apiViewModel.dictionaryModel.collectAsStateWithLifecycle()

    val apiTabs = getApiTabs()
    var selectedTab by remember { mutableStateOf(apiTabs[0]) }

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.label_ai_configuration),
                onNavigateBack = { navController.popBackStack() },
                hintContent =  HintDefinition.API_KEY.hint()
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .imePadding()
        ) {
            HandleApiManagementDialogs(state)

            // Tab Layout
            AppTabLayout(
                tabs = apiTabs,
                selectedTab = selectedTab,
                onTabSelected = { selectedTab = it },
            )

            // Tab Content
            when (selectedTab) {
                apiTabs[0] -> ProvidersTabContent(
                    state = state,
                    allProviders = allProviders,
                    apiViewModel = apiViewModel,
                    navController = navController
                )
                apiTabs[1] -> TasksTabContent(
                    allModels = allModels.filter { model -> allProviders.any { it.key == model.providerKey && it.hasValidKey } },
                    allProviders = allProviders.filter { it.isCustom || it.hasValidKey },
                    translationModel = translationModel,
                    exerciseModel = exerciseModel,
                    vocabularyModel = vocabularyModel,
                    dictionaryModel = dictionaryModel,
                    apiViewModel = apiViewModel
                )
            }
        }
    }
}

@Composable
private fun ProvidersTabContent(
    state: ApiKeyManagementState,
    allProviders: List<ApiProvider>,
    apiViewModel: ApiViewModel,
    navController: NavController
) {
    var showDeleteProviderDialog by remember { mutableStateOf(false) }
    var showDeleteModelDialog by remember { mutableStateOf(false) }
    var providerToDelete by remember { mutableStateOf<ApiProvider?>(null) }
    var modelToDelete by remember { mutableStateOf<Pair<String, String>?>(null) } // providerKey to modelId
    var showDeleteKeyDialog by remember { mutableStateOf(false) }
    var providerToDeleteKey by remember { mutableStateOf<String?>(null) }

    val listState = rememberLazyListState()
    var focusedProviderKey by remember { mutableStateOf<String?>(null) }

    // 1. Stable Sort: Remember the sorted list to avoid re-sorting on every frame
    val sortedProviders = remember(state.providerStates) {
        state.providerStates.sortedWith(compareBy<ProviderState> { !it.provider.isCustom }
            .thenBy { !it.hasKey }
            .thenBy { it.provider.displayName.lowercase() })
    }

    // 2. Smart Scroll Logic: Scroll to the focused provider if its index changes
    var lastKnownIndex by remember { mutableIntStateOf(-1) }

    LaunchedEffect(sortedProviders, focusedProviderKey) {
        val key = focusedProviderKey ?: return@LaunchedEffect
        val newIndex = sortedProviders.indexOfFirst { it.provider.key == key }

        if (newIndex != -1 && newIndex != lastKnownIndex) {
            listState.animateScrollToItem(newIndex)
            lastKnownIndex = newIndex
        } else if (newIndex == -1) {
            lastKnownIndex = -1
        }
    }

    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        // Add Provider Button
        AppButton(
            onClick = { apiViewModel.startAddingProvider() },
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Icon(AppIcons.Add, contentDescription = null, modifier = Modifier.size(ButtonDefaults.IconSize))
            Spacer(Modifier.size(ButtonDefaults.IconSpacing))
            Text(stringResource(R.string.label_add_custom_provider))
        }

        // Provider List
        LazyColumn(
            state = listState,
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 16.dp),
            contentPadding = PaddingValues(vertical = 8.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            items(
                items = sortedProviders,
                // 3. Key: Ensure Compose tracks items by ID, not position
                key = { it.provider.key }
            ) { providerState ->

                val focusRequester = remember { FocusRequester() }

                // If this is the focused provider, request focus
                LaunchedEffect(focusedProviderKey) {
                    if (focusedProviderKey == providerState.provider.key) {
                        focusRequester.requestFocus()
                    }
                }

                ProviderCard(
                    providerState = providerState,
                    onApiKeyChanged = { newKey ->
                        apiViewModel.updateApiKeyForProvider(providerState.provider.key, newKey)
                        // Keep focus on this provider while typing
                        if (newKey.isNotBlank()) {
                            focusedProviderKey = providerState.provider.key
                        }
                    },
                    onSave = {
                        apiViewModel.saveApiKeyForProvider(providerState.provider.key)
                        // Ensure we track this provider as it moves in the list
                        focusedProviderKey = providerState.provider.key
                    },
                    onToggleEdit = {
                        apiViewModel.toggleEditModeForProvider(providerState.provider.key)
                    },
                    onAddModel = {
                        focusedProviderKey = providerState.provider.key
                        @Suppress("HardCodedStringLiteral")
                        navController.navigate(SettingsRoutes.ADD_MODEL.replace("{providerKey}", providerState.provider.key))
                    },
                    onEditModel = { modelId ->
                        focusedProviderKey = providerState.provider.key
                        apiViewModel.startEditingModel(providerState.provider.key, modelId)
                    },
                    onDeleteModel = { modelId ->
                        modelToDelete = Pair(providerState.provider.key, modelId)
                        showDeleteModelDialog = true
                    },
                    onEditProvider = { apiViewModel.startEditingProvider(providerState.provider.key) },
                    onDeleteProvider = {
                        providerToDelete = providerState.provider
                        showDeleteProviderDialog = true
                    },
                    onDeleteKey = {
                        providerToDeleteKey = providerState.provider.key
                        showDeleteKeyDialog = true
                    },
                    modifier = Modifier.focusRequester(focusRequester)
                )
            }

            // Danger zone
            @Suppress("HardCodedStringLiteral")
            item(key = "danger_zone") {
                AppButton(
                    onClick = { apiViewModel.showWipeAllConfirm() },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error,
                        contentColor = MaterialTheme.colorScheme.onError
                    )
                ) {
                    Icon(AppIcons.Delete, contentDescription = null, modifier = Modifier.size(ButtonDefaults.IconSize))
                    Spacer(Modifier.size(ButtonDefaults.IconSpacing))
                    Text(stringResource(R.string.text_delete_all_providers_and_models))
                }
            }
        }
    }

    // Delete Provider Confirmation Dialog
    if (showDeleteProviderDialog && providerToDelete != null) {
        AppAlertDialog(
            onDismissRequest = {
                showDeleteProviderDialog = false
                providerToDelete = null
            },
            icon = {
                Icon(
                    AppIcons.Warning,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.error
                )
            },
            title = { Text(stringResource(R.string.label_delete_provider)) },
            text = {
                Text(
                    stringResource(
                        R.string.text_dialog_delete_provider,
                        providerToDelete!!.displayName
                    ))
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        apiViewModel.deleteProvider(providerToDelete!!.key)
                        showDeleteProviderDialog = false
                        providerToDelete = null
                    },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text(stringResource(R.string.label_delete))
                }
            },
            dismissButton = {
                TextButton(onClick = {
                    showDeleteProviderDialog = false
                    providerToDelete = null
                }) {
                    Text(stringResource(R.string.label_cancel))
                }
            }
        )
    }

    // Delete Model Confirmation Dialog
    if (showDeleteModelDialog && modelToDelete != null) {
        val (providerKey, modelId) = modelToDelete!!
        val provider = allProviders.find { it.key == providerKey }
        val model = provider?.models?.find { it.modelId == modelId }

        AppAlertDialog(
            onDismissRequest = {
                showDeleteModelDialog = false
                modelToDelete = null
            },
            icon = {
                Icon(
                    AppIcons.Warning,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.error
                )
            },
            title = { Text(stringResource(R.string.label_delete_model)) },
            text = {
                Text(
                    stringResource(
                        R.string.text_dialog_delete_model,
                        model?.displayName ?: modelId,
                        provider?.displayName ?: providerKey
                    ))
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        apiViewModel.deleteModelFromProvider(providerKey, modelId)
                        showDeleteModelDialog = false
                        modelToDelete = null
                    },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text(stringResource(R.string.label_delete))
                }
            },
            dismissButton = {
                TextButton(onClick = {
                    showDeleteModelDialog = false
                    modelToDelete = null
                }) {
                    Text(stringResource(R.string.label_cancel))
                }
            }
        )
    }

    // Delete Key Confirmation Dialog
    if (showDeleteKeyDialog && providerToDeleteKey != null) {
        val provider = allProviders.find { it.key == providerToDeleteKey }

        AppAlertDialog(
            onDismissRequest = {
                showDeleteKeyDialog = false
                providerToDeleteKey = null
            },
            icon = {
                Icon(
                    AppIcons.Warning,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.error
                )
            },
            title = { Text(stringResource(R.string.label_delete_key)) },
            text = {
                Text(
                    stringResource(
                        R.string.text_dialog_delete_key,
                        provider?.displayName ?: providerToDeleteKey!!
                    ))
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        apiViewModel.deleteApiKeyForProvider(providerToDeleteKey!!)
                        showDeleteKeyDialog = false
                        providerToDeleteKey = null
                    },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text(stringResource(R.string.label_delete))
                }
            },
            dismissButton = {
                TextButton(onClick = {
                    showDeleteKeyDialog = false
                    providerToDeleteKey = null
                }) {
                    Text(stringResource(R.string.label_cancel))
                }
            }
        )
    }
}

@Composable
private fun TasksTabContent(
    allModels: List<LanguageModel>,
    allProviders: List<ApiProvider>,
    translationModel: LanguageModel?,
    exerciseModel: LanguageModel?,
    vocabularyModel: LanguageModel?,
    dictionaryModel: LanguageModel?,
    apiViewModel: ApiViewModel
) {
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 16.dp),
        contentPadding = PaddingValues(vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        item {
            AppCard {
                Column(Modifier.padding(16.dp)) {
                    Text(
                        text = stringResource(R.string.label_task_model_assignments),
                        style = MaterialTheme.typography.titleLarge,
                        modifier = Modifier.padding(bottom = 4.dp)
                    )
                    Text(
                        text = stringResource(R.string.text_configure_which_ai_model_to_use_for_each_task_type),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
                        modifier = Modifier.padding(bottom = 12.dp)
                    )
                    HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))

                    ModelSelectionRow(
                        label = stringResource(id = R.string.label_translation),
                        allModels = allModels,
                        allProviders = allProviders,
                        selectedModel = translationModel,
                        onModelSelected = { apiViewModel.setTranslationModel(it) }
                    )
                    ModelSelectionRow(
                        label = stringResource(id = R.string.label_exercise),
                        allModels = allModels,
                        allProviders = allProviders,
                        selectedModel = exerciseModel,
                        onModelSelected = { apiViewModel.setExerciseModel(it) }
                    )
                    ModelSelectionRow(
                        label = stringResource(id = R.string.label_vocabulary),
                        allModels = allModels,
                        allProviders = allProviders,
                        selectedModel = vocabularyModel,
                        onModelSelected = { apiViewModel.setVocabularyModel(it) }
                    )
                    ModelSelectionRow(
                        label = stringResource(id = R.string.label_dictionary),
                        allModels = allModels,
                        allProviders = allProviders,
                        selectedModel = dictionaryModel,
                        onModelSelected = { apiViewModel.setDictionaryModel(it) }
                    )
                }
            }
        }
    }
}

@Composable
@Preview
fun ApiKeyScreenPreview() {
    ApiKeyScreen(navController = NavController(ApplicationProvider.getApplicationContext()))
}

@Composable
private fun ModelSelectionRow(
    label: String,
    allModels: List<LanguageModel>,
    allProviders: List<ApiProvider>,
    selectedModel: LanguageModel?,
    onModelSelected: (LanguageModel?) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyLarge,
            modifier = Modifier.weight(1f)
        )
        Box(modifier = Modifier.weight(1.5f)) {
            ApiModelDropDown(
                models = allModels,
                providers = allProviders,
                selectedModel = selectedModel,
                onModelSelected = onModelSelected
            )
        }
    }
}

@Composable
@Preview
private fun HandleApiManagementDialogsPreview() {
    HandleApiManagementDialogs(
        state = ApiKeyManagementState()
    )
}


@Composable
private fun HandleApiManagementDialogs(
    state: ApiKeyManagementState
) {
    val activity = LocalContext.current.findActivity()
    val apiViewModel: ApiViewModel = hiltViewModel(viewModelStoreOwner = activity)
    if (state.isAddingProvider) {
        AddProviderDialog(
            onDismiss = { apiViewModel.cancelAddProvider() },
            onConfirm = { provider -> apiViewModel.addProvider(provider) }
        )
    }

    state.providerKeyForAddingModel?.let { providerKey ->
        AddModelDialog(
            providerKey = providerKey,
            isLoading = state.isAddingModel,
            isScanning = state.isScanningModels,
            scannedModels = state.scannedModels,
            errorMessage = state.addModelError,
            onDismiss = { apiViewModel.cancelAddModel() },
            onScan = { apiViewModel.scanModelsForProvider(providerKey) },
            onConfirm = { model -> apiViewModel.addModelToProvider(providerKey, model) }
        )
    }

    // Edit provider dialog
    state.providerKeyForEditing?.let { providerKey ->
        val provider = state.providerStates.firstOrNull { it.provider.key == providerKey }?.provider
        if (provider != null && state.modelIdForEditing == null) {
            EditProviderDialog(
                initial = provider,
                onDismiss = { apiViewModel.cancelEditing() },
                onConfirm = { updated -> apiViewModel.applyEditProvider(updated) }
            )
        }
        // Edit model dialog
        val modelId = state.modelIdForEditing
        if (provider != null && modelId != null) {
            val model = provider.models.firstOrNull { it.modelId == modelId }
            if (model != null) {
                EditModelDialog(
                    providerKey = provider.key,
                    initial = model,
                    onDismiss = { apiViewModel.cancelEditing() },
                    onConfirm = { updated -> apiViewModel.applyEditModel(provider.key, updated) },
                    errorMessage = state.addModelError
                )
            }
        }
    }

    if (state.showWipeAllConfirm) {
        AlertDialog(
            onDismissRequest = { apiViewModel.hideWipeAllConfirm() },
            title = { Text(stringResource(R.string.text_delete_all_providers_and_models_qm)) },
            text = { Text(stringResource(R.string.text_this_will_remove_all)) },
            confirmButton = {
                TextButton(
                    onClick = { apiViewModel.confirmWipeAll() },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text(stringResource(R.string.label_delete_all))
                }
            },
            dismissButton = {
                TextButton(onClick = { apiViewModel.hideWipeAllConfirm() }) {
                    Text(stringResource(R.string.label_cancel))
                }
            }
        )
    }
}


@Suppress("HardCodedStringLiteral")
@Composable
private fun EnhancedKeyStatus(provider: ApiProvider, hasKey: Boolean) {
    val base = provider.baseUrl.trim()
    val lower = base.lowercase()
    val isLocalHost = (
            lower.contains("localhost") ||
                    lower.contains("127.0.0.1") ||
                    lower.startsWith("192.168.") ||
                    lower.startsWith("http://192.168.") ||
                    lower.startsWith("10.") ||
                    lower.startsWith("http://10.") ||
                    Regex("^172\\.(1[6-9]|2[0-9]|3[0-1])\\.").containsMatchIn(lower) ||
                    Regex("^http://172\\.(1[6-9]|2[0-9]|3[0-1])\\.").containsMatchIn(lower)
            )

    val (text, color, icon) = when {
        isLocalHost -> Triple(stringResource(R.string.text_key_optional), MaterialTheme.colorScheme.primary, AppIcons.CheckCircle)
        hasKey -> Triple(stringResource(R.string.text_key_active), MaterialTheme.colorScheme.primary, AppIcons.CheckCircle)
        provider.isCustom -> Triple(stringResource(R.string.text_key_optional), MaterialTheme.colorScheme.primary, AppIcons.CheckCircle)
        else -> Triple(stringResource(R.string.text_no_key), MaterialTheme.colorScheme.error, AppIcons.Warning)
    }

    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .background(
                color = color.copy(alpha = 0.1f),
                shape = RoundedCornerShape(12.dp)
            )
            .padding(horizontal = 8.dp, vertical = 4.dp)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = text,
            tint = color,
            modifier = Modifier.size(14.dp)
        )
        Spacer(Modifier.width(4.dp))
        Text(
            text,
            color = color,
            style = MaterialTheme.typography.labelSmall,
            fontWeight = androidx.compose.ui.text.font.FontWeight.Medium
        )
    }
}

@Composable
private fun EnhancedProviderDetails(
    provider: ApiProvider,
    hasKey: Boolean,
    onChangeClick: () -> Unit,
    onAddModel: () -> Unit,
    onEditModel: (String) -> Unit,
    onDeleteModel: (String) -> Unit,
    onDeleteKey: () -> Unit = {}
) {
    Column(modifier = Modifier.fillMaxWidth()) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                stringResource(R.string.text_available_models),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.weight(1f)
            )
            TextButton(onClick = onAddModel) {
                Icon(AppIcons.Add, contentDescription = null, modifier = Modifier.size(16.dp))
                Spacer(Modifier.width(4.dp))
                Text(stringResource(R.string.label_add_model))
            }
        }

        if (provider.models.isNotEmpty()) {
            Spacer(Modifier.height(8.dp))
            provider.models.forEach { model ->
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp)
                ) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            model.displayName,
                            style = MaterialTheme.typography.bodyMedium,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.Medium
                        )
                        if (model.description.isNotBlank()) {
                            Text(
                                model.description,
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                            )
                        }
                    }
                    if (model.isCustom) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier.height(40.dp)
                        ) {
                            IconButton(
                                onClick = { onEditModel(model.modelId) },
                                modifier = Modifier.size(36.dp)
                            ) {
                                Icon(
                                    AppIcons.Edit,
                                    contentDescription = stringResource(R.string.edit),
                                    modifier = Modifier.size(20.dp)
                                )
                            }
                            IconButton(
                                onClick = { onDeleteModel(model.modelId) },
                                modifier = Modifier.size(36.dp)
                            ) {
                                Icon(
                                    AppIcons.Delete,
                                    contentDescription = stringResource(R.string.delete_model),
                                    modifier = Modifier.size(20.dp)
                                )
                            }
                        }
                    }
                }
            }
        } else {
            Spacer(Modifier.height(8.dp))
            Text(
                stringResource(R.string.no_models_configured),
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
                modifier = Modifier.padding(vertical = 8.dp)
            )
        }

        Spacer(Modifier.height(16.dp))
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            if (hasKey) {
                SecondaryButton(
                    onClick = onChangeClick,
                    text = stringResource(R.string.text_change_key),
                    modifier = Modifier.weight(1f)
                )
                SecondaryButton(
                    onClick = onDeleteKey,
                    text = stringResource(R.string.label_delete_key),
                    modifier = Modifier.weight(1f),
                    maxLines = 1
                )
            } else {
                SecondaryButton(
                    onClick = onChangeClick,
                    text = stringResource(R.string.label_add_key),
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
}

@Composable
private fun ProviderCard(
    providerState: ProviderState,
    onApiKeyChanged: (String) -> Unit,
    onSave: () -> Unit,
    onToggleEdit: () -> Unit,
    onAddModel: () -> Unit,
    onEditModel: (String) -> Unit,
    onDeleteModel: (String) -> Unit,
    onEditProvider: () -> Unit,
    onDeleteProvider: () -> Unit,
    onDeleteKey: () -> Unit,
    modifier: Modifier = Modifier
) {
    var expanded by remember { mutableStateOf(false) }
    @Suppress("HardCodedStringLiteral") val rotationAngle by animateFloatAsState(
        targetValue = if (expanded) 180f else 0f,
        animationSpec = tween(durationMillis = 300),
        label = "rotation"
    )

    val isActive = providerState.hasKey || providerState.provider.isCustom
    val modelCount = providerState.provider.models.size

    AppCard(
        modifier = modifier.fillMaxWidth(),
    ) {
        Column(Modifier.padding(vertical = 12.dp, horizontal = 16.dp)) {
            // Main header with essential info only
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { expanded = !expanded },
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = AppIcons.ExpandMore,
                    contentDescription = if (expanded) stringResource(R.string.cd_collapse) else stringResource(R.string.cd_expand),
                    modifier = Modifier.rotate(rotationAngle),
                    tint = if (isActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                )
                Spacer(Modifier.width(12.dp))

                Column(modifier = Modifier.weight(1f)) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text(
                            providerState.provider.displayName,
                            style = MaterialTheme.typography.titleMedium,
                            color = if (isActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
                            modifier = Modifier.weight(1f)
                        )
                        if (providerState.provider.isCustom) {
                            Spacer(Modifier.width(8.dp))
                            Text(
                                stringResource(R.string.label_custom),
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.primary,
                                modifier = Modifier
                                    .background(
                                        color = MaterialTheme.colorScheme.primary.copy(alpha = 0.1f),
                                        shape = RoundedCornerShape(4.dp)
                                    )
                                    .padding(horizontal = 6.dp, vertical = 2.dp)
                            )
                        }
                    }
                    Spacer(Modifier.height(4.dp))
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        EnhancedKeyStatus(provider = providerState.provider, hasKey = providerState.hasKey)
                        Text(
                            text = stringResource(R.string.label_amount_models, modelCount),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                        )
                    }
                }
            }

            // Quick actions when not expanded
            if (!expanded && isActive) {
                Spacer(Modifier.height(8.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    TextButton(
                        onClick = onAddModel,
                        modifier = Modifier.weight(1f)
                    ) {
                        Icon(AppIcons.Add, contentDescription = null, modifier = Modifier.size(16.dp))
                        Spacer(Modifier.width(4.dp))
                        Text(stringResource(R.string.label_add_model))
                    }
                }
            }

            // Expanded content with better organization
            AnimatedVisibility(visible = expanded) {
                Column(modifier = Modifier.padding(top = 12.dp)) {
                    HorizontalDivider()

                    Spacer(Modifier.height(12.dp))

                    // Status and actions section
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column {
                            Text(
                                stringResource(R.string.label_status),
                                style = MaterialTheme.typography.labelMedium,
                                color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                            )
                            EnhancedKeyStatus(provider = providerState.provider, hasKey = providerState.hasKey)
                        }

                        if (providerState.provider.isCustom) {
                            Row {
                                IconButton(onClick = onEditProvider) {
                                    Icon(AppIcons.Edit, contentDescription = stringResource(R.string.edit), tint = MaterialTheme.colorScheme.primary)
                                }
                                IconButton(onClick = onDeleteProvider) {
                                    Icon(AppIcons.Delete, contentDescription = stringResource(R.string.delete_provider), tint = MaterialTheme.colorScheme.error)
                                }
                            }
                        }
                    }

                    if (providerState.provider.websiteUrl.isNotBlank()) {
                        Spacer(Modifier.height(12.dp))
                        val annotatedString = buildAnnotatedString {
                            withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.primary, textDecoration = TextDecoration.Underline)) {
                                append(stringResource(R.string.text_get_api_key_at, providerState.provider.displayName))
                                addStringAnnotation("URL", providerState.provider.websiteUrl, 0, length)
                            }
                        }
                        ClickableText(
                            text = annotatedString,
                            style = MaterialTheme.typography.bodySmall,
                        )
                    }

                    Spacer(Modifier.height(16.dp))

                    if (providerState.isEditing) {
                        ApiKeyInput(
                            apiKey = providerState.apiKey,
                            validationMessage = providerState.validationMessage,
                            onApiKeyChanged = onApiKeyChanged,
                            onSave = onSave,
                            onCancel = onToggleEdit
                        )
                    } else {
                        EnhancedProviderDetails(
                            provider = providerState.provider,
                            hasKey = providerState.hasKey,
                            onChangeClick = onToggleEdit,
                            onAddModel = onAddModel,
                            onEditModel = onEditModel,
                            onDeleteModel = onDeleteModel,
                            onDeleteKey = onDeleteKey
                        )
                    }
                }
            }
        }
    }
}


@Suppress("HardCodedStringLiteral")
@Composable
@Preview
private fun ApiKeyInputPreview() {
    ApiKeyInput(
        apiKey = "test_api_key",
        validationMessage = "",
        onApiKeyChanged = {},
        onSave = {}
    )
}


@Composable
private fun ApiKeyInput(
    apiKey: String,
    validationMessage: String,
    onApiKeyChanged: (String) -> Unit,
    onSave: () -> Unit,
    onCancel: (() -> Unit)? = null
) {
    Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
        val clipboard = LocalClipboardManager.current
        AppOutlinedTextField(
            value = apiKey,
            onValueChange = onApiKeyChanged,
            label = { Text(stringResource(R.string.text_enter_api_key)) },
            modifier = Modifier.fillMaxWidth(),
            maxLines = 3,
            trailingIcon = {
                IconButton(
                    onClick = {
                        val text = clipboard.getText()?.text
                        if (!text.isNullOrBlank()) onApiKeyChanged(text)
                    },
                    enabled = true
                ) { Icon(AppIcons.Paste, contentDescription = stringResource(R.string.cd_paste)) }
            }
        )
        if (validationMessage.isNotBlank()) {
            Text(validationMessage, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
        }
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
            onCancel?.let {
                TextButton(onClick = it) { Text(stringResource(R.string.label_cancel)) }
                Spacer(Modifier.width(8.dp))
            }
            PrimaryButton(
                onClick = onSave,
                enabled = apiKey.isNotBlank(),
                text = stringResource(R.string.text_save_key)
            )
        }
    }
}


@Composable
fun AddProviderDialog(onDismiss: () -> Unit, onConfirm: (ApiProvider) -> Unit) {
    val activity = LocalContext.current.findActivity()
    val apiViewModel: ApiViewModel = hiltViewModel(viewModelStoreOwner = activity)
    var key by remember { mutableStateOf("") }
    var displayName by remember { mutableStateOf("") }
    var baseUrl by remember { mutableStateOf("") }
    var endpoint by remember { mutableStateOf("") }
    var websiteUrl by remember { mutableStateOf("") }
    val isFormValid = displayName.isNotBlank() && baseUrl.isNotBlank()
    var isChecking by remember { mutableStateOf(false) }
    var availabilityMessage by remember { mutableStateOf<String?>(null) }
    var availabilityOk by remember { mutableStateOf<Boolean?>(null) }

    AppDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.label_add_custom_provider)) },
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(0.dp),
        ) {
            Column(
                modifier = Modifier.padding(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                AppOutlinedTextField(
                    value = displayName,
                    onValueChange = { newValue: String -> displayName = newValue },
                    label = { Text(stringResource(R.string.display_name) + " *") },
                    modifier = Modifier.fillMaxWidth()
                )
                AppOutlinedTextField(
                    value = baseUrl,
                    onValueChange = { newValue: String -> baseUrl = newValue },
                    label = { Text(stringResource(R.string.text_base_url_and_example) + " *") },
                    modifier = Modifier.fillMaxWidth(),
                    maxLines = 2
                )
                AppOutlinedTextField(
                    value = endpoint,
                    onValueChange = { newValue: String -> endpoint = newValue },
                    label = { Text(buildString {
                        append(stringResource(R.string.endpoint_e_g_api_chat))
                        append(stringResource(R.string.text_optional))
                    }) },
                    modifier = Modifier.fillMaxWidth()
                )
                AppOutlinedTextField(
                    value = websiteUrl,
                    onValueChange = { newValue: String -> websiteUrl = newValue },
                    label = { Text(buildString {
                        append(stringResource(R.string.website_url))
                        append(stringResource(R.string.text_optional))
                    }) },
                    modifier = Modifier.fillMaxWidth()
                )

                Text(stringResource(R.string.label_start_required), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f))

                Row(verticalAlignment = Alignment.CenterVertically) {
                    if (isChecking) {
                        CircularProgressIndicator(modifier = Modifier.size(18.dp))
                        Spacer(Modifier.width(8.dp))
                        @Suppress("HardCodedStringLiteral")
                        Text("Checking...", style = MaterialTheme.typography.bodySmall)
                    } else {
                        SecondaryButton(
                            onClick = {
                                availabilityMessage = null
                                availabilityOk = null
                                isChecking = true
                                val url = baseUrl.trim()
                                apiViewModel.checkProviderAvailability(url) { ok, msg ->
                                    availabilityOk = ok
                                    availabilityMessage = msg
                                    isChecking = false
                                }
                            },
                            text = stringResource(R.string.text_check_availability)
                        )
                    }
                }
                availabilityMessage?.let { msg ->
                    val color = if (availabilityOk == true) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error
                    Text(msg, color = color, style = MaterialTheme.typography.bodySmall)
                }

                // Buttons
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 16.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextButton(onClick = onDismiss) {
                        Text(stringResource(R.string.label_cancel))
                    }
                    AppButton(
                        onClick = {
                            onConfirm(ApiProvider(
                                key = key.trim(),
                                displayName = displayName.trim(),
                                baseUrl = baseUrl.trim(),
                                endpoint = endpoint.trim(),
                                websiteUrl = websiteUrl.trim(),
                                models = emptyList(),
                                isCustom = true
                            ))
                        },
                        enabled = isFormValid
                    ) {
                        Text(stringResource(R.string.label_add))
                    }
                }
            }
        }
    }
}



@Composable
fun EditProviderDialog(
    initial: ApiProvider,
    onDismiss: () -> Unit,
    onConfirm: (ApiProvider) -> Unit
) {
    var displayName by remember { mutableStateOf(initial.displayName) }
    var baseUrl by remember { mutableStateOf(initial.baseUrl) }
    var endpoint by remember { mutableStateOf(initial.endpoint) }
    var websiteUrl by remember { mutableStateOf(initial.websiteUrl) }
    val isFormValid = displayName.isNotBlank() && baseUrl.isNotBlank()

    AppDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.edit) + " " + initial.displayName) },
    ) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            )
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                AppOutlinedTextField(
                    value = displayName,
                    onValueChange = { displayName = it },
                    label = { Text(stringResource(R.string.display_name) + " *") },
                    modifier = Modifier.fillMaxWidth()
                )
                AppOutlinedTextField(
                    value = baseUrl,
                    onValueChange = { baseUrl = it },
                    label = { Text(stringResource(R.string.text_base_url_and_example) + " *") },
                    modifier = Modifier.fillMaxWidth()
                )
                AppOutlinedTextField(
                    value = endpoint,
                    onValueChange = { endpoint = it },
                    label = { Text(buildString {
                        append(stringResource(R.string.endpoint_e_g_api_chat))
                        append(stringResource(R.string.text_optional))
                    }) },
                    modifier = Modifier.fillMaxWidth()
                )
                AppOutlinedTextField(
                    value = websiteUrl,
                    onValueChange = { websiteUrl = it },
                    label = { Text(buildString {
                        append(stringResource(R.string.website_url))
                        append(stringResource(R.string.text_optional))
                    }) },
                    modifier = Modifier.fillMaxWidth()
                )

                Text(stringResource(R.string.label_star_required), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f))

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 16.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextButton(onClick = onDismiss) { Text(stringResource(R.string.label_cancel)) }
                    AppButton(
                        onClick = {
                            onConfirm(
                                initial.copy(
                                    displayName = displayName.trim(),
                                    baseUrl = baseUrl.trim(),
                                    endpoint = endpoint.trim(),
                                    websiteUrl = websiteUrl.trim()
                                )
                            )
                        },
                        enabled = isFormValid
                    ) { Text(stringResource(R.string.label_save)) }
                }
            }
        }
    }
}


@Composable
@Preview
fun AddModelDialogPreview() {
    @Suppress("HardCodedStringLiteral")
    AddModelDialog(
        providerKey = "test_provider",
        isLoading = false,
        isScanning = false,
        scannedModels = emptyList(),
        errorMessage = null,
        onDismiss = {},
        onScan = {},
        onConfirm = {}
    )
}

@Composable
fun AddModelDialog(
    providerKey: String,
    isLoading: Boolean,
    isScanning: Boolean,
    scannedModels: List<LanguageModel>,
    errorMessage: String?,
    onDismiss: () -> Unit,
    onScan: () -> Unit,
    onConfirm: (LanguageModel) -> Unit
) {
    var modelId by remember { mutableStateOf("") }
    var displayName by remember { mutableStateOf("") }
    var description by remember { mutableStateOf("") }
    val isFormValid = modelId.isNotBlank() && displayName.isNotBlank() && !isLoading

    AppDialog(
        onDismissRequest = { if (!isLoading) onDismiss() },
        title = {
            Text(
                text = stringResource(R.string.label_add_custom_model),
            )
        }
    ) {

        Column(
            modifier = Modifier
                .padding(4.dp)
                .heightIn(max = 1000.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // Optional scan area
            Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                TextButton(onClick = onScan, enabled = !isLoading && !isScanning) {
                    Text(text = if (isScanning) stringResource(R.string.scanning) else stringResource(R.string.scan_models))
                }
            }
            if (scannedModels.isNotEmpty()) {
                Text(text = stringResource(R.string.text_select_model), style = MaterialTheme.typography.titleSmall)
                LazyColumn(
                    modifier = Modifier.heightIn(max = 150.dp)
                ) {
                    items(scannedModels) { m ->
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Text(text = m.modelId, modifier = Modifier.weight(1f))
                            TextButton(onClick = {
                                modelId = m.modelId
                                displayName = m.displayName.ifBlank { m.modelId }
                                description = m.description
                            }) { Text(stringResource(R.string.label_select)) }
                        }
                    }
                }
            } else if (!isScanning) {
                Text(text = stringResource(R.string.no_models_found), style = MaterialTheme.typography.bodySmall)
            }

            // Manual entry
            AppOutlinedTextField(
                value = displayName,
                onValueChange = { newValue: String -> displayName = newValue },
                label = { Text(stringResource(R.string.display_name)) },
                enabled = !isLoading,
                modifier = Modifier.fillMaxWidth()
            )
            AppOutlinedTextField(
                value = modelId,
                onValueChange = { newValue: String -> modelId = newValue },
                label = { Text(stringResource(R.string.model_id)) },
                enabled = !isLoading,
                modifier = Modifier.fillMaxWidth(),
                maxLines = 2
            )
            AppOutlinedTextField(
                value = description,
                onValueChange = { newValue: String -> description = newValue },
                label = { Text(stringResource(R.string.description)) },
                enabled = !isLoading,
                modifier = Modifier.fillMaxWidth()
            )

            if (isLoading) {
                Spacer(modifier = Modifier.height(8.dp))
                CircularProgressIndicator(modifier = Modifier.align(Alignment.CenterHorizontally))
            }

            errorMessage?.let {
                Spacer(modifier = Modifier.height(8.dp))
                Text(text = it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
            }

            // Buttons
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp),
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically
            ) {
                TextButton(onClick = onDismiss, enabled = !isLoading) {
                    Text(stringResource(R.string.label_cancel))
                }
                AppButton(
                    onClick = {
                        onConfirm(LanguageModel(
                            modelId = modelId.trim(),
                            displayName = displayName.trim(),
                            providerKey = providerKey,
                            description = description.trim(),
                            isCustom = true
                        ))
                    },
                    enabled = isFormValid
                ) {
                    Text(stringResource(R.string.label_add_validate))
                }
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Composable
@Preview
fun EditModelDialogPreview() {
    EditModelDialog(
        providerKey = "test_provider",
        initial = LanguageModel("test_model_id", "Test Model", "test_provider", "Test description"),
        onDismiss = {},
        onConfirm = {},
        errorMessage = null
    )
}


@Composable
fun EditModelDialog(
    providerKey: String,
    initial: LanguageModel,
    onDismiss: () -> Unit,
    onConfirm: (LanguageModel) -> Unit,
    errorMessage: String? = null
) {
    var displayName by remember { mutableStateOf(initial.displayName) }
    var description by remember { mutableStateOf(initial.description) }
    var modelId by remember { mutableStateOf(initial.modelId) }

    val isFormValid = modelId.isNotBlank() && displayName.isNotBlank()

    AppDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.edit) + " " + initial.displayName) },
    ) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            )
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                AppOutlinedTextField(
                    value = displayName,
                    onValueChange = { displayName = it },
                    label = { Text(stringResource(R.string.display_name)) },
                    modifier = Modifier.fillMaxWidth()
                )
                AppOutlinedTextField(
                    value = modelId,
                    onValueChange = { modelId = it },
                    label = { Text(stringResource(R.string.model_id)) },
                    modifier = Modifier.fillMaxWidth()
                )
                AppOutlinedTextField(
                    value = description,
                    onValueChange = { description = it },
                    label = { Text(stringResource(R.string.description)) },
                    modifier = Modifier.fillMaxWidth()
                )

                errorMessage?.let {
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(text = it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
                }

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 16.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextButton(onClick = onDismiss) { Text(stringResource(R.string.label_cancel)) }
                    AppButton(
                        onClick = {
                            onConfirm(
                                initial.copy(
                                    modelId = modelId.trim(),
                                    displayName = displayName.trim(),
                                    description = description.trim(),
                                    providerKey = providerKey,
                                    isCustom = true
                                )
                            )
                        },
                        enabled = isFormValid
                    ) { Text(stringResource(R.string.label_save)) }
                }
            }
        }
    }
}