package com.module.breeze

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Map
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
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.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.module.breeze.ui.theme.BreezeTheme
import kotlinx.coroutines.flow.first
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

var plzArrayStatus: List<String> = listOf(
  "Loading...",
  "Loading...",
  "Loading...",
  "Loading...",
  "Loading...",
  "Loading...",
  "Loading...",
)

val defaultPlzList = listOf("8005", "8005", "8005", "8400", "8400", "8500", "8500")

// ### Start ChatGPT + Fixing
val SHARED_PLZ_KEY = stringPreferencesKey("shared-plz")
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

suspend fun setLocations(context: Context, array: List<String>) {
  context.dataStore.edit { preferences ->
    preferences[SHARED_PLZ_KEY] = Json.encodeToString(array)
  }
}

suspend fun getLocations(context: Context): List<String> {
  val preferences = context.dataStore.data.first()
  return preferences[SHARED_PLZ_KEY]?.let { Json.decodeFromString(it) } ?: defaultPlzList
}
// ### End ChatGPT

suspend fun getPLZ(index: Int, ctx: Context): String {
  var arr = getLocations(ctx)
  if (arr.isEmpty() || arr.size != 7) {
    arr = defaultPlzList
  }
  plzArrayStatus = arr
  return arr[index]
}

suspend fun setPLZ(index: Int, value: String, ctx: Context) {
  var arr = plzArrayStatus.toMutableList()
  arr[index] = value
  setLocations(ctx, arr)
}

class SettingsActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    enableEdgeToEdge()
    setContent {
      BreezeTheme {
        Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
          Settings(
            modifier = Modifier.padding(innerPadding),
          )
        }
      }
    }
  }

  companion object {
    fun openHome(ctx: Context) {
      var intent = Intent(ctx, MainActivity::class.java)
      ctx.startActivity(intent)
    }
  }
}

@Composable
fun Settings(modifier: Modifier = Modifier) {
  val ctx = LocalContext.current

  Navigation(
    iconStyle.Home,
    "Home Icon",
    onClick = { SettingsActivity.openHome(ctx) },
  )
  Column(
    modifier = Modifier.fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally,
  ) {
    Row(
      verticalAlignment = Alignment.CenterVertically,
      modifier = Modifier.padding(16.dp),
    ) {
      Icon(
        imageVector = iconStyle.Map,
        contentDescription = "Configured Locations Icon",
        modifier = Modifier.size(40.dp),
      )
      Text(
        text = "Configured Locations",
        fontWeight = breezeFontWeight,
        fontSize = fontSizeTitle,
      )
    }
    ConfiguredLocationDay("Monday", 0, ctx)
    ConfiguredLocationDay("Tuesday", 1, ctx)
    ConfiguredLocationDay("Wednesday", 2, ctx)
    ConfiguredLocationDay("Thursday", 3, ctx)
    ConfiguredLocationDay("Friday", 4, ctx)
    ConfiguredLocationDay("Saturday", 5, ctx)
    ConfiguredLocationDay("Sunday", 6, ctx)
  }
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview2() {
  BreezeTheme {
    Settings()
  }
}

@Composable
fun ConfiguredLocationDay(dayName: String = "day", index: Int, ctx: Context) {
  var plz by remember { mutableStateOf("") }
  var isLoadingGet by remember { mutableStateOf(false) }
  var isLoadingSet by remember { mutableStateOf(false) }

  LaunchedEffect(index) {
    isLoadingGet = true
    plz = getPLZ(index, ctx)
    isLoadingGet = false
  }

  LaunchedEffect(plz) {
    if (plz.length == 4) {
      isLoadingSet = true
      setPLZ(index, plz, ctx)
      isLoadingSet = false
    }
  }

  if (isLoadingSet || isLoadingGet) {
    CircularProgressIndicator()
  } else {
    Row(
      verticalAlignment = Alignment.CenterVertically,
      modifier = Modifier.padding(0.dp, 4.dp),
    ) {
      Text(
        text = dayName,
        fontWeight = breezeFontWeight,
        modifier = Modifier.width(100.dp),
      )
      TextField(
        value = plz,
        onValueChange = { newPlz ->
          var cutNewPlz = newPlz
          if (newPlz.length > 4) {
            cutNewPlz = newPlz.substring(0, 4)
          }
          plz = cutNewPlz
        },
        label = { Text("PLZ") },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
        modifier = Modifier.width(110.dp),
      )
    }
  }
}
