package com.sunzones.ui.main.components

import android.content.Intent
import android.net.Uri
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.clickable
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.KeyboardArrowDown
import androidx.compose.material.icons.rounded.MyLocation
import androidx.compose.material.icons.rounded.WbSunny
import androidx.compose.material.icons.rounded.WbTwilight
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
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.draw.alpha
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.sunzones.R
import com.sunzones.domain.model.MonthDaylight
import com.sunzones.domain.model.SunLocation
import com.sunzones.ui.theme.*
import java.time.format.DateTimeFormatter

private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm")

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SunCard(
    location: SunLocation,
    onDelete: () -> Unit,
    monthlyDaylight: List<MonthDaylight>?,
    modifier: Modifier = Modifier
) {
    var showDeleteDialog by remember { mutableStateOf(false) }
    var showAboutDialog by remember { mutableStateOf(false) }

    val gradientColors = getTimeGradient(location.sunProgress, location.isDaytime)
    val scrollState = rememberScrollState()

    val chevronAlpha by remember {
        derivedStateOf {
            if (scrollState.value == 0) 1f else (1f - (scrollState.value / 100f)).coerceAtLeast(0f)
        }
    }

    BoxWithConstraints(
        modifier = modifier
            .fillMaxSize()
            .background(brush = Brush.verticalGradient(gradientColors))
    ) {
        val pageHeight = maxHeight

        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(scrollState)
        ) {
            // Section 1: Original card content filling one page
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(pageHeight)
                    .combinedClickable(
                        onClick = {},
                        onLongClick = { showDeleteDialog = true }
                    )
                    .statusBarsPadding()
                    .padding(horizontal = 24.dp)
            ) {
                Column(
                    modifier = Modifier.fillMaxSize(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    // Location name
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.Center
                    ) {
                        if (location.isCurrentLocation) {
                            Icon(
                                imageVector = Icons.Rounded.MyLocation,
                                contentDescription = null,
                                tint = TextOnDark,
                                modifier = Modifier
                                    .size(28.dp)
                                    .padding(end = 8.dp)
                            )
                        }
                        Text(
                            text = location.name,
                            style = MaterialTheme.typography.displayMedium.copy(shadow = TextShadowStrong),
                            color = TextOnDark,
                            maxLines = 2
                        )
                    }

                    Spacer(modifier = Modifier.height(32.dp))

                    // Sun/Moon arc with optional moon phase overlay
                    Box(
                        contentAlignment = Alignment.Center
                    ) {
                        SunArc(
                            progress = location.sunProgress,
                            isDaytime = location.isDaytime,
                            nightProgress = location.nightProgress,
                            modifier = Modifier.fillMaxWidth()
                        )

                        // Moon phase overlay — visible at night
                        if (!location.isDaytime) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally,
                                modifier = Modifier.padding(bottom = 24.dp)
                            ) {
                                Text(
                                    text = moonPhaseEmoji(location.moonPhase),
                                    style = MaterialTheme.typography.headlineMedium
                                )
                                Text(
                                    text = "${(location.moonIllumination * 100).toInt()}%",
                                    style = MaterialTheme.typography.bodyMedium.copy(shadow = TextShadowDefault),
                                    color = MoonSilver
                                )
                            }
                        }
                    }

                    Spacer(modifier = Modifier.height(32.dp))

                    // Hero element — day length or night length
                    if (location.isDaytime) {
                        Text(
                            text = location.dayLengthFormatted,
                            style = MaterialTheme.typography.displayLarge.copy(shadow = TextShadowStrong),
                            color = TextOnDark,
                            fontWeight = FontWeight.Black
                        )
                        Text(
                            text = stringResource(R.string.day_length),
                            style = MaterialTheme.typography.titleMedium.copy(shadow = TextShadowDefault),
                            color = TextOnDarkSecondary
                        )
                    } else {
                        Text(
                            text = location.nightLengthFormatted,
                            style = MaterialTheme.typography.displayLarge.copy(shadow = TextShadowStrong),
                            color = TextOnDark,
                            fontWeight = FontWeight.Black
                        )
                        Text(
                            text = stringResource(R.string.night_length),
                            style = MaterialTheme.typography.titleMedium.copy(shadow = TextShadowDefault),
                            color = TextOnDarkSecondary
                        )
                        if (location.sunriseCountdownFormatted != null) {
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = stringResource(R.string.sunrise_in, location.sunriseCountdownFormatted),
                                style = MaterialTheme.typography.titleSmall.copy(shadow = TextShadowDefault),
                                color = SunGold.copy(alpha = 0.8f)
                            )
                        }
                    }

                    Spacer(modifier = Modifier.height(24.dp))

                    // Sunrise / Sunset times
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceEvenly
                    ) {
                        // Sunrise
                        Column(horizontalAlignment = Alignment.CenterHorizontally) {
                            Icon(
                                imageVector = Icons.Rounded.WbSunny,
                                contentDescription = stringResource(R.string.sunrise),
                                tint = SunGold,
                                modifier = Modifier.size(28.dp)
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = location.sunrise?.format(timeFormatter) ?: "--:--",
                                style = MaterialTheme.typography.headlineMedium.copy(shadow = TextShadowStrong),
                                color = TextOnDark,
                                fontWeight = FontWeight.Bold
                            )
                            Text(
                                text = stringResource(R.string.sunrise),
                                style = MaterialTheme.typography.bodyMedium.copy(shadow = TextShadowDefault),
                                color = TextOnDarkSecondary
                            )
                        }

                        // Sunset
                        Column(horizontalAlignment = Alignment.CenterHorizontally) {
                            Icon(
                                imageVector = Icons.Rounded.WbTwilight,
                                contentDescription = stringResource(R.string.sunset),
                                tint = SunOrange,
                                modifier = Modifier.size(28.dp)
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = location.sunset?.format(timeFormatter) ?: "--:--",
                                style = MaterialTheme.typography.headlineMedium.copy(shadow = TextShadowStrong),
                                color = TextOnDark,
                                fontWeight = FontWeight.Bold
                            )
                            Text(
                                text = stringResource(R.string.sunset),
                                style = MaterialTheme.typography.bodyMedium.copy(shadow = TextShadowDefault),
                                color = TextOnDarkSecondary
                            )
                        }
                    }
                }

                // Scroll-down chevron indicator
                if (monthlyDaylight != null) {
                    val infiniteTransition = rememberInfiniteTransition(label = "chevron_bounce")
                    val bounceOffset by infiniteTransition.animateFloat(
                        initialValue = 0f,
                        targetValue = 8f,
                        animationSpec = infiniteRepeatable(
                            animation = tween(durationMillis = 1000),
                            repeatMode = RepeatMode.Reverse
                        ),
                        label = "chevron_offset"
                    )

                    Icon(
                        imageVector = Icons.Rounded.KeyboardArrowDown,
                        contentDescription = null,
                        tint = TextOnDarkSecondary,
                        modifier = Modifier
                            .align(Alignment.BottomCenter)
                            .padding(bottom = 24.dp)
                            .offset { IntOffset(0, bounceOffset.dp.roundToPx()) }
                            .alpha(chevronAlpha)
                            .size(32.dp)
                    )
                }
            }

            // Section 2: Yearly daylight chart (below fold)
            if (monthlyDaylight != null) {
                YearlyDaylightChart(
                    monthlyDaylight = monthlyDaylight,
                    modifier = Modifier.padding(top = 8.dp)
                )

                // Space for navigation bar + page indicator (80dp offset + 8dp height) + FAB
                Spacer(
                    modifier = Modifier
                        .navigationBarsPadding()
                        .height(112.dp)
                )

                // Subtle about button at the very bottom
                Box(
                    modifier = Modifier.fillMaxWidth(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = stringResource(R.string.about_title),
                        style = MaterialTheme.typography.bodySmall,
                        color = TextOnDarkSecondary.copy(alpha = 0.35f),
                        modifier = Modifier
                            .clickable { showAboutDialog = true }
                            .padding(vertical = 12.dp, horizontal = 24.dp)
                    )
                }
            }
        }
    }

    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text(stringResource(R.string.delete_location_title)) },
            text = { Text(stringResource(R.string.delete_location_message, location.name)) },
            confirmButton = {
                TextButton(onClick = {
                    showDeleteDialog = false
                    onDelete()
                }) {
                    Text(stringResource(R.string.delete))
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteDialog = false }) {
                    Text(stringResource(R.string.cancel))
                }
            }
        )
    }

    if (showAboutDialog) {
        val context = LocalContext.current
        val email = stringResource(R.string.about_email)
        AlertDialog(
            onDismissRequest = { showAboutDialog = false },
            title = { Text(stringResource(R.string.app_name)) },
            text = {
                Column {
                    Text(stringResource(R.string.about_made_in))
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = email,
                        color = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.clickable {
                            context.startActivity(
                                Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$email"))
                            )
                        }
                    )
                }
            },
            confirmButton = {
                TextButton(onClick = { showAboutDialog = false }) {
                    Text(stringResource(R.string.ok))
                }
            }
        )
    }
}

private fun getTimeGradient(sunProgress: Float, isDaytime: Boolean): List<Color> {
    if (!isDaytime) return listOf(NightTop, NightBottom)

    return when {
        sunProgress < 0.1f -> listOf(SunriseTop, SunriseBottom)
        sunProgress < 0.3f -> listOf(MorningTop, MorningBottom)
        sunProgress < 0.7f -> listOf(MiddayTop, MiddayBottom)
        sunProgress < 0.85f -> listOf(AfternoonTop, AfternoonBottom)
        sunProgress < 0.95f -> listOf(SunsetTop, SunsetBottom)
        else -> listOf(TwilightTop, TwilightBottom)
    }
}

private fun moonPhaseEmoji(degrees: Double): String {
    // degrees: -180..180 where 0=new moon, 90=first quarter, 180/-180=full, -90=last quarter
    val normalized = ((degrees % 360) + 360) % 360 // normalize to 0..360
    return when {
        normalized < 22.5 -> "\uD83C\uDF11"   // 🌑 New moon
        normalized < 67.5 -> "\uD83C\uDF12"   // 🌒 Waxing crescent
        normalized < 112.5 -> "\uD83C\uDF13"  // 🌓 First quarter
        normalized < 157.5 -> "\uD83C\uDF14"  // 🌔 Waxing gibbous
        normalized < 202.5 -> "\uD83C\uDF15"  // 🌕 Full moon
        normalized < 247.5 -> "\uD83C\uDF16"  // 🌖 Waning gibbous
        normalized < 292.5 -> "\uD83C\uDF17"  // 🌗 Last quarter
        normalized < 337.5 -> "\uD83C\uDF18"  // 🌘 Waning crescent
        else -> "\uD83C\uDF11"                 // 🌑 New moon
    }
}
