package com.tt.honeyDue.ui.screens

import androidx.compose.animation.core.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.support.enableTestTagsAsResourceId
import com.tt.honeyDue.ui.components.ApiResultHandler
import com.tt.honeyDue.ui.components.common.StatItem
import com.tt.honeyDue.ui.components.residence.TaskStatChip
import com.tt.honeyDue.viewmodel.ResidenceViewModel
import com.tt.honeyDue.viewmodel.TaskViewModel
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.utils.SubscriptionHelper
import com.tt.honeyDue.ui.subscription.UpgradePromptDialog
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.data.LocalDataManager
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun ResidencesScreen(
    onResidenceClick: (Int) -> Unit,
    onAddResidence: () -> Unit,
    onJoinResidence: () -> Unit,
    onLogout: () -> Unit,
    onNavigateToProfile: () -> Unit = {},
    onEditResidence: ((Int) -> Unit)? = null,
    onDeleteResidence: ((Int) -> Unit)? = null,
    onShareResidence: ((Int) -> Unit)? = null,
    shouldRefresh: Boolean = false,
    viewModel: ResidenceViewModel = viewModel { ResidenceViewModel() },
    taskViewModel: TaskViewModel = viewModel { TaskViewModel() }
) {
    val dataManager = LocalDataManager.current
    val myResidencesState by viewModel.myResidencesState.collectAsStateWithLifecycle()
    val totalSummary by dataManager.totalSummary.collectAsStateWithLifecycle()
    var isRefreshing by remember { mutableStateOf(false) }
    var showUpgradePrompt by remember { mutableStateOf(false) }
    var upgradeTriggerKey by remember { mutableStateOf<String?>(null) }

    // Check if screen is blocked (limit=0) - this hides the FAB
    val isBlocked = SubscriptionHelper.isResidencesBlocked()
    // Get current count for checking when adding
    val currentCount = (myResidencesState as? ApiResult.Success)?.data?.residences?.size ?: 0

    // Helper function to check if user can add a property
    fun canAddProperty(): Pair<Boolean, String?> {
        val check = SubscriptionHelper.canAddProperty(currentCount)
        return Pair(check.allowed, check.triggerKey)
    }

    // Track screen view and load data
    LaunchedEffect(Unit) {
        PostHogAnalytics.screen(AnalyticsEvents.RESIDENCE_SCREEN_SHOWN)
        viewModel.loadMyResidences()
        // Also load tasks to ensure summary can be calculated from kanban data
        taskViewModel.loadTasks()
    }

    // Refresh when shouldRefresh flag changes
    LaunchedEffect(shouldRefresh) {
        if (shouldRefresh) {
            viewModel.loadMyResidences(forceRefresh = true)
            taskViewModel.loadTasks(forceRefresh = true)
        }
    }

    // Handle refresh state
    LaunchedEffect(myResidencesState) {
        if (myResidencesState !is ApiResult.Loading) {
            isRefreshing = false
        }
    }

    if (showUpgradePrompt && upgradeTriggerKey != null) {
        UpgradePromptDialog(
            triggerKey = upgradeTriggerKey!!,
            onDismiss = {
                showUpgradePrompt = false
                upgradeTriggerKey = null
            },
            onUpgrade = {
                // TODO: Navigate to subscription purchase screen
                showUpgradePrompt = false
                upgradeTriggerKey = null
            }
        )
    }

    Scaffold(
        modifier = Modifier.enableTestTagsAsResourceId(),
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        stringResource(Res.string.properties_title),
                        fontWeight = FontWeight.Bold
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateToProfile) {
                        Icon(
                            Icons.Default.Settings,
                            contentDescription = stringResource(Res.string.profile_title),
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                },
                actions = {
                    // Only show Join button if not blocked (limit>0)
                    if (!isBlocked.allowed) {
                        IconButton(
                            modifier = Modifier.testTag(AccessibilityIds.Residence.joinButton),
                            onClick = {
                                val (allowed, triggerKey) = canAddProperty()
                                if (allowed) {
                                    onJoinResidence()
                                } else {
                                    upgradeTriggerKey = triggerKey
                                    showUpgradePrompt = true
                                }
                            }
                        ) {
                            Icon(Icons.Default.GroupAdd, contentDescription = stringResource(Res.string.properties_join_title))
                        }
                    }
                    // Add property button
                    if (!isBlocked.allowed) {
                        IconButton(
                            modifier = Modifier.testTag(AccessibilityIds.Residence.addButton),
                            onClick = {
                                val (allowed, triggerKey) = canAddProperty()
                                if (allowed) {
                                    onAddResidence()
                                } else {
                                    upgradeTriggerKey = triggerKey
                                    showUpgradePrompt = true
                                }
                            }
                        ) {
                            Icon(
                                Icons.Default.AddCircle,
                                contentDescription = stringResource(Res.string.properties_add_button),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        },
        floatingActionButton = {
            // Only show FAB when there are properties and NOT blocked (limit>0)
            val hasResidences = myResidencesState is ApiResult.Success &&
                (myResidencesState as ApiResult.Success).data.residences.isNotEmpty()

            if (hasResidences && !isBlocked.allowed) {
                Box(modifier = Modifier.padding(bottom = 80.dp)) {
                    FloatingActionButton(
                        modifier = Modifier.testTag(AccessibilityIds.Residence.addFab),
                        onClick = {
                            val (allowed, triggerKey) = canAddProperty()
                            if (allowed) {
                                onAddResidence()
                            } else {
                                upgradeTriggerKey = triggerKey
                                showUpgradePrompt = true
                            }
                        },
                        containerColor = MaterialTheme.colorScheme.primary,
                        elevation = FloatingActionButtonDefaults.elevation(
                            defaultElevation = 8.dp,
                            pressedElevation = 12.dp
                        )
                    ) {
                        Icon(
                            Icons.Default.Add,
                            contentDescription = stringResource(Res.string.properties_add_button),
                            tint = MaterialTheme.colorScheme.onPrimary
                        )
                    }
                }
            }
        },
        floatingActionButtonPosition = FabPosition.End
    ) { paddingValues ->
        ApiResultHandler(
            state = myResidencesState,
            onRetry = { viewModel.loadMyResidences() },
            modifier = Modifier.padding(paddingValues),
            errorTitle = stringResource(Res.string.error_generic)
        ) { response ->
                if (response.residences.isEmpty()) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(paddingValues)
                            .testTag(AccessibilityIds.Residence.emptyStateView),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy),
                            modifier = Modifier.padding(OrganicSpacing.comfortable)
                        ) {
                            OrganicIconContainer(
                                icon = Icons.Default.Home,
                                size = 80.dp,
                                iconScale = 0.6f,
                                backgroundColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)
                            )
                            Text(
                                stringResource(Res.string.properties_empty_title),
                                style = MaterialTheme.typography.headlineSmall,
                                fontWeight = FontWeight.SemiBold
                            )
                            Text(
                                stringResource(Res.string.properties_empty_subtitle),
                                style = MaterialTheme.typography.bodyLarge,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Spacer(modifier = Modifier.height(OrganicSpacing.compact))
                            // Only show Add Property button if not blocked (limit>0)
                            if (!isBlocked.allowed) {
                                Button(
                                    onClick = {
                                        val (allowed, triggerKey) = canAddProperty()
                                        if (allowed) {
                                            onAddResidence()
                                        } else {
                                            upgradeTriggerKey = triggerKey
                                            showUpgradePrompt = true
                                        }
                                    },
                                    modifier = Modifier
                                        .fillMaxWidth(0.7f)
                                        .height(56.dp)
                                        .testTag(AccessibilityIds.Residence.emptyStateButton),
                                    shape = RoundedCornerShape(AppRadius.md)
                                ) {
                                    Row(
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Icon(Icons.Default.Add, contentDescription = null) // decorative
                                        Text(
                                            stringResource(Res.string.properties_add_button),
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.SemiBold
                                        )
                                    }
                                }
                                Spacer(modifier = Modifier.height(OrganicSpacing.compact))
                                OutlinedButton(
                                    onClick = {
                                        val (allowed, triggerKey) = canAddProperty()
                                        if (allowed) {
                                            onJoinResidence()
                                        } else {
                                            upgradeTriggerKey = triggerKey
                                            showUpgradePrompt = true
                                        }
                                    },
                                    modifier = Modifier
                                        .fillMaxWidth(0.7f)
                                        .height(56.dp),
                                    shape = RoundedCornerShape(AppRadius.md)
                                ) {
                                    Row(
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Icon(Icons.Default.GroupAdd, contentDescription = null) // decorative
                                        Text(
                                            stringResource(Res.string.properties_join_button),
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.SemiBold
                                        )
                                    }
                                }
                            } else {
                                // Show upgrade prompt when limit=0
                                Button(
                                    onClick = {
                                        upgradeTriggerKey = isBlocked.triggerKey
                                        showUpgradePrompt = true
                                    },
                                    modifier = Modifier
                                        .fillMaxWidth(0.7f)
                                        .height(56.dp),
                                    shape = RoundedCornerShape(AppRadius.md)
                                ) {
                                    Row(
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Icon(Icons.Default.Star, contentDescription = null) // decorative
                                        Text(
                                            "Upgrade to Add",
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.SemiBold
                                        )
                                    }
                                }
                            }
                        }
                    }
                } else {
                    PullToRefreshBox(
                        isRefreshing = isRefreshing,
                        onRefresh = {
                            isRefreshing = true
                            viewModel.loadMyResidences(forceRefresh = true)
                            taskViewModel.loadTasks(forceRefresh = true)
                        },
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(paddingValues)
                    ) {
                        LazyColumn(
                            modifier = Modifier
                                .fillMaxSize()
                                .testTag(AccessibilityIds.Residence.residencesList),
                            contentPadding = PaddingValues(
                                start = OrganicSpacing.cozy,
                                end = OrganicSpacing.cozy,
                                top = OrganicSpacing.cozy,
                                bottom = 96.dp
                            ),
                            verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
                        ) {
                        // Summary Card
                        item {
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                accentColor = MaterialTheme.colorScheme.primary,
                                showBlob = true,
                                blobVariation = 0,
                                shadowIntensity = ShadowIntensity.Medium
                            ) {
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(OrganicSpacing.cozy),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
                                ) {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Icon(
                                            Icons.Default.Dashboard,
                                            contentDescription = null, // decorative
                                            tint = MaterialTheme.colorScheme.primary,
                                            modifier = Modifier.size(24.dp)
                                        )
                                        Spacer(modifier = Modifier.width(OrganicSpacing.compact))
                                        Text(
                                            text = stringResource(Res.string.home_overview),
                                            style = MaterialTheme.typography.titleLarge,
                                            fontWeight = FontWeight.Bold,
                                            color = MaterialTheme.colorScheme.textPrimary
                                        )
                                    }

                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.SpaceEvenly
                                    ) {
                                        StatItem(
                                            icon = Icons.Default.Home,
                                            value = "${totalSummary?.totalResidences ?: response.residences.size}",
                                            label = stringResource(Res.string.home_properties)
                                        )
                                        StatItem(
                                            icon = Icons.Default.Assignment,
                                            value = "${totalSummary?.totalTasks ?: 0}",
                                            label = stringResource(Res.string.home_total_tasks)
                                        )
                                    }

                                    OrganicDivider(
                                        color = MaterialTheme.colorScheme.textSecondary.copy(alpha = 0.2f)
                                    )

                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.SpaceEvenly
                                    ) {
                                        StatItem(
                                            icon = Icons.Default.Warning,
                                            value = "${totalSummary?.totalOverdue ?: 0}",
                                            label = stringResource(Res.string.home_overdue),
                                            valueColor = if ((totalSummary?.totalOverdue ?: 0) > 0) MaterialTheme.colorScheme.error else null
                                        )
                                        StatItem(
                                            icon = Icons.Default.CalendarToday,
                                            value = "${totalSummary?.tasksDueNextWeek ?: 0}",
                                            label = stringResource(Res.string.home_due_this_week)
                                        )
                                        StatItem(
                                            icon = Icons.Default.Event,
                                            value = "${totalSummary?.tasksDueNextMonth ?: 0}",
                                            label = stringResource(Res.string.home_next_30_days)
                                        )
                                    }
                                }
                            }
                        }

                        // Properties Header
                        item {
                            Text(
                                text = stringResource(Res.string.home_your_properties),
                                style = MaterialTheme.typography.titleLarge,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier.padding(top = OrganicSpacing.compact)
                            )
                        }

                        // Residences
                        items(response.residences) { residence ->
                            val hasOverdue = residence.overdueCount > 0
                            var showContextMenu by remember { mutableStateOf(false) }

                            // Pulsing animation for overdue indicator
                            val infiniteTransition = rememberInfiniteTransition(label = "pulse")
                            val pulseScale by infiniteTransition.animateFloat(
                                initialValue = 1f,
                                targetValue = 1.15f,
                                animationSpec = infiniteRepeatable(
                                    animation = tween(800, easing = EaseInOut),
                                    repeatMode = RepeatMode.Reverse
                                ),
                                label = "pulseScale"
                            )

                            OrganicCard(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .testTag(AccessibilityIds.withId(AccessibilityIds.Residence.residenceCard, residence.id))
                                    .combinedClickable(
                                        onClick = { onResidenceClick(residence.id) },
                                        onLongClick = {
                                            if (onEditResidence != null || onDeleteResidence != null || onShareResidence != null) {
                                                showContextMenu = true
                                            }
                                        }
                                    ),
                                accentColor = if (hasOverdue) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary,
                                showBlob = true,
                                blobVariation = residence.id % 3,
                                shadowIntensity = ShadowIntensity.Subtle
                            ) {
                                // Long-press context menu
                                DropdownMenu(
                                    expanded = showContextMenu,
                                    onDismissRequest = { showContextMenu = false },
                                    modifier = Modifier.testTag(AccessibilityIds.Residence.contextMenu)
                                ) {
                                    onEditResidence?.let { handler ->
                                        DropdownMenuItem(
                                            text = { Text(stringResource(Res.string.common_edit)) },
                                            leadingIcon = { Icon(Icons.Default.Edit, contentDescription = null) },
                                            onClick = {
                                                handler(residence.id)
                                                showContextMenu = false
                                            }
                                        )
                                    }
                                    onShareResidence?.let { handler ->
                                        DropdownMenuItem(
                                            text = { Text(stringResource(Res.string.common_share)) },
                                            leadingIcon = { Icon(Icons.Default.Share, contentDescription = null) },
                                            onClick = {
                                                handler(residence.id)
                                                showContextMenu = false
                                            }
                                        )
                                    }
                                    onDeleteResidence?.let { handler ->
                                        DropdownMenuItem(
                                            text = { Text(stringResource(Res.string.common_delete)) },
                                            leadingIcon = {
                                                Icon(
                                                    Icons.Default.Delete,
                                                    contentDescription = null,
                                                    tint = MaterialTheme.colorScheme.error
                                                )
                                            },
                                            onClick = {
                                                handler(residence.id)
                                                showContextMenu = false
                                            }
                                        )
                                    }
                                }
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(OrganicSpacing.cozy)
                                ) {
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        // Pulsing organic icon container when overdue
                                        Box(
                                            modifier = if (hasOverdue) Modifier.scale(pulseScale) else Modifier
                                        ) {
                                            OrganicIconContainer(
                                                icon = Icons.Default.Home,
                                                size = 56.dp,
                                                iconScale = 0.5f,
                                                backgroundColor = if (hasOverdue)
                                                    MaterialTheme.colorScheme.errorContainer
                                                else
                                                    MaterialTheme.colorScheme.primaryContainer,
                                                iconColor = if (hasOverdue)
                                                    MaterialTheme.colorScheme.onErrorContainer
                                                else
                                                    MaterialTheme.colorScheme.onPrimaryContainer
                                            )
                                        }

                                        Column(modifier = Modifier.weight(1f)) {
                                            // Name with primary star indicator
                                            Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.spacedBy(6.dp)
                                            ) {
                                                Text(
                                                    text = residence.name,
                                                    style = MaterialTheme.typography.titleMedium,
                                                    color = MaterialTheme.colorScheme.onSurface,
                                                    maxLines = 1,
                                                    overflow = TextOverflow.Ellipsis
                                                )
                                                if (residence.isPrimary) {
                                                    Icon(
                                                        Icons.Default.Star,
                                                        contentDescription = "Primary residence",
                                                        modifier = Modifier.size(16.dp),
                                                        tint = Color(0xFFFFD700) // Gold color
                                                    )
                                                }
                                            }

                                            // Property type
                                            residence.propertyTypeName?.let { typeName ->
                                                Text(
                                                    text = typeName.uppercase(),
                                                    style = MaterialTheme.typography.labelSmall,
                                                    color = MaterialTheme.colorScheme.primary,
                                                    letterSpacing = 1.sp
                                                )
                                            }

                                            Spacer(modifier = Modifier.height(AppSpacing.xs))

                                            // Street address (if available)
                                            if (residence.streetAddress.isNotBlank()) {
                                                Row(
                                                    verticalAlignment = Alignment.CenterVertically,
                                                    horizontalArrangement = Arrangement.spacedBy(AppSpacing.xs)
                                                ) {
                                                    Icon(
                                                        Icons.Default.Place,
                                                        contentDescription = null, // decorative
                                                        modifier = Modifier.size(14.dp),
                                                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                                                    )
                                                    Text(
                                                        text = residence.streetAddress,
                                                        style = MaterialTheme.typography.bodySmall,
                                                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                        maxLines = 1,
                                                        overflow = TextOverflow.Ellipsis
                                                    )
                                                }
                                            }

                                            // City, State
                                            Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.spacedBy(AppSpacing.xs)
                                            ) {
                                                Icon(
                                                    Icons.Default.LocationOn,
                                                    contentDescription = null, // decorative
                                                    modifier = Modifier.size(14.dp),
                                                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                                                Text(
                                                    text = "${residence.city}, ${residence.stateProvince}",
                                                    style = MaterialTheme.typography.bodySmall,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                                            }
                                        }

                                        Icon(
                                            Icons.Default.KeyboardArrowRight,
                                            contentDescription = null, // decorative
                                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }

                                    Spacer(modifier = Modifier.height(OrganicSpacing.cozy))
                                    OrganicDivider(color = MaterialTheme.colorScheme.textSecondary.copy(alpha = 0.15f))
                                    Spacer(modifier = Modifier.height(OrganicSpacing.cozy))

                                    // Fully dynamic task summary from API - show first 3 categories
                                    val displayCategories = residence.taskSummary.categories.take(3)

                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.SpaceEvenly
                                    ) {
                                        displayCategories.forEach { category ->
                                            TaskStatChip(
                                                icon = getIconForCategory(category.icons.android),
                                                value = "${category.count}",
                                                label = category.displayName,
                                                color = parseHexColor(category.color)
                                            )
                                        }
                                    }
                                }
                            }
                        }
                        }
                    }
                }
            }
        }
}

/**
 * Map Android icon name from backend to Material Icon
 */
private fun getIconForCategory(iconName: String) = when (iconName) {
    "Warning" -> Icons.Default.Warning
    "CalendarToday" -> Icons.Default.CalendarToday
    "PlayCircle" -> Icons.Default.PlayCircle
    "Inbox" -> Icons.Default.Inbox
    "CheckCircle" -> Icons.Default.CheckCircle
    "Archive" -> Icons.Default.Archive
    else -> Icons.Default.Circle
}

/**
 * Parse hex color string to Compose Color
 * Works in commonMain without android dependencies
 */
private fun parseHexColor(hex: String): Color {
    return try {
        val cleanHex = hex.removePrefix("#")
        val colorInt = cleanHex.toLong(16)
        val alpha = if (cleanHex.length == 8) {
            (colorInt shr 24 and 0xFF) / 255f
        } else {
            1f
        }
        val red = ((colorInt shr 16) and 0xFF) / 255f
        val green = ((colorInt shr 8) and 0xFF) / 255f
        val blue = (colorInt and 0xFF) / 255f
        Color(red, green, blue, alpha)
    } catch (e: Exception) {
        Color.Gray
    }
}
