package com.tt.honeyDue.ui.components.documents

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
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.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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 com.tt.honeyDue.models.Document
import com.tt.honeyDue.models.DocumentCategory
import com.tt.honeyDue.models.DocumentType
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing

@Composable
fun DocumentCard(document: Document, isWarrantyCard: Boolean = false, onClick: () -> Unit) {
    if (isWarrantyCard) {
        WarrantyCardContent(document = document, onClick = onClick)
    } else {
        RegularDocumentCardContent(document = document, onClick = onClick)
    }
}

@Composable
private fun WarrantyCardContent(document: Document, onClick: () -> Unit) {
    val daysUntilExpiration = document.daysUntilExpiration ?: 0
    val statusColor = when {
        !document.isActive -> Color.Gray
        daysUntilExpiration < 0 -> Color.Red
        daysUntilExpiration < 30 -> Color(0xFFF59E0B)
        daysUntilExpiration < 90 -> Color(0xFFFBBF24)
        else -> Color(0xFF10B981)
    }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .testTag(AccessibilityIds.Document.documentCard)
            .clickable(onClick = onClick),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(AppRadius.md)
    ) {
        Column(modifier = Modifier.fillMaxWidth().padding(AppSpacing.lg)) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Top
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        document.title,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    Spacer(modifier = Modifier.height(AppSpacing.xs))
                    document.itemName?.let { itemName ->
                        Text(
                            itemName,
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }

                Box(
                    modifier = Modifier
                        .background(statusColor.copy(alpha = 0.2f), RoundedCornerShape(AppRadius.sm))
                        .padding(horizontal = AppSpacing.sm, vertical = AppSpacing.xs)
                ) {
                    Text(
                        when {
                            !document.isActive -> "Inactive"
                            daysUntilExpiration < 0 -> "Expired"
                            daysUntilExpiration < 30 -> "Expiring soon"
                            else -> "Active"
                        },
                        style = MaterialTheme.typography.labelSmall,
                        color = statusColor,
                        fontWeight = FontWeight.Bold
                    )
                }
            }

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

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Column {
                    Text("Provider", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                    Text(document.provider ?: "N/A", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium)
                }
                Column(horizontalAlignment = Alignment.End) {
                    Text("Expires", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                    Text(document.endDate ?: "N/A", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium)
                }
            }

            if (document.isActive && daysUntilExpiration >= 0) {
                Spacer(modifier = Modifier.height(AppSpacing.sm))
                Text(
                    "$daysUntilExpiration days remaining",
                    style = MaterialTheme.typography.labelMedium,
                    color = statusColor
                )
            }

            document.category?.let { category ->
                Spacer(modifier = Modifier.height(AppSpacing.sm))
                Box(
                    modifier = Modifier
                        .background(Color(0xFFE5E7EB), RoundedCornerShape(6.dp))
                        .padding(horizontal = AppSpacing.sm, vertical = AppSpacing.xs)
                ) {
                    Text(
                        DocumentCategory.fromValue(category).displayName,
                        style = MaterialTheme.typography.labelSmall,
                        color = Color(0xFF374151)
                    )
                }
            }
        }
    }
}

@Composable
private fun RegularDocumentCardContent(document: Document, onClick: () -> Unit) {
    val typeColor = when (document.documentType) {
        "warranty" -> Color(0xFF3B82F6)
        "manual" -> Color(0xFF8B5CF6)
        "receipt" -> Color(0xFF10B981)
        "inspection" -> Color(0xFFF59E0B)
        else -> Color(0xFF6B7280)
    }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .testTag(AccessibilityIds.Document.documentCard)
            .clickable(onClick = onClick),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(AppRadius.md)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth().padding(AppSpacing.lg),
            horizontalArrangement = Arrangement.spacedBy(AppSpacing.md)
        ) {
            // Document icon
            Box(
                modifier = Modifier
                    .size(56.dp)
                    .background(typeColor.copy(alpha = 0.1f), RoundedCornerShape(AppRadius.sm)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    when (document.documentType) {
                        "photo" -> Icons.Default.Image
                        "warranty", "insurance" -> Icons.Default.VerifiedUser
                        "manual" -> Icons.Default.MenuBook
                        "receipt" -> Icons.Default.Receipt
                        else -> Icons.Default.Description
                    },
                    contentDescription = null, // decorative
                    tint = typeColor,
                    modifier = Modifier.size(32.dp)
                )
            }

            Column(modifier = Modifier.weight(1f)) {
                Text(
                    document.title,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Spacer(modifier = Modifier.height(AppSpacing.xs))

                if (document.description?.isNotBlank() == true) {
                    Text(
                        document.description,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                    Spacer(modifier = Modifier.height(AppSpacing.sm))
                }

                Row(
                    horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(
                        modifier = Modifier
                            .background(typeColor.copy(alpha = 0.2f), RoundedCornerShape(AppRadius.xs))
                            .padding(horizontal = 6.dp, vertical = 2.dp)
                    ) {
                        Text(
                            DocumentType.fromValue(document.documentType).displayName,
                            style = MaterialTheme.typography.labelSmall,
                            color = typeColor
                        )
                    }

                    document.fileSize?.let { size ->
                        Text(
                            formatFileSize(size),
                            style = MaterialTheme.typography.labelSmall,
                            color = Color.Gray
                        )
                    }
                }
            }

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

fun formatFileSize(bytes: Int): String {
    var size = bytes.toDouble()
    val units = listOf("B", "KB", "MB", "GB")
    var unitIndex = 0

    while (size >= 1024 && unitIndex < units.size - 1) {
        size /= 1024
        unitIndex++
    }

    // Round to 1 decimal place
    val rounded = (size * 10).toInt() / 10.0
    return "$rounded ${units[unitIndex]}"
}
