package com.tt.honeyDue.ui.theme

import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Eco
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
import kotlin.random.Random

// MARK: - Organic Design System
// Warm, natural aesthetic with soft shapes, subtle textures, and flowing layouts

// MARK: - Organic Shapes

/**
 * Soft organic blob shape for backgrounds
 * Matches iOS OrganicBlobShape
 */
class OrganicBlobShape(private val variation: Int = 0) : Shape {
    override fun createOutline(
        size: Size,
        layoutDirection: androidx.compose.ui.unit.LayoutDirection,
        density: androidx.compose.ui.unit.Density
    ): Outline {
        val path = Path()
        val w = size.width
        val h = size.height

        when (variation % 3) {
            0 -> {
                // Soft cloud-like blob
                path.moveTo(w * 0.1f, h * 0.5f)
                path.cubicTo(
                    w * 0.0f, h * 0.1f,
                    w * 0.25f, h * 0.0f,
                    w * 0.5f, h * 0.05f
                )
                path.cubicTo(
                    w * 0.75f, h * 0.1f,
                    w * 1.0f, h * 0.25f,
                    w * 0.95f, h * 0.45f
                )
                path.cubicTo(
                    w * 0.9f, h * 0.7f,
                    w * 0.8f, h * 0.95f,
                    w * 0.55f, h * 0.95f
                )
                path.cubicTo(
                    w * 0.25f, h * 0.95f,
                    w * 0.05f, h * 0.75f,
                    w * 0.1f, h * 0.5f
                )
            }
            1 -> {
                // Pebble shape
                path.moveTo(w * 0.15f, h * 0.4f)
                path.cubicTo(
                    w * 0.1f, h * 0.15f,
                    w * 0.35f, h * 0.05f,
                    w * 0.6f, h * 0.08f
                )
                path.cubicTo(
                    w * 0.85f, h * 0.12f,
                    w * 0.95f, h * 0.35f,
                    w * 0.9f, h * 0.55f
                )
                path.cubicTo(
                    w * 0.85f, h * 0.8f,
                    w * 0.65f, h * 0.95f,
                    w * 0.45f, h * 0.92f
                )
                path.cubicTo(
                    w * 0.2f, h * 0.88f,
                    w * 0.08f, h * 0.65f,
                    w * 0.15f, h * 0.4f
                )
            }
            else -> {
                // Leaf-like shape
                path.moveTo(w * 0.05f, h * 0.5f)
                path.cubicTo(
                    w * 0.05f, h * 0.2f,
                    w * 0.25f, h * 0.02f,
                    w * 0.5f, h * 0.02f
                )
                path.cubicTo(
                    w * 0.75f, h * 0.02f,
                    w * 0.95f, h * 0.2f,
                    w * 0.95f, h * 0.5f
                )
                path.cubicTo(
                    w * 0.95f, h * 0.8f,
                    w * 0.75f, h * 0.98f,
                    w * 0.5f, h * 0.98f
                )
                path.cubicTo(
                    w * 0.25f, h * 0.98f,
                    w * 0.05f, h * 0.8f,
                    w * 0.05f, h * 0.5f
                )
            }
        }

        path.close()
        return Outline.Generic(path)
    }
}

/**
 * Super soft rounded rectangle for organic cards
 * Uses continuous corner radius matching iOS .continuous style
 */
val OrganicRoundedShape = RoundedCornerShape(28.dp)

// MARK: - Grain Texture Overlay

/**
 * Grain texture overlay for natural feel
 * Matches iOS GrainTexture
 */
@Composable
fun GrainTexture(
    modifier: Modifier = Modifier,
    opacity: Float = 0.03f
) {
    val grainColor = Color.Black.copy(alpha = opacity)

    Canvas(modifier = modifier.fillMaxSize()) {
        val density = size.width * size.height / 50
        val random = Random(42) // Fixed seed for consistent pattern

        repeat(density.toInt().coerceAtMost(5000)) {
            val x = random.nextFloat() * size.width
            val y = random.nextFloat() * size.height
            val grainOpacity = random.nextFloat() * 0.7f + 0.3f

            drawCircle(
                color = grainColor.copy(alpha = grainColor.alpha * grainOpacity),
                radius = 0.5f,
                center = Offset(x, y)
            )
        }
    }
}

// MARK: - Organic Card Background

/**
 * Organic card background with subtle accent blob and grain texture
 * Matches iOS OrganicCardBackground
 */
@Composable
fun OrganicCardBackground(
    modifier: Modifier = Modifier,
    accentColor: Color = MaterialTheme.colorScheme.primary,
    showBlob: Boolean = true,
    blobVariation: Int = 0
) {
    Box(modifier = modifier) {
        // Main card fill
        Box(
            modifier = Modifier
                .fillMaxSize()
                .clip(OrganicRoundedShape)
                .background(MaterialTheme.colorScheme.backgroundSecondary)
        )

        // Subtle accent blob in corner
        if (showBlob) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .clip(OrganicRoundedShape)
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth(0.6f)
                        .fillMaxHeight(0.7f)
                        .offset(x = 80.dp, y = (-20).dp)
                        .align(Alignment.TopEnd)
                        .clip(OrganicBlobShape(blobVariation))
                        .background(
                            brush = Brush.linearGradient(
                                colors = listOf(
                                    accentColor.copy(alpha = 0.08f),
                                    accentColor.copy(alpha = 0.02f)
                                )
                            )
                        )
                        .blur(20.dp)
                )
            }
        }

        // Grain texture
        Box(
            modifier = Modifier
                .fillMaxSize()
                .clip(OrganicRoundedShape)
        ) {
            GrainTexture(opacity = 0.015f)
        }
    }
}

// MARK: - Natural Shadow

/**
 * Shadow intensity levels matching iOS NaturalShadow
 */
enum class ShadowIntensity {
    Subtle,
    Medium,
    Pronounced;

    val elevation: Dp
        get() = when (this) {
            Subtle -> 4.dp
            Medium -> 8.dp
            Pronounced -> 12.dp
        }

    val ambientAlpha: Float
        get() = when (this) {
            Subtle -> 0.04f
            Medium -> 0.08f
            Pronounced -> 0.12f
        }
}

/**
 * Natural shadow modifier matching iOS NaturalShadow
 */
fun Modifier.naturalShadow(
    intensity: ShadowIntensity = ShadowIntensity.Medium,
    shape: Shape = OrganicRoundedShape
): Modifier = this
    .shadow(
        elevation = intensity.elevation,
        shape = shape,
        ambientColor = Color.Black.copy(alpha = intensity.ambientAlpha),
        spotColor = Color.Black.copy(alpha = intensity.ambientAlpha * 0.5f)
    )

// MARK: - Organic Icon Container

/**
 * Icon with soft organic background and inner glow
 * Matches iOS OrganicIconContainer
 *
 * @param icon The icon to display (ImageVector)
 * @param modifier Modifier for the container
 * @param size The size of the container (default 48.dp)
 * @param iconScale Scale of the icon relative to container (default 0.5f)
 * @param iconSize Optional explicit icon size (overrides iconScale if provided)
 * @param backgroundColor Background color for the container
 * @param iconColor Tint color for the icon
 * @param containerColor Alias for backgroundColor (for compatibility)
 * @param iconTint Alias for iconColor (for compatibility)
 * @param gradientColors Optional custom gradient colors (overrides backgroundColor)
 * @param contentDescription Accessibility description
 */
@Composable
fun OrganicIconContainer(
    icon: ImageVector,
    modifier: Modifier = Modifier,
    size: Dp = 48.dp,
    iconScale: Float = 0.5f,
    iconSize: Dp? = null,
    backgroundColor: Color? = null,
    iconColor: Color? = null,
    containerColor: Color? = null,
    iconTint: Color? = null,
    gradientColors: List<Color>? = null,
    contentDescription: String? = null
) {
    // Resolve colors with fallback chain: explicit param -> alias -> default
    val resolvedBackgroundColor = backgroundColor ?: containerColor ?: MaterialTheme.colorScheme.primary
    val resolvedIconColor = iconColor ?: iconTint ?: MaterialTheme.colorScheme.onPrimary

    val actualGradientColors = gradientColors ?: listOf(
        resolvedBackgroundColor,
        resolvedBackgroundColor.copy(alpha = 0.85f)
    )
    val actualIconSize = iconSize ?: (size * iconScale)

    Box(
        modifier = modifier
            .size(size)
            .naturalShadow(ShadowIntensity.Subtle, CircleShape),
        contentAlignment = Alignment.Center
    ) {
        // Soft organic background with radial gradient
        Canvas(modifier = Modifier.fillMaxSize()) {
            drawCircle(
                brush = Brush.radialGradient(
                    colors = actualGradientColors,
                    center = Offset(this.size.width * 0.3f, this.size.height * 0.3f),
                    radius = this.size.maxDimension
                )
            )
        }

        // Inner glow
        Canvas(modifier = Modifier.fillMaxSize()) {
            drawCircle(
                brush = Brush.radialGradient(
                    colors = listOf(
                        Color.White.copy(alpha = 0.2f),
                        Color.Transparent
                    ),
                    center = Offset(this.size.width * 0.3f, this.size.height * 0.3f),
                    radius = this.size.maxDimension * 0.5f
                )
            )
        }

        // Icon
        Icon(
            imageVector = icon,
            contentDescription = contentDescription,
            modifier = Modifier.size(actualIconSize),
            tint = resolvedIconColor
        )
    }
}

// MARK: - Organic Stat Pill

/**
 * Stat display pill with icon and label
 * Matches iOS OrganicStatPill
 */
@Composable
fun OrganicStatPill(
    icon: ImageVector,
    value: String,
    label: String,
    modifier: Modifier = Modifier,
    color: Color = MaterialTheme.colorScheme.primary
) {
    Row(
        modifier = modifier
            .background(
                color = MaterialTheme.colorScheme.backgroundSecondary,
                shape = RoundedCornerShape(50)
            )
            .drawBehind {
                // Border
                drawRoundRect(
                    color = color.copy(alpha = 0.15f),
                    style = androidx.compose.ui.graphics.drawscope.Stroke(width = 1.dp.toPx()),
                    cornerRadius = androidx.compose.ui.geometry.CornerRadius(50.dp.toPx())
                )
            }
            .padding(horizontal = 14.dp, vertical = 10.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // Icon with soft background
        Box(
            modifier = Modifier
                .size(32.dp)
                .background(
                    color = color.copy(alpha = 0.12f),
                    shape = CircleShape
                ),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null, // decorative
                modifier = Modifier.size(13.dp),
                tint = color
            )
        }

        Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
            Text(
                text = value,
                style = MaterialTheme.typography.labelLarge.copy(
                    fontSize = 15.sp,
                    fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
                ),
                color = MaterialTheme.colorScheme.textPrimary
            )
            Text(
                text = label,
                style = MaterialTheme.typography.labelSmall.copy(
                    fontSize = 11.sp,
                    fontWeight = androidx.compose.ui.text.font.FontWeight.Medium
                ),
                color = MaterialTheme.colorScheme.textSecondary
            )
        }
    }
}

// MARK: - Organic Divider

/**
 * Gradient divider that fades at edges
 * Matches iOS OrganicDivider
 */
@Composable
fun OrganicDivider(
    modifier: Modifier = Modifier,
    color: Color = MaterialTheme.colorScheme.textSecondary.copy(alpha = 0.15f),
    height: Dp = 1.dp,
    horizontalPadding: Dp = 0.dp,
    vertical: Boolean = false
) {
    if (vertical) {
        Box(
            modifier = modifier
                .width(1.dp)
                .background(
                    brush = Brush.verticalGradient(
                        colors = listOf(
                            color.copy(alpha = 0f),
                            color,
                            color,
                            color.copy(alpha = 0f)
                        )
                    )
                )
        )
    } else {
        Box(
            modifier = modifier
                .padding(horizontal = horizontalPadding)
                .fillMaxWidth()
                .height(height)
                .background(
                    brush = Brush.horizontalGradient(
                        colors = listOf(
                            color.copy(alpha = 0f),
                            color,
                            color,
                            color.copy(alpha = 0f)
                        )
                    )
                )
        )
    }
}

// MARK: - Warm Gradient Background

/**
 * Screen background with subtle warm gradient and grain
 * Matches iOS WarmGradientBackground
 */
@Composable
fun WarmGradientBackground(
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit = {}
) {
    val isDark = isSystemInDarkTheme()
    val primaryColor = MaterialTheme.colorScheme.primary
    val backgroundColor = MaterialTheme.colorScheme.backgroundPrimary

    Box(modifier = modifier.fillMaxSize()) {
        // Base background
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(backgroundColor)
        )

        // Subtle warm gradient overlay
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(
                            primaryColor.copy(alpha = if (isDark) 0.05f else 0.03f),
                            Color.Transparent
                        ),
                        start = Offset.Zero,
                        end = Offset.Infinite
                    )
                )
        )

        // Grain for natural feel
        GrainTexture(opacity = 0.02f)

        // Content
        content()
    }
}

// MARK: - Organic Card Modifier

/**
 * Organic card styling modifier
 * Matches iOS organicCard view modifier
 */
@Composable
fun Modifier.organicCard(
    accentColor: Color = MaterialTheme.colorScheme.primary,
    showBlob: Boolean = true,
    shadowIntensity: ShadowIntensity = ShadowIntensity.Medium,
    blobVariation: Int = 0
): Modifier = this
    .naturalShadow(shadowIntensity)
    .clip(OrganicRoundedShape)
    .drawBehind {
        // Main fill
        drawRoundRect(
            color = Color.Transparent, // Background handled by OrganicCardBackground
            cornerRadius = androidx.compose.ui.geometry.CornerRadius(28.dp.toPx())
        )
    }

/**
 * Composable wrapper for organic card styling
 */
@Composable
fun OrganicCard(
    modifier: Modifier = Modifier,
    accentColor: Color = MaterialTheme.colorScheme.primary,
    showBlob: Boolean = true,
    shadowIntensity: ShadowIntensity = ShadowIntensity.Medium,
    blobVariation: Int = 0,
    content: @Composable BoxScope.() -> Unit
) {
    Box(
        modifier = modifier.naturalShadow(shadowIntensity, OrganicRoundedShape)
    ) {
        OrganicCardBackground(
            accentColor = accentColor,
            showBlob = showBlob,
            blobVariation = blobVariation
        )
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .clip(OrganicRoundedShape),
            content = content
        )
    }
}

// MARK: - Organic Spacing

/**
 * Organic spacing constants matching iOS OrganicSpacing
 * Provides both semantic names (compact, cozy, etc.) and standard names (xs, sm, etc.)
 */
object OrganicSpacing {
    // Semantic names (original)
    val compact = 8.dp
    val cozy = 20.dp
    val comfortable = 24.dp
    val spacious = 32.dp
    val airy = 40.dp

    // Standard size names (for compatibility)
    val xs = 4.dp
    val sm = 8.dp
    val md = 12.dp
    val lg = 16.dp
    val xl = 24.dp
    val xxl = 32.dp

    // Additional aliases
    val extraSmall = xs
    val small = sm
    val medium = md
    val large = lg
    val extraLarge = xl

    // Extended aliases (matching iOS naming)
    val minimal = 2.dp
    val generous = 48.dp
}

/**
 * Organic radius constants for rounded corners
 * Alias for AppRadius with organic naming
 */
object OrganicRadius {
    val xs = 4.dp
    val sm = 8.dp
    val md = 12.dp
    val lg = 16.dp
    val xl = 20.dp
    val xxl = 24.dp
    val full = 50.dp
}

/**
 * Organic shapes for consistency
 */
object OrganicShapes {
    val extraSmall = RoundedCornerShape(OrganicRadius.xs)
    val small = RoundedCornerShape(OrganicRadius.sm)
    val medium = RoundedCornerShape(OrganicRadius.md)
    val large = RoundedCornerShape(OrganicRadius.lg)
    val extraLarge = RoundedCornerShape(OrganicRadius.xl)
}

// MARK: - Floating Leaf Decoration

/**
 * Animated floating leaf decoration
 * Matches iOS FloatingLeaf
 */
@Composable
fun FloatingLeaf(
    modifier: Modifier = Modifier,
    delay: Int = 0,
    size: Dp = 20.dp,
    color: Color = MaterialTheme.colorScheme.primary
) {
    val infiniteTransition = rememberInfiniteTransition(label = "leaf")

    val rotation by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 15f,
        animationSpec = infiniteRepeatable(
            animation = tween(
                durationMillis = 4000,
                delayMillis = delay,
                easing = FastOutSlowInEasing
            ),
            repeatMode = RepeatMode.Reverse
        ),
        label = "leafRotation"
    )

    val offsetY by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 8f,
        animationSpec = infiniteRepeatable(
            animation = tween(
                durationMillis = 4000,
                delayMillis = delay,
                easing = FastOutSlowInEasing
            ),
            repeatMode = RepeatMode.Reverse
        ),
        label = "leafOffset"
    )

    Icon(
        imageVector = Icons.Default.Eco,
        contentDescription = null, // decorative
        modifier = modifier
            .size(size)
            .rotate(rotation)
            .offset(y = offsetY.dp),
        tint = color.copy(alpha = 0.15f)
    )
}

// MARK: - Organic Button

/**
 * Primary button with organic gradient styling
 */
@Composable
fun OrganicPrimaryButton(
    text: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    isLoading: Boolean = false,
    icon: ImageVector? = null
) {
    val primaryColor = MaterialTheme.colorScheme.primary

    androidx.compose.material3.Button(
        onClick = onClick,
        modifier = modifier
            .fillMaxWidth()
            .height(56.dp),
        enabled = enabled && !isLoading,
        shape = RoundedCornerShape(28.dp),
        colors = androidx.compose.material3.ButtonDefaults.buttonColors(
            containerColor = primaryColor,
            contentColor = MaterialTheme.colorScheme.onPrimary,
            disabledContainerColor = primaryColor.copy(alpha = 0.5f),
            disabledContentColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.7f)
        )
    ) {
        if (isLoading) {
            androidx.compose.material3.CircularProgressIndicator(
                modifier = Modifier.size(24.dp),
                color = MaterialTheme.colorScheme.onPrimary,
                strokeWidth = 2.dp
            )
        } else {
            Row(
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = text,
                    style = MaterialTheme.typography.labelLarge.copy(
                        fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold
                    )
                )
                if (icon != null) {
                    Spacer(modifier = Modifier.width(8.dp))
                    Icon(
                        imageVector = icon,
                        contentDescription = null, // decorative
                        modifier = Modifier.size(20.dp)
                    )
                }
            }
        }
    }
}
