/*
 * Book's Story — free and open-source Material You eBook reader.
 * Copyright (C) 2024-2026 Acclorite
 * SPDX-License-Identifier: GPL-3.0-only
 */

package org.dueattendant149.bookshelf.ui.settings.bookshelf

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import org.dueattendant149.bookshelf.R
import org.dueattendant149.bookshelf.presentation.settings.BookshelfSettingsModel
import org.dueattendant149.bookshelf.ui.navigator.NavigatorBackIconButton

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BookshelfSettingsContent(
    model: BookshelfSettingsModel,
    listState: LazyListState,
    scrollBehavior: TopAppBarScrollBehavior,
    navigateBack: () -> Unit,
) {
    val state by model.state.collectAsStateWithLifecycle()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.bookshelf_settings_screen_title)) },
                navigationIcon = {
                    NavigatorBackIconButton(navigateBack = navigateBack)
                },
                scrollBehavior = scrollBehavior,
            )
        }
    ) { padding ->
        LazyColumn(
            state = listState,
            modifier = Modifier
                .fillMaxSize()
                .padding(padding),
            contentPadding = PaddingValues(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            item {
                OutlinedTextField(
                    value = state.bookshelfUrl,
                    onValueChange = model::updateBookshelfUrl,
                    label = { Text(stringResource(R.string.bookshelf_url_option)) },
                    placeholder = { Text("http://bookshelf-api:8073") },
                    supportingText = { Text(stringResource(R.string.bookshelf_url_option_desc)) },
                    modifier = Modifier.fillMaxWidth()
                )
            }
            item {
                OutlinedTextField(
                    value = state.absUrl,
                    onValueChange = model::updateAbsUrl,
                    label = { Text(stringResource(R.string.abs_url_option)) },
                    placeholder = { Text("http://192.168.1.119:13378") },
                    supportingText = { Text(stringResource(R.string.abs_url_option_desc)) },
                    modifier = Modifier.fillMaxWidth()
                )
            }
            item {
                OutlinedTextField(
                    value = state.absToken,
                    onValueChange = model::updateAbsToken,
                    label = { Text(stringResource(R.string.abs_token_option)) },
                    supportingText = { Text(stringResource(R.string.abs_token_option_desc)) },
                    modifier = Modifier.fillMaxWidth()
                )
            }
            item {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Button(
                        onClick = model::save,
                        enabled = !state.isLoading && !state.isCheckingConnection,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(stringResource(R.string.save_button))
                    }
                    Button(
                        onClick = model::checkConnection,
                        enabled = !state.isLoading && !state.isCheckingConnection,
                        modifier = Modifier.weight(1f)
                    ) {
                        if (state.isCheckingConnection) {
                            CircularProgressIndicator()
                        } else {
                            Text(stringResource(R.string.check_connection_button))
                        }
                    }
                }
            }
            item {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    OutlinedButton(
                        onClick = model::deriveAbsUrlFromBookshelf,
                        enabled = state.bookshelfUrl.isNotBlank() && !state.isLoading,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(stringResource(R.string.derive_abs_url_button))
                    }
                    OutlinedButton(
                        onClick = model::testLibraries,
                        enabled = !state.isLoading && !state.isCheckingConnection,
                        modifier = Modifier.weight(1f)
                    ) {
                        if (state.isLoading) {
                            CircularProgressIndicator()
                        } else {
                            Text(stringResource(R.string.fetch_libraries_button))
                        }
                    }
                }
            }
            state.connectionSuccess.takeIf { it }?.let {
                item {
                    Text(
                        text = stringResource(R.string.connection_successful),
                        color = MaterialTheme.colorScheme.primary,
                    )
                }
            }
            state.connectionError?.let { error ->
                item {
                    Text(
                        text = error,
                        color = MaterialTheme.colorScheme.error,
                    )
                }
            }
            state.librariesSuccess.takeIf { it }?.let {
                item {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.CheckCircle,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary
                        )
                        Text(
                            text = stringResource(
                                R.string.libraries_fetched_successful,
                                state.libraries.size
                            ),
                            color = MaterialTheme.colorScheme.primary,
                        )
                    }
                }
            }
            state.error?.let { error ->
                item {
                    Text(
                        text = error,
                        color = MaterialTheme.colorScheme.error,
                    )
                }
            }
            items(state.libraries.size) { index ->
                val library = state.libraries[index]
                ListItem(
                    headlineContent = { Text(library.name) },
                    supportingContent = {
                        Text(
                            stringResource(
                                R.string.bookshelf_library_subtitle,
                                library.mediaType,
                                library.itemCount
                            )
                        )
                    }
                )
            }
        }
    }
}
