package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material3.*
import androidx.compose.runtime.*
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.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
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.HandleErrors
import com.tt.honeyDue.viewmodel.DocumentViewModel
import com.tt.honeyDue.models.*
import com.tt.honeyDue.network.ApiResult
import androidx.compose.foundation.Image
import coil3.compose.AsyncImage
import coil3.compose.rememberAsyncImagePainter
import androidx.compose.ui.window.Dialog
import com.tt.honeyDue.ui.components.documents.ErrorState
import com.tt.honeyDue.ui.components.documents.formatFileSize
import androidx.compose.ui.window.DialogProperties
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil3.compose.SubcomposeAsyncImage
import coil3.compose.SubcomposeAsyncImageContent
import coil3.compose.AsyncImagePainter
import com.tt.honeyDue.ui.components.AuthenticatedImage
import com.tt.honeyDue.util.DateUtils
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DocumentDetailScreen(
    documentId: Int,
    onNavigateBack: () -> Unit,
    onNavigateToEdit: (Int) -> Unit,
    documentViewModel: DocumentViewModel = viewModel { DocumentViewModel() }
) {
    val documentState by documentViewModel.documentDetailState.collectAsStateWithLifecycle()
    val deleteState by documentViewModel.deleteState.collectAsStateWithLifecycle()
    var showDeleteDialog by remember { mutableStateOf(false) }
    var showPhotoViewer by remember { mutableStateOf(false) }
    var selectedPhotoIndex by remember { mutableStateOf(0) }

    LaunchedEffect(documentId) {
        documentViewModel.loadDocumentDetail(documentId)
    }

    // Handle errors for document deletion
    deleteState.HandleErrors(
        onRetry = { documentViewModel.deleteDocument(documentId) },
        errorTitle = stringResource(Res.string.documents_failed_to_delete)
    )

    // Handle successful deletion
    LaunchedEffect(deleteState) {
        if (deleteState is ApiResult.Success) {
            documentViewModel.resetDeleteState()
            onNavigateBack()
        }
    }

    Scaffold(
        modifier = Modifier.enableTestTagsAsResourceId(),
        topBar = {
            TopAppBar(
                title = { Text(stringResource(Res.string.documents_details), fontWeight = FontWeight.Bold) },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(Res.string.common_back))
                    }
                },
                actions = {
                    when (documentState) {
                        is ApiResult.Success -> {
                            IconButton(
                                modifier = Modifier.testTag(AccessibilityIds.Document.editButton),
                                onClick = { onNavigateToEdit(documentId) }
                            ) {
                                Icon(Icons.Default.Edit, stringResource(Res.string.common_edit))
                            }
                            IconButton(
                                modifier = Modifier.testTag(AccessibilityIds.Document.deleteButton),
                                onClick = { showDeleteDialog = true }
                            ) {
                                Icon(Icons.Default.Delete, stringResource(Res.string.common_delete), tint = MaterialTheme.colorScheme.error)
                            }
                        }
                        else -> {}
                    }
                }
            )
        }
    ) { padding ->
        WarmGradientBackground {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
                    .testTag(AccessibilityIds.Document.detailView)
            ) {
                ApiResultHandler(
                    state = documentState,
                    onRetry = { documentViewModel.loadDocumentDetail(documentId) },
                    errorTitle = stringResource(Res.string.documents_failed_to_load)
                ) { document ->
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState())
                            .padding(start = OrganicSpacing.lg, end = OrganicSpacing.lg, top = OrganicSpacing.lg, bottom = 96.dp),
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.lg)
                    ) {
                        // Status badge (for warranties)
                        if (document.documentType == "warranty") {
                            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)
                            }

                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                accentColor = statusColor.copy(alpha = 0.1f)
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(OrganicSpacing.lg),
                                    horizontalArrangement = Arrangement.SpaceBetween,
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Column {
                                        Text(
                                            stringResource(Res.string.documents_status),
                                            style = MaterialTheme.typography.labelMedium,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                        Text(
                                            when {
                                                !document.isActive -> stringResource(Res.string.documents_inactive)
                                                daysUntilExpiration < 0 -> stringResource(Res.string.documents_expired)
                                                daysUntilExpiration < 30 -> stringResource(Res.string.documents_expiring_soon)
                                                else -> stringResource(Res.string.documents_active)
                                            },
                                            style = MaterialTheme.typography.titleLarge,
                                            fontWeight = FontWeight.Bold,
                                            color = statusColor
                                        )
                                    }
                                    if (document.isActive && daysUntilExpiration >= 0) {
                                        Column(horizontalAlignment = Alignment.End) {
                                            Text(
                                                stringResource(Res.string.documents_days_remaining),
                                                style = MaterialTheme.typography.labelMedium,
                                                color = MaterialTheme.colorScheme.onSurfaceVariant
                                            )
                                            Text(
                                                "$daysUntilExpiration",
                                                style = MaterialTheme.typography.titleLarge,
                                                fontWeight = FontWeight.Bold,
                                                color = statusColor
                                            )
                                        }
                                    }
                                }
                            }
                        }

                        // Basic Information
                        OrganicCard(modifier = Modifier.fillMaxWidth()) {
                            Column(
                                modifier = Modifier.padding(OrganicSpacing.lg),
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                            ) {
                                Text(
                                    stringResource(Res.string.documents_basic_info),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.Bold
                                )
                                OrganicDivider()

                                DetailRow(stringResource(Res.string.documents_title_label), document.title)
                                DetailRow(stringResource(Res.string.documents_type_label), DocumentType.fromValue(document.documentType).displayName)
                                document.category?.let {
                                    DetailRow(stringResource(Res.string.documents_all_categories), DocumentCategory.fromValue(it).displayName)
                                }
                                document.description?.let {
                                    DetailRow(stringResource(Res.string.documents_description_label), it)
                                }
                            }
                        }

                        // Warranty/Item Details (for warranties)
                        if (document.documentType == "warranty" &&
                            (document.itemName != null || document.modelNumber != null ||
                             document.serialNumber != null || document.provider != null)) {
                            OrganicCard(modifier = Modifier.fillMaxWidth()) {
                                Column(
                                    modifier = Modifier.padding(OrganicSpacing.lg),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                                ) {
                                    Text(
                                        stringResource(Res.string.documents_item_details),
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Bold
                                    )
                                    OrganicDivider()

                                    document.itemName?.let { DetailRow(stringResource(Res.string.documents_item_name), it) }
                                    document.modelNumber?.let { DetailRow(stringResource(Res.string.documents_model_number), it) }
                                    document.serialNumber?.let { DetailRow(stringResource(Res.string.documents_serial_number), it) }
                                    document.provider?.let { DetailRow(stringResource(Res.string.documents_provider), it) }
                                    document.providerContact?.let { DetailRow(stringResource(Res.string.documents_provider_contact), it) }
                                }
                            }
                        }

                        // Claim Information (for warranties)
                        if (document.documentType == "warranty" &&
                            (document.claimPhone != null || document.claimEmail != null ||
                             document.claimWebsite != null)) {
                            OrganicCard(modifier = Modifier.fillMaxWidth()) {
                                Column(
                                    modifier = Modifier.padding(OrganicSpacing.lg),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                                ) {
                                    Text(
                                        stringResource(Res.string.documents_claim_info),
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Bold
                                    )
                                    OrganicDivider()

                                    document.claimPhone?.let { DetailRow(stringResource(Res.string.documents_claim_phone), it) }
                                    document.claimEmail?.let { DetailRow(stringResource(Res.string.documents_claim_email), it) }
                                    document.claimWebsite?.let { DetailRow(stringResource(Res.string.documents_claim_website), it) }
                                }
                            }
                        }

                        // Dates
                        if (document.purchaseDate != null || document.startDate != null ||
                            document.endDate != null) {
                            OrganicCard(modifier = Modifier.fillMaxWidth()) {
                                Column(
                                    modifier = Modifier.padding(OrganicSpacing.lg),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                                ) {
                                    Text(
                                        stringResource(Res.string.documents_important_dates),
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Bold
                                    )
                                    OrganicDivider()

                                    document.purchaseDate?.let { DetailRow(stringResource(Res.string.documents_purchase_date), DateUtils.formatDateMedium(it)) }
                                    document.startDate?.let { DetailRow(stringResource(Res.string.documents_start_date), DateUtils.formatDateMedium(it)) }
                                    document.endDate?.let { DetailRow(stringResource(Res.string.documents_end_date), DateUtils.formatDateMedium(it)) }
                                }
                            }
                        }

                        // Residence & Contractor
                        OrganicCard(modifier = Modifier.fillMaxWidth()) {
                            Column(
                                modifier = Modifier.padding(OrganicSpacing.lg),
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                            ) {
                                Text(
                                    stringResource(Res.string.documents_associations),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.Bold
                                )
                                OrganicDivider()

                                document.residenceId?.let { DetailRow(stringResource(Res.string.documents_residence), "Residence #$it") }
                                document.taskId?.let { DetailRow(stringResource(Res.string.documents_contractor), "Task #$it") }
                            }
                        }

                        // Additional Information
                        if (document.tags != null || document.notes != null) {
                            OrganicCard(modifier = Modifier.fillMaxWidth()) {
                                Column(
                                    modifier = Modifier.padding(OrganicSpacing.lg),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                                ) {
                                    Text(
                                        stringResource(Res.string.documents_additional_info),
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Bold
                                    )
                                    OrganicDivider()

                                    document.tags?.let { DetailRow(stringResource(Res.string.documents_tags), it) }
                                    document.notes?.let { DetailRow(stringResource(Res.string.documents_notes), it) }
                                }
                            }
                        }

                        // Images
                        if (document.images.isNotEmpty()) {
                            OrganicCard(modifier = Modifier.fillMaxWidth()) {
                                Column(
                                    modifier = Modifier.padding(OrganicSpacing.lg),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                                ) {
                                    Text(
                                        stringResource(Res.string.documents_images, document.images.size),
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Bold
                                    )
                                    OrganicDivider()

                                    // Image grid
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
                                    ) {
                                        document.images.take(4).forEachIndexed { index, image ->
                                            Box(
                                                modifier = Modifier
                                                    .weight(1f)
                                                    .aspectRatio(1f)
                                                    .clickable {
                                                        selectedPhotoIndex = index
                                                        showPhotoViewer = true
                                                    }
                                            ) {
                                                AuthenticatedImage(
                                                    mediaUrl = image.mediaUrl,
                                                    contentDescription = image.caption,
                                                    modifier = Modifier.fillMaxSize(),
                                                    contentScale = androidx.compose.ui.layout.ContentScale.Crop
                                                )
                                                if (index == 3 && document.images.size > 4) {
                                                    Box(
                                                        modifier = Modifier
                                                            .fillMaxSize()
                                                            .background(Color.Black.copy(alpha = 0.6f)),
                                                        contentAlignment = Alignment.Center
                                                    ) {
                                                        Text(
                                                            "+${document.images.size - 4}",
                                                            color = Color.White,
                                                            style = MaterialTheme.typography.titleLarge,
                                                            fontWeight = FontWeight.Bold
                                                        )
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // File Information
                        if (document.fileUrl != null) {
                            OrganicCard(modifier = Modifier.fillMaxWidth()) {
                                Column(
                                    modifier = Modifier.padding(OrganicSpacing.lg),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                                ) {
                                    Text(
                                        stringResource(Res.string.documents_attached_file),
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Bold
                                    )
                                    OrganicDivider()

                                    document.mimeType?.let { DetailRow(stringResource(Res.string.documents_file_type), it) }
                                    document.fileSize?.let {
                                        DetailRow(stringResource(Res.string.documents_file_size), formatFileSize(it))
                                    }

                                    Button(
                                        onClick = { /* TODO: Download file */ },
                                        modifier = Modifier.fillMaxWidth()
                                    ) {
                                        Icon(Icons.Default.Download, null)
                                        Spacer(modifier = Modifier.width(OrganicSpacing.sm))
                                        Text(stringResource(Res.string.documents_download_file))
                                    }
                                }
                            }
                        }

                        // Metadata
                        OrganicCard(modifier = Modifier.fillMaxWidth()) {
                            Column(
                                modifier = Modifier.padding(OrganicSpacing.lg),
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                            ) {
                                Text(
                                    stringResource(Res.string.documents_metadata),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.Bold
                                )
                                OrganicDivider()

                                document.createdBy?.let { user ->
                                    val name = listOfNotNull(user.firstName, user.lastName).joinToString(" ").ifEmpty { user.username }
                                    DetailRow(stringResource(Res.string.documents_uploaded_by), name)
                                }
                                document.createdAt?.let { DetailRow(stringResource(Res.string.documents_created), DateUtils.formatDateMedium(it)) }
                                document.updatedAt?.let { DetailRow(stringResource(Res.string.documents_updated), DateUtils.formatDateMedium(it)) }
                            }
                        }
                    }
                }
            }
        }
    }

    // Delete confirmation dialog
    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text(stringResource(Res.string.documents_delete)) },
            text = { Text(stringResource(Res.string.documents_delete_warning)) },
            confirmButton = {
                TextButton(
                    modifier = Modifier.testTag(AccessibilityIds.Alert.deleteButton),
                    onClick = {
                        documentViewModel.deleteDocument(documentId)
                        showDeleteDialog = false
                    }
                ) {
                    Text(stringResource(Res.string.common_delete), color = MaterialTheme.colorScheme.error)
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteDialog = false }) {
                    Text(stringResource(Res.string.common_cancel))
                }
            }
        )
    }

    // Photo viewer dialog
    if (showPhotoViewer && documentState is ApiResult.Success) {
        val document = (documentState as ApiResult.Success<Document>).data
        if (document.images.isNotEmpty()) {
            DocumentImageViewer(
                images = document.images,
                initialIndex = selectedPhotoIndex,
                onDismiss = { showPhotoViewer = false }
            )
        }
    }
}

@Composable
fun DetailRow(label: String, value: String) {
    Column(modifier = Modifier.fillMaxWidth()) {
        Text(
            label,
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        Spacer(modifier = Modifier.height(OrganicSpacing.xs))
        Text(
            value,
            style = MaterialTheme.typography.bodyLarge
        )
    }
}

@Composable
fun DocumentImageViewer(
    images: List<DocumentImage>,
    initialIndex: Int = 0,
    onDismiss: () -> Unit
) {
    var selectedIndex by remember { mutableStateOf(initialIndex) }
    var showFullImage by remember { mutableStateOf(false) }

    Dialog(
        onDismissRequest = {
            if (showFullImage) {
                showFullImage = false
            } else {
                onDismiss()
            }
        },
        properties = DialogProperties(
            dismissOnBackPress = true,
            dismissOnClickOutside = true,
            usePlatformDefaultWidth = false
        )
    ) {
        Surface(
            modifier = Modifier
                .fillMaxWidth(0.95f)
                .fillMaxHeight(0.9f),
            shape = RoundedCornerShape(OrganicSpacing.lg),
            color = MaterialTheme.colorScheme.background
        ) {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                // Header
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(OrganicSpacing.lg),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = if (showFullImage) "Image ${selectedIndex + 1} of ${images.size}" else "Document Images",
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold
                    )
                    IconButton(onClick = {
                        if (showFullImage) {
                            showFullImage = false
                        } else {
                            onDismiss()
                        }
                    }) {
                        Icon(
                            Icons.Default.Close,
                            contentDescription = "Close"
                        )
                    }
                }

                OrganicDivider()

                // Content
                if (showFullImage) {
                    // Single image view
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(OrganicSpacing.lg),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        AuthenticatedImage(
                            mediaUrl = images[selectedIndex].mediaUrl,
                            contentDescription = images[selectedIndex].caption,
                            modifier = Modifier
                                .fillMaxWidth()
                                .weight(1f),
                            contentScale = androidx.compose.ui.layout.ContentScale.Fit
                        )

                        images[selectedIndex].caption?.let { caption ->
                            Spacer(modifier = Modifier.height(OrganicSpacing.lg))
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Text(
                                    text = caption,
                                    modifier = Modifier.padding(OrganicSpacing.lg),
                                    style = MaterialTheme.typography.bodyMedium
                                )
                            }
                        }

                        // Navigation buttons
                        if (images.size > 1) {
                            Spacer(modifier = Modifier.height(OrganicSpacing.lg))
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween
                            ) {
                                OutlinedButton(
                                    onClick = { selectedIndex = (selectedIndex - 1 + images.size) % images.size },
                                    enabled = selectedIndex > 0
                                ) {
                                    Icon(Icons.AutoMirrored.Filled.ArrowBack, "Previous")
                                    Spacer(modifier = Modifier.width(OrganicSpacing.sm))
                                    Text("Previous")
                                }
                                OutlinedButton(
                                    onClick = { selectedIndex = (selectedIndex + 1) % images.size },
                                    enabled = selectedIndex < images.size - 1
                                ) {
                                    Text("Next")
                                    Spacer(modifier = Modifier.width(OrganicSpacing.sm))
                                    Icon(Icons.AutoMirrored.Filled.ArrowForward, "Next")
                                }
                            }
                        }
                    }
                } else {
                    // Grid view
                    LazyVerticalGrid(
                        columns = GridCells.Fixed(2),
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(OrganicSpacing.lg),
                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.md),
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                    ) {
                        items(images.size) { index ->
                            val image = images[index]
                            OrganicCard(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable {
                                        selectedIndex = index
                                        showFullImage = true
                                    }
                            ) {
                                Column {
                                    AuthenticatedImage(
                                        mediaUrl = image.mediaUrl,
                                        contentDescription = image.caption,
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .aspectRatio(1f),
                                        contentScale = androidx.compose.ui.layout.ContentScale.Crop
                                    )

                                    image.caption?.let { caption ->
                                        Text(
                                            text = caption,
                                            modifier = Modifier.padding(OrganicSpacing.sm),
                                            style = MaterialTheme.typography.bodySmall,
                                            maxLines = 2
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
