package eu.gaudian.translator.view.settings

import android.annotation.SuppressLint
import android.content.Context
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import eu.gaudian.translator.BuildConfig
import eu.gaudian.translator.R
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.utils.StatusAction
import eu.gaudian.translator.utils.StatusMessageId
import eu.gaudian.translator.utils.StatusMessageService
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppSwitch
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.SecondaryButton
import eu.gaudian.translator.viewmodel.SettingsViewModel
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Composable
fun AboutScreen(
    navController: NavController,
) {
    val context = LocalContext.current
    val activity = LocalContext.current.findActivity()
    val settingsViewModel: SettingsViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val isDeveloperMode by settingsViewModel.isDeveloperModeEnabled.collectAsStateWithLifecycle(initialValue = false)
    var tapCount by remember { mutableIntStateOf(0) }
    var showDeveloperSwitch by remember { mutableStateOf(isDeveloperMode) }
    var licensesExpanded by remember { mutableStateOf(false) }
    var changelogExpanded by remember { mutableStateOf(false) }
    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.label_about),
                onNavigateBack = { navController.popBackStack() }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(paddingValues)
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            AppCard {

                Column(
                    modifier = Modifier
                        .padding(16.dp)
                        .fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Image(
                        painter = painterResource(id = R.mipmap.ic_launcher_foreground),
                        contentDescription = stringResource(R.string.cd_app_logo),
                        modifier = Modifier
                            .size(128.dp)
                            .clickable {
                                tapCount++
                                if (tapCount >= 7) {
                                    showDeveloperSwitch = true
                                }
                            }
                    )

                    Text(
                        text = stringResource(id = R.string.app_name),
                        style = MaterialTheme.typography.headlineSmall,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = getAppVersion(context),
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = stringResource(id = R.string.text_developed_by_jonas_gaudian),
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            val uriHandler = LocalUriHandler.current

            // Group 1: Website + Contact Developer + Changelog in one AppCard
            AppCard {
                Column {
                    // Website link
                    val websiteUrl = stringResource(R.string.gaudian_eu_website)
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { uriHandler.openUri(websiteUrl) }
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = stringResource(id = R.string.text_visit_my_website),
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = FontWeight.SemiBold
                        )
                        Icon(
                            imageVector = AppIcons.ExitToApp,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }

                    HorizontalDivider()

                    // Contact developer
                    val appName = stringResource(R.string.app_name)
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                @Suppress("HardCodedStringLiteral") val intent = android.content.Intent(android.content.Intent.ACTION_SENDTO).apply {
                                    data = "mailto:play@gaudian.eu".toUri()
                                    putExtra(android.content.Intent.EXTRA_EMAIL, arrayOf("play@gaudian.eu"))
                                    putExtra(android.content.Intent.EXTRA_SUBJECT,
                                        "$appName Feedback"
                                    )
                                }
                                context.startActivity(intent)
                            }
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                text = stringResource(R.string.contact_developer_title),
                                style = MaterialTheme.typography.bodyLarge,
                                fontWeight = FontWeight.SemiBold
                            )
                            Text(
                                text = stringResource(R.string.contact_developer_description),
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }

                    HorizontalDivider()

                    // Changelog expandable
                    @Suppress("HardCodedStringLiteral") val rotationAngle by animateFloatAsState(
                        targetValue = if (changelogExpanded) 180f else 0f,
                        label = "Changelog Arrow Animation"
                    )
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { changelogExpanded = !changelogExpanded }
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = stringResource(R.string.whats_new_changelog_title),
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = FontWeight.SemiBold,
                            modifier = Modifier.weight(1f)
                        )
                        Icon(
                            imageVector = AppIcons.ExpandMore,
                            contentDescription = stringResource(R.string.toggle_licenses),
                            modifier = Modifier.rotate(rotationAngle)
                        )
                    }

                    AnimatedVisibility(visible = changelogExpanded) {
                        ChangelogList()
                    }
                }
            }

            // Group 2: Open source licenses + Legal information in one AppCard
            AppCard {
                Column {
                    @Suppress("HardCodedStringLiteral") val rotationAngle by animateFloatAsState(
                        targetValue = if (licensesExpanded) 180f else 0f,
                        label = "License Arrow Animation"
                    )
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { licensesExpanded = !licensesExpanded }
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = stringResource(R.string.open_source_licenses),
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = FontWeight.SemiBold,
                            modifier = Modifier.weight(1f)
                        )
                        Icon(
                            imageVector = AppIcons.ExpandMore,
                            contentDescription = stringResource(R.string.toggle_licenses),
                            modifier = Modifier.rotate(rotationAngle)
                        )
                    }

                    AnimatedVisibility(visible = licensesExpanded) {
                        OpenSourceLicensesList()
                    }

                    HorizontalDivider()
                    val legalInformationUrl = stringResource(R.string.legal_information_url)

                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { uriHandler.openUri(legalInformationUrl) }
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = stringResource(R.string.legal_information),
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = FontWeight.SemiBold
                        )
                        Icon(
                            imageVector = AppIcons.ExitToApp,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                }
            }

            if (showDeveloperSwitch) {
                DeveloperOptions(
                    isDeveloperMode = isDeveloperMode,
                    onToggle = { settingsViewModel.setDeveloperMode(it) },
                    navController = navController
                )
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Composable
private fun OpenSourceLicensesList() {
    val uriHandler = LocalUriHandler.current
    val apacheLicenseUrl = "https://www.apache.org/licenses/LICENSE-2.0"

    data class LibraryInfo(val name: String, val author: String, val licenseUrl: String, val licenseType: String = "Apache License 2.0")

    // Updated dependencies
    val libraries = remember {
        listOf(
            LibraryInfo("Android Jetpack", "Google", apacheLicenseUrl),
            LibraryInfo("AndroidX", "Google", apacheLicenseUrl),
            LibraryInfo("Core KTX", "Google", apacheLicenseUrl),
            LibraryInfo("JSoup", "Jonathan Hedley", "https://jsoup.org/license"),
            LibraryInfo("Kotlin", "JetBrains", "https://kotlinlang.org/LICENSE.txt"),
            LibraryInfo("KotlinX", "JetBrains", apacheLicenseUrl),
            LibraryInfo("Material Components for Android", "Google", apacheLicenseUrl),
            LibraryInfo("OkHttp", "Square, Inc.", "https://www.apache.org/licenses/LICENSE-2.0"),
            LibraryInfo("Retrofit", "Square, Inc.", "https://www.apache.org/licenses/LICENSE-2.0"),
            LibraryInfo("Room Compiler", "Google", apacheLicenseUrl),
            LibraryInfo("Timber", "Jake Wharton", "https://www.apache.org/licenses/LICENSE-2.0"),
            LibraryInfo("YouTube Player Android Core", "Pierfrancesco Soffritti", "https://www.apache.org/licenses/LICENSE-2.0"),
            LibraryInfo("Zstandard", "Meta Platforms", "https://github.com/facebook/zstd/blob/dev/LICENSE"),
        ).sortedBy { it.name } // Sort alphabetically
    }

    Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
        libraries.forEach { library ->
            Column(Modifier.padding(vertical = 8.dp)) {
                Text(
                    text = library.name,
                    style = MaterialTheme.typography.bodyLarge,
                    fontWeight = FontWeight.Bold
                )
                Text(
                    text = library.author,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = library.licenseType,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.primary,
                    textDecoration = TextDecoration.Underline,
                    modifier = Modifier.clickable { uriHandler.openUri(library.licenseUrl) }
                )
            }
            HorizontalDivider(modifier = Modifier.padding(top = 8.dp))
        }
    }
}

@Composable
private fun ChangelogList() {
    val changelogEntries = stringArrayResource(R.array.changelog_entries)
    
    Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
        changelogEntries.forEachIndexed { index, entry ->
            Text(
                text = entry,
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.padding(vertical = 8.dp)
            )
            if (index < changelogEntries.size - 1) {
                HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
            }
        }
    }
}


@Composable
private fun DeveloperOptions(
    isDeveloperMode: Boolean,
    onToggle: (Boolean) -> Unit,
    navController: NavController,
) {
    val context = LocalContext.current

    val activity = context.findActivity()
    val statusMessageService = StatusMessageService
    val settingsViewModel: SettingsViewModel = hiltViewModel(viewModelStoreOwner = activity)


    AppCard {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onToggle(!isDeveloperMode) },
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = stringResource(R.string.title_developer_options),
                    style = MaterialTheme.typography.titleMedium
                )
                AppSwitch(checked = isDeveloperMode, onCheckedChange = onToggle)
            }

            if (isDeveloperMode) {
                val experimentalFeatures by settingsViewModel.experimentalFeatures.collectAsStateWithLifecycle()
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { settingsViewModel.setExperimentalFeatures(!experimentalFeatures) },
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = stringResource(R.string.experimental_features),
                            style = MaterialTheme.typography.bodyLarge
                        )
                        Text(
                            text = stringResource(R.string.experimental_features_description),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                    AppSwitch(
                        checked = experimentalFeatures,
                        onCheckedChange = { settingsViewModel.setExperimentalFeatures(it) }
                    )
                }



                SecondaryButton(
                    onClick = { statusMessageService.showMessageById(StatusMessageId.LOADING_GENERIC) },
                    text = stringResource(R.string.text_show_loading),
                    modifier = Modifier.fillMaxWidth()
                )
                SecondaryButton(
                    onClick = { statusMessageService.trigger(StatusAction.CancelLoadingOperation)},
                    text = stringResource(R.string.text_cancel_loading),
                    modifier = Modifier.fillMaxWidth()
                )
                SecondaryButton(
                    onClick = { statusMessageService.showInfoById(StatusMessageId.TEST_INFO) },
                    text = stringResource(R.string.text_show_info_message),
                    modifier = Modifier.fillMaxWidth()
                )
                SecondaryButton(
                    onClick = { statusMessageService.showSuccessById(StatusMessageId.TEST_SUCCESS) },
                    text = stringResource(R.string.title_show_success_message),
                    modifier = Modifier.fillMaxWidth()
                )
                SecondaryButton(
                    onClick = { statusMessageService.showErrorById(StatusMessageId.TEST_ERROR) },
                    text = stringResource(R.string.text_show_error_message),
                    modifier = Modifier.fillMaxWidth()
                )
                SecondaryButton(
                    onClick = { statusMessageService.showErrorById(StatusMessageId.ERROR_API_KEY_MISSING) },
                    text = stringResource(R.string.show_api_key_missing_message),
                    modifier = Modifier.fillMaxWidth()
                )
                SecondaryButton(
                    onClick = { settingsViewModel.setIntroCompleted(false) },
                    text = stringResource(R.string.text_reset_intro),
                    modifier = Modifier.fillMaxWidth()
                )
                HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
                SecondaryButton(
                    onClick = { navController.navigate(SettingsRoutes.THEME_PREVIEW) },
                    text = stringResource(R.string.text_theme_preview),
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
}

@SuppressLint("DefaultLocale")
@Suppress("HardCodedStringLiteral")
private fun getAppVersion(context: Context): String {
    return try {
        val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)


        val parser = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm")

        val buildDateTime = LocalDateTime.parse(BuildConfig.BUILD_TIME, parser)

        val year = buildDateTime.format(DateTimeFormatter.ofPattern("yy"))
        val dayOfYear = String.format("%03d", buildDateTime.dayOfYear)
        val time = buildDateTime.format(DateTimeFormatter.ofPattern("HHmm"))
        val buildIdentifier = "$year.$dayOfYear.$time"


        context.getString(
            R.string.text_version_display_string_2d,
            packageInfo.versionName,
            buildIdentifier
        )
    } catch (e: Exception) {
        e.printStackTrace()
        context.getString(R.string.text_sentenc_version_information_not_available)
    }
}

@ThemePreviews
@Composable
private fun AboutScreenPreview() {
    MaterialTheme {
        AboutScreen(navController = NavController(LocalContext.current))
    }
}