package com.birdsounds.identify.presentation

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.text.format.DateFormat
import android.util.Log
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.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Face
import androidx.compose.material.icons.rounded.Info
import androidx.compose.material.icons.rounded.Mic
import androidx.compose.material.icons.rounded.MicOff
import androidx.compose.material.icons.rounded.MusicNote
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.wear.compose.foundation.curvedComposable
import androidx.wear.compose.foundation.lazy.itemsIndexed
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.LocalContentColor
import androidx.wear.compose.material.TimeTextDefaults
import androidx.wear.compose.material.TimeText
import androidx.wear.compose.material.curvedText
import com.google.android.horologist.annotations.ExperimentalHorologistApi
import com.google.android.horologist.compose.layout.ScalingLazyColumn
import com.google.android.horologist.compose.layout.ScalingLazyColumnDefaults
import com.google.android.horologist.compose.layout.ScreenScaffold
import com.google.android.horologist.compose.layout.rememberResponsiveColumnState
import kotlinx.coroutines.delay
import java.time.Instant
import java.util.Locale


fun interpolateColor(value: Float): Color {
    // Ensure that the input value is clamped between 0 and 1
    val clampedValue = value.coerceIn(0f, 1f)

    // Red component: starts at 255 (white) and decreases to 0
    val red = (255 * (1 - clampedValue)).toInt()

    // Green component: stays at 255 (since both white and green have full green)
    val green = 255

    // Blue component: starts at 255 (white) and decreases to 0
    val blue = (255 * (1 - clampedValue)).toInt()

    // Construct the color
    return Color(red.toInt(), green.toInt(), blue.toInt())
}


val species_list_show = mutableStateListOf<MutableState<AScore>>()



@SuppressLint("UnrememberedMutableState")
@OptIn(ExperimentalHorologistApi::class)
@Composable
fun SpeciesListView(
    context: Context, appState: AppState, birdHeardState: BirdHeardState, mainState: MainState,
) {


    for (i in 1..3) {
        val hi = mutableStateOf(AScore("", 0.0F, 0L))
        species_list_show.add(hi);
    }
    SpeciesList.setSpeciecsShow_list(species_list_show)
    SpeciesList.setMainState(mainState);
    val species_show: SnapshotStateList<MutableState<AScore>> = remember { species_list_show }

//    var sP = scalingParams( maxTransitionArea= 0.25f, minTransitionArea = 0.05f)
//    val columnState = ScalingLazyColumnState(scalingParams = sP);
    var columnState = rememberResponsiveColumnState(
        contentPadding = ScalingLazyColumnDefaults.padding(
            first = ScalingLazyColumnDefaults.ItemType.Text,
            last = ScalingLazyColumnDefaults.ItemType.Chip
        ),
        verticalArrangement = Arrangement.spacedBy(
            space = 1.dp,
            alignment = Alignment.Top,
        ),
    )


    var battery_level = remember { mutableStateOf(getBatteryLevel(context)) }

    LaunchedEffect(key1 = Unit) {
        while (true) {
            battery_level.value = getBatteryLevel(context)
            delay(60000) // Update every minute
        }
    }

    val text_counter = remember { mutableStateOf("Initial text") }
    LaunchedEffect(key1 = true) {
        while (true) {
            // Update the text - you can put your custom logic here
            // For example, showing current time:
            var lag = ((Instant.now().toEpochMilli() - last_message_recv_tstamp) / 1000F).toInt();
            if (last_message_recv_tstamp == 0L) {
                text_counter.value = "No msg recv"
            } else {
                text_counter.value = "${lag}s"
            }

            // Delay for 1 second
            delay(1000)
        }
    }



    ScreenScaffold(
        scrollState = columnState
    ) {
        TimeText(
            timeSource =
            TimeTextDefaults.timeSource(
                DateFormat.getBestDateTimePattern(Locale.getDefault(), "hh:mm")
            ),
            startCurvedContent = {

                curvedComposable {
                    Icon(
                        Icons.Rounded.MusicNote,
                        contentDescription = "",
                        modifier = Modifier.size(14.dp),
                         tint = if (mainState.birdHeardState == BirdHeardState.Hearing
                             ) Color.Green else Color.Black
                    )
                }
                curvedComposable {
                    Icon(
                        if (appState == AppState.Recording) Icons.Rounded.Mic else Icons.Rounded.MicOff,
                        contentDescription = "",
                        modifier = Modifier.size(14.dp)
                    )
                }
            },
            endCurvedContent = {


                curvedText(
                    text = text_counter.value + " · " + battery_level.value+"%",
                    fontSize = TextUnit(value = 14F, type = TextUnitType.Sp)
                )


                //, textAlign = TextAlign.Center)`

            }


        )
        Column(
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier
                .fillMaxSize()
                .align(Alignment.Center)
        ) {

            ScalingLazyColumn(
                modifier = Modifier.fillMaxWidth(),
                columnState = columnState
            ) {
                itemsIndexed(
                    species_show,
                ) { index, aSpec ->
                    var text_decor = TextDecoration.None
                    var text_style = FontStyle.Normal;
                    val currentName = aSpec.value.common_name
                    val isNewEntry = aSpec.value.new_entry
                    val shouldTrigger = aSpec.value.trigger
//                    if (isNewEntry) {
//                        text_style = FontStyle.Italic;
//                        aSpec.value.new_entry = false;
//                    }
                    Log.w(
                        TAG,
                        index.toString() + " " + currentName + " " + isNewEntry.toString() + " " + shouldTrigger.toString()
                    )
                    key(currentName, isNewEntry, shouldTrigger) {
                        if (shouldTrigger) {
                            Log.w(TAG, "Trigger " + aSpec.toString())
                            Row {
                                FlashingText(
                                    text = aSpec.value.common_name,
                                    fontStyle = text_style,
                                    color = interpolateColor(aSpec.value.score),
                                    key = Instant.now().toEpochMilli(),
                                    textDecor = text_decor,
                                    modifier = Modifier.fillMaxSize()
                                )
                                LaunchedEffect(Unit) {
                                    delay(100);
                                    aSpec.value.trigger = false
                                }
                            }

                        } else {
                            Row {
                                AutoSizedText(
                                    text = aSpec.value.common_name,
                                    color = interpolateColor(aSpec.value.score),
                                    modifier = Modifier.fillMaxSize(),
                                    textAlign = TextAlign.Center,
                                    key = Instant.now().toEpochMilli(),
                                    textDecor = text_decor,
                                    fontStyle = text_style,
                                )
                            }
                            Log.e("TAG", "Not blinking")
                        }
                    }
                }
            }
        }

    }
}

// Get current battery level
private fun getBatteryLevel(context: Context): Int {
    val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { iFilter ->
        context.registerReceiver(null, iFilter)
    }

    val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
    val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1

    return if (level != -1 && scale != -1) {
        level * 100 / scale
    } else {
        -1
    }
}
