package com.aicrus.firebase.kit

import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
import androidx.glance.Image
import androidx.glance.ImageProvider
import androidx.glance.LocalSize
import androidx.glance.action.clickable
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.SizeMode
import androidx.glance.appwidget.action.actionRunCallback
import androidx.glance.appwidget.provideContent
import androidx.glance.background
import androidx.glance.currentState
import androidx.glance.layout.Alignment
import androidx.glance.layout.Box
import androidx.glance.layout.Column
import androidx.glance.layout.ContentScale
import androidx.glance.layout.Row
import androidx.glance.layout.Spacer
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.fillMaxWidth
import androidx.glance.layout.padding
import androidx.glance.layout.size
import androidx.glance.state.GlanceStateDefinition
import androidx.glance.text.FontStyle
import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextStyle
import androidx.glance.unit.ColorProvider
import es.antonborri.home_widget.HomeWidgetGlanceState
import es.antonborri.home_widget.HomeWidgetGlanceStateDefinition
import java.util.Calendar
import java.util.Locale

class MyWidgetWidget : GlanceAppWidget() {

  // Recompose when the user resizes the widget so the layout can adapt
  // between small (no "+", no quote) and large (everything visible).
  override val sizeMode: SizeMode = SizeMode.Exact

  override val stateDefinition: GlanceStateDefinition<*>?
    get() = HomeWidgetGlanceStateDefinition()

  override suspend fun provideGlance(context: Context, id: GlanceId) {
    provideContent {
      GlanceContent(context, currentState())
    }
  }

  @Composable
  private fun GlanceContent(context: Context, currentState: HomeWidgetGlanceState) {
    val prefs = currentState.preferences
    val storedGreeting = prefs.getString("greeting", "") ?: ""
    val storedTitle = prefs.getString("title", "") ?: ""
    val planText = prefs.getString("planText", "") ?: ""
    val isPro = prefs.getString("isPro", "false") == "true"
    val quote = prefs.getString("quote", "") ?: ""

    // Time/locale-based fallback used when Flutter has not pushed data yet —
    // first install before the app opens. Keeps the widget from rendering
    // blank in the gallery preview.
    val defaults = defaultStrings()
    val greeting = storedGreeting.ifEmpty { defaults.greeting }
    val title = storedTitle.ifEmpty { defaults.hello }

    val size = LocalSize.current
    val isSmall = size.width < 200.dp
    // Heuristic: tall enough to fit greeting + title + quote without crowding.
    val isLarge = size.height >= 280.dp

    val white = Color.White
    val whiteSubtle = Color(red = 1f, green = 1f, blue = 1f, alpha = 0.55f)
    val whiteQuote = Color(red = 1f, green = 1f, blue = 1f, alpha = 0.65f)
    val gold = Color(red = 1f, green = 0.84f, blue = 0f)
    val whiteVerySubtle = Color(red = 1f, green = 1f, blue = 1f, alpha = 0.45f)

    // The gradient lives in its own Image at the bottom of the stack rather
    // than as `.background(ImageProvider(...))`, because in some Glance
    // versions the latter ends up rendered ABOVE the content — the widget
    // shows just the gradient, no text. The explicit Image+Column layering
    // here is deterministic.
    Box(
      modifier = GlanceModifier
        .fillMaxSize()
        .clickable(actionRunCallback<OpenAppAction>()),
    ) {
      Image(
        provider = ImageProvider(R.drawable.widget_gradient_inner),
        contentDescription = null,
        contentScale = ContentScale.FillBounds,
        modifier = GlanceModifier.fillMaxSize(),
      )
      Column(
        modifier = GlanceModifier.fillMaxSize().padding(16.dp),
      ) {
        Text(
          text = greeting,
          style = TextStyle(
            color = ColorProvider(whiteSubtle),
            fontSize = 11.sp,
            fontWeight = FontWeight.Medium,
          ),
        )
        Text(
          text = title,
          style = TextStyle(
            color = ColorProvider(white),
            fontSize = if (isSmall) 20.sp else 24.sp,
            fontWeight = FontWeight.Bold,
          ),
          modifier = GlanceModifier.padding(top = 4.dp),
        )
        if (isLarge && quote.isNotEmpty()) {
          Text(
            text = quote,
            style = TextStyle(
              color = ColorProvider(whiteQuote),
              fontSize = 15.sp,
              fontWeight = FontWeight.Normal,
              fontStyle = FontStyle.Italic,
            ),
            maxLines = 4,
            modifier = GlanceModifier.padding(top = 12.dp),
          )
        }
        Spacer(modifier = GlanceModifier.defaultWeight())
        Row(
          modifier = GlanceModifier.fillMaxWidth(),
          verticalAlignment = Alignment.CenterVertically,
        ) {
          // Empty planText hides the pill (used in logged-out state).
          if (planText.isNotEmpty()) {
            PlanPill(
              isPro = isPro,
              planText = planText,
              gold = gold,
              whiteVerySubtle = whiteVerySubtle,
            )
          }
          // Small intentionally drops the "+" so the layout breathes —
          // the pill sits flush left like the original design.
          if (!isSmall) {
            Spacer(modifier = GlanceModifier.defaultWeight())
            Image(
              provider = ImageProvider(R.drawable.widget_add_button),
              contentDescription = "Add",
              modifier = GlanceModifier
                .size(34.dp)
                .clickable(actionRunCallback<OpenAppAction>()),
            )
          }
        }
      }
    }
  }

  @Composable
  private fun PlanPill(
    isPro: Boolean,
    planText: String,
    gold: Color,
    whiteVerySubtle: Color,
  ) {
    if (isPro) {
      Box(
        modifier = GlanceModifier
          .background(ImageProvider(R.drawable.widget_pro_pill_bg))
          .padding(horizontal = 10.dp, vertical = 5.dp),
      ) {
        Text(
          text = "⭐ $planText",
          style = TextStyle(
            color = ColorProvider(gold),
            fontSize = 11.sp,
            fontWeight = FontWeight.Bold,
          ),
        )
      }
    } else {
      Box(
        modifier = GlanceModifier
          .background(ImageProvider(R.drawable.widget_plan_pill_bg))
          .padding(horizontal = 10.dp, vertical = 5.dp),
      ) {
        Text(
          text = planText,
          style = TextStyle(
            color = ColorProvider(whiteVerySubtle),
            fontSize = 11.sp,
            fontWeight = FontWeight.Medium,
          ),
        )
      }
    }
  }

  private data class DefaultStrings(val greeting: String, val hello: String)

  private fun defaultStrings(): DefaultStrings {
    val hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
    val lang = Locale.getDefault().language
    val morning: String; val afternoon: String; val evening: String; val hello: String
    when (lang) {
      "pt" -> { morning = "Bom dia"; afternoon = "Boa tarde"; evening = "Boa noite"; hello = "Olá!" }
      "es" -> { morning = "Buenos días"; afternoon = "Buenas tardes"; evening = "Buenas noches"; hello = "¡Hola!" }
      else -> { morning = "Good morning"; afternoon = "Good afternoon"; evening = "Good evening"; hello = "Hi there!" }
    }
    val greeting = when {
      hour < 12 -> morning
      hour < 18 -> afternoon
      else -> evening
    }
    return DefaultStrings(greeting, hello)
  }
}
