package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
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.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil3.compose.AsyncImage
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.support.enableTestTagsAsResourceId
import com.tt.honeyDue.ui.components.AuthenticatedImage
import com.tt.honeyDue.viewmodel.DocumentViewModel
import com.tt.honeyDue.viewmodel.ResidenceViewModel
import com.tt.honeyDue.models.*
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.platform.ImageData
import com.tt.honeyDue.platform.rememberImagePicker
import com.tt.honeyDue.platform.rememberCameraPicker
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DocumentFormScreen(
    residenceId: Int? = null,
    existingDocumentId: Int? = null,
    initialDocumentType: String = "other",
    onNavigateBack: () -> Unit,
    onSuccess: () -> Unit,
    documentViewModel: DocumentViewModel = viewModel { DocumentViewModel() },
    residenceViewModel: ResidenceViewModel = viewModel { ResidenceViewModel() }
) {
    val isEditMode = existingDocumentId != null
    val needsResidenceSelection = residenceId == null || residenceId == -1

    // State
    var selectedResidence by remember { mutableStateOf<Residence?>(null) }
    var title by remember { mutableStateOf("") }
    var description by remember { mutableStateOf("") }
    var selectedDocumentType by remember { mutableStateOf(initialDocumentType) }
    var selectedCategory by remember { mutableStateOf<String?>(null) }
    var notes by remember { mutableStateOf("") }
    var tags by remember { mutableStateOf("") }
    var isActive by remember { mutableStateOf(true) }
    var selectedImages by remember { mutableStateOf<List<ImageData>>(emptyList()) }
    var existingImages by remember { mutableStateOf<List<DocumentImage>>(emptyList()) }

    // Warranty-specific fields
    var itemName by remember { mutableStateOf("") }
    var modelNumber by remember { mutableStateOf("") }
    var serialNumber by remember { mutableStateOf("") }
    var provider by remember { mutableStateOf("") }
    var providerContact by remember { mutableStateOf("") }
    var claimPhone by remember { mutableStateOf("") }
    var claimEmail by remember { mutableStateOf("") }
    var claimWebsite by remember { mutableStateOf("") }
    var purchaseDate by remember { mutableStateOf("") }
    var startDate by remember { mutableStateOf("") }
    var endDate by remember { mutableStateOf("") }

    // Dropdowns
    var documentTypeExpanded by remember { mutableStateOf(false) }
    var categoryExpanded by remember { mutableStateOf(false) }
    var residenceExpanded by remember { mutableStateOf(false) }

    // Validation errors
    var titleError by remember { mutableStateOf("") }
    var itemNameError by remember { mutableStateOf("") }
    var providerError by remember { mutableStateOf("") }
    var residenceError by remember { mutableStateOf("") }

    val residencesState by residenceViewModel.residencesState.collectAsStateWithLifecycle()
    val documentDetailState by documentViewModel.documentDetailState.collectAsStateWithLifecycle()
    val operationState by if (isEditMode) {
        documentViewModel.updateState.collectAsStateWithLifecycle()
    } else {
        documentViewModel.createState.collectAsStateWithLifecycle()
    }

    val isWarranty = selectedDocumentType == "warranty"
    val maxImages = if (isEditMode) 10 else 5

    // Image pickers
    val imagePicker = rememberImagePicker { images ->
        selectedImages = if (selectedImages.size + images.size <= maxImages) {
            selectedImages + images
        } else {
            selectedImages + images.take(maxImages - selectedImages.size)
        }
    }

    val cameraPicker = rememberCameraPicker { image ->
        if (selectedImages.size < maxImages) {
            selectedImages = selectedImages + image
        }
    }

    // Track screen view
    LaunchedEffect(Unit) {
        if (!isEditMode) {
            val type = if (initialDocumentType == "warranty") "warranty" else "document"
            PostHogAnalytics.screen(
                AnalyticsEvents.NEW_DOCUMENT_SCREEN_SHOWN,
                mapOf("type" to type)
            )
        }
    }

    // Load residences if needed
    LaunchedEffect(needsResidenceSelection) {
        if (needsResidenceSelection) {
            residenceViewModel.loadResidences()
        }
    }

    // Load existing document for edit mode
    LaunchedEffect(existingDocumentId) {
        if (existingDocumentId != null) {
            documentViewModel.loadDocumentDetail(existingDocumentId)
        }
    }

    // Populate form from existing document
    LaunchedEffect(documentDetailState) {
        if (isEditMode && documentDetailState is ApiResult.Success) {
            val document = (documentDetailState as ApiResult.Success<Document>).data
            title = document.title
            selectedDocumentType = document.documentType
            description = document.description ?: ""
            selectedCategory = document.category
            tags = document.tags ?: ""
            notes = document.notes ?: ""
            isActive = document.isActive
            existingImages = document.images

            // Warranty fields
            itemName = document.itemName ?: ""
            modelNumber = document.modelNumber ?: ""
            serialNumber = document.serialNumber ?: ""
            provider = document.provider ?: ""
            providerContact = document.providerContact ?: ""
            claimPhone = document.claimPhone ?: ""
            claimEmail = document.claimEmail ?: ""
            claimWebsite = document.claimWebsite ?: ""
            purchaseDate = document.purchaseDate ?: ""
            startDate = document.startDate ?: ""
            endDate = document.endDate ?: ""
        }
    }

    // Handle success
    LaunchedEffect(operationState) {
        if (operationState is ApiResult.Success) {
            if (!isEditMode) {
                // Track document creation
                val type = if (selectedDocumentType == "warranty") "warranty" else "document"
                PostHogAnalytics.capture(
                    AnalyticsEvents.DOCUMENT_CREATED,
                    mapOf("type" to type)
                )
            }
            if (isEditMode) {
                documentViewModel.resetUpdateState()
            } else {
                documentViewModel.resetCreateState()
            }
            onSuccess()
        }
    }

    Scaffold(
        modifier = Modifier.enableTestTagsAsResourceId(),
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        when {
                            isEditMode && isWarranty -> stringResource(Res.string.documents_form_edit_warranty)
                            isEditMode -> stringResource(Res.string.documents_form_edit_document)
                            isWarranty -> stringResource(Res.string.documents_form_add_warranty)
                            else -> stringResource(Res.string.documents_form_add_document)
                        }
                    )
                },
                navigationIcon = {
                    IconButton(
                        modifier = Modifier.testTag(AccessibilityIds.Document.formCancelButton),
                        onClick = onNavigateBack
                    ) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(Res.string.common_back))
                    }
                }
            )
        }
    ) { padding ->
        WarmGradientBackground {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
                    .imePadding()
                    .verticalScroll(rememberScrollState())
                    .padding(start = OrganicSpacing.cozy, end = OrganicSpacing.cozy, top = OrganicSpacing.cozy, bottom = 96.dp),
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
            ) {
                // Loading state for edit mode
                if (isEditMode && documentDetailState is ApiResult.Loading) {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                    return@Column
                }

                // Residence Dropdown (if needed)
                if (needsResidenceSelection) {
                    when (residencesState) {
                        is ApiResult.Loading -> {
                            CircularProgressIndicator(modifier = Modifier.size(40.dp))
                        }
                        is ApiResult.Success -> {
                            val residences = (residencesState as ApiResult.Success<List<Residence>>).data
                            ExposedDropdownMenuBox(
                                expanded = residenceExpanded,
                                onExpandedChange = { residenceExpanded = it }
                            ) {
                                OutlinedTextField(
                                    value = selectedResidence?.name ?: stringResource(Res.string.documents_form_select_residence),
                                    onValueChange = {},
                                    readOnly = true,
                                    label = { Text(stringResource(Res.string.documents_form_residence_required)) },
                                    isError = residenceError.isNotEmpty(),
                                    supportingText = if (residenceError.isNotEmpty()) {
                                        { Text(residenceError) }
                                    } else null,
                                    trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = residenceExpanded) },
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .menuAnchor()
                                        .testTag(AccessibilityIds.Document.residencePicker)
                                )
                                ExposedDropdownMenu(
                                    expanded = residenceExpanded,
                                    onDismissRequest = { residenceExpanded = false }
                                ) {
                                    residences.forEach { residence ->
                                        DropdownMenuItem(
                                            text = { Text(residence.name) },
                                            onClick = {
                                                selectedResidence = residence
                                                residenceError = ""
                                                residenceExpanded = false
                                            }
                                        )
                                    }
                                }
                            }
                        }
                        is ApiResult.Error -> {
                            Text(
                                stringResource(Res.string.documents_form_failed_to_load_residences, com.tt.honeyDue.util.ErrorMessageParser.parse((residencesState as ApiResult.Error).message)),
                                color = MaterialTheme.colorScheme.error
                            )
                        }
                        else -> {}
                    }
                }

                // Document Type Dropdown
                ExposedDropdownMenuBox(
                    expanded = documentTypeExpanded,
                    onExpandedChange = { documentTypeExpanded = it }
                ) {
                    OutlinedTextField(
                        value = DocumentType.fromValue(selectedDocumentType).displayName,
                        onValueChange = {},
                        readOnly = true,
                        label = { Text(stringResource(Res.string.documents_form_document_type_required)) },
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = documentTypeExpanded) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor()
                            .testTag(AccessibilityIds.Document.typePicker)
                    )
                    ExposedDropdownMenu(
                        expanded = documentTypeExpanded,
                        onDismissRequest = { documentTypeExpanded = false }
                    ) {
                        DocumentType.values().forEach { type ->
                            DropdownMenuItem(
                                text = { Text(type.displayName) },
                                onClick = {
                                    selectedDocumentType = type.value
                                    documentTypeExpanded = false
                                }
                            )
                        }
                    }
                }

                // Title
                OutlinedTextField(
                    value = title,
                    onValueChange = {
                        title = it
                        titleError = ""
                    },
                    label = { Text(stringResource(Res.string.documents_form_title_required)) },
                    isError = titleError.isNotEmpty(),
                    supportingText = if (titleError.isNotEmpty()) {
                        { Text(titleError) }
                    } else null,
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Document.titleField)
                )

                // Warranty-specific fields
                if (isWarranty) {
                    OutlinedTextField(
                        value = itemName,
                        onValueChange = {
                            itemName = it
                            itemNameError = ""
                        },
                        label = { Text(stringResource(Res.string.documents_form_item_name_required)) },
                        isError = itemNameError.isNotEmpty(),
                        supportingText = if (itemNameError.isNotEmpty()) {
                            { Text(itemNameError) }
                        } else null,
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Document.itemNameField)
                    )

                    OutlinedTextField(
                        value = modelNumber,
                        onValueChange = { modelNumber = it },
                        label = { Text(stringResource(Res.string.documents_form_model_number)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Document.modelNumberField)
                    )

                    OutlinedTextField(
                        value = serialNumber,
                        onValueChange = { serialNumber = it },
                        label = { Text(stringResource(Res.string.documents_form_serial_number)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Document.serialNumberField)
                    )

                    OutlinedTextField(
                        value = provider,
                        onValueChange = {
                            provider = it
                            providerError = ""
                        },
                        label = { Text(stringResource(Res.string.documents_form_provider_required)) },
                        isError = providerError.isNotEmpty(),
                        supportingText = if (providerError.isNotEmpty()) {
                            { Text(providerError) }
                        } else null,
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Document.providerField)
                    )

                    OutlinedTextField(
                        value = providerContact,
                        onValueChange = { providerContact = it },
                        label = { Text(stringResource(Res.string.documents_form_provider_contact)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Document.providerContactField)
                    )

                    OutlinedTextField(
                        value = claimPhone,
                        onValueChange = { claimPhone = it },
                        label = { Text(stringResource(Res.string.documents_form_claim_phone)) },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone),
                        modifier = Modifier.fillMaxWidth()
                    )

                    OutlinedTextField(
                        value = claimEmail,
                        onValueChange = { claimEmail = it },
                        label = { Text(stringResource(Res.string.documents_form_claim_email)) },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
                        modifier = Modifier.fillMaxWidth()
                    )

                    OutlinedTextField(
                        value = claimWebsite,
                        onValueChange = { claimWebsite = it },
                        label = { Text(stringResource(Res.string.documents_form_claim_website)) },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
                        modifier = Modifier.fillMaxWidth()
                    )

                    OutlinedTextField(
                        value = purchaseDate,
                        onValueChange = { purchaseDate = it },
                        label = { Text(stringResource(Res.string.documents_form_purchase_date)) },
                        placeholder = { Text(stringResource(Res.string.documents_form_date_placeholder)) },
                        modifier = Modifier.fillMaxWidth()
                    )

                    OutlinedTextField(
                        value = startDate,
                        onValueChange = { startDate = it },
                        label = { Text(stringResource(Res.string.documents_form_warranty_start)) },
                        placeholder = { Text(stringResource(Res.string.documents_form_date_placeholder)) },
                        modifier = Modifier.fillMaxWidth()
                    )

                    OutlinedTextField(
                        value = endDate,
                        onValueChange = { endDate = it },
                        label = { Text(stringResource(Res.string.documents_form_warranty_end_required)) },
                        placeholder = { Text(stringResource(Res.string.documents_form_date_placeholder_end)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Document.expirationDatePicker)
                    )
                }

                // Description
                OutlinedTextField(
                    value = description,
                    onValueChange = { description = it },
                    label = { Text(stringResource(Res.string.documents_form_description)) },
                    minLines = 3,
                    modifier = Modifier.fillMaxWidth()
                )

                // Category Dropdown (for warranties and some documents)
                if (isWarranty || selectedDocumentType in listOf("inspection", "manual", "receipt")) {
                    ExposedDropdownMenuBox(
                        expanded = categoryExpanded,
                        onExpandedChange = { categoryExpanded = it }
                    ) {
                        OutlinedTextField(
                            value = selectedCategory?.let { DocumentCategory.fromValue(it).displayName } ?: stringResource(Res.string.documents_form_select_category),
                            onValueChange = {},
                            readOnly = true,
                            label = { Text(stringResource(Res.string.documents_form_category)) },
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = categoryExpanded) },
                            modifier = Modifier
                                .fillMaxWidth()
                                .menuAnchor()
                                .testTag(AccessibilityIds.Document.categoryPicker)
                        )
                        ExposedDropdownMenu(
                            expanded = categoryExpanded,
                            onDismissRequest = { categoryExpanded = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text(stringResource(Res.string.documents_form_category_none)) },
                                onClick = {
                                    selectedCategory = null
                                    categoryExpanded = false
                                }
                            )
                            DocumentCategory.values().forEach { category ->
                                DropdownMenuItem(
                                    text = { Text(category.displayName) },
                                    onClick = {
                                        selectedCategory = category.value
                                        categoryExpanded = false
                                    }
                                )
                            }
                        }
                    }
                }

                // Tags
                OutlinedTextField(
                    value = tags,
                    onValueChange = { tags = it },
                    label = { Text(stringResource(Res.string.documents_form_tags)) },
                    placeholder = { Text(stringResource(Res.string.documents_form_tags_placeholder)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Document.tagsField)
                )

                // Notes
                OutlinedTextField(
                    value = notes,
                    onValueChange = { notes = it },
                    label = { Text(stringResource(Res.string.documents_form_notes)) },
                    minLines = 3,
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Document.notesField)
                )

                // Active toggle (edit mode only)
                if (isEditMode) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(stringResource(Res.string.documents_form_active))
                        Switch(
                            checked = isActive,
                            onCheckedChange = { isActive = it }
                        )
                    }
                }

                // Existing images (edit mode only)
                if (isEditMode && existingImages.isNotEmpty()) {
                    OrganicCard(
                        modifier = Modifier.fillMaxWidth(),
                        showBlob = false
                    ) {
                        Column(
                            modifier = Modifier.padding(OrganicSpacing.cozy),
                            verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
                        ) {
                            Text(
                                stringResource(Res.string.documents_form_existing_photos, existingImages.size),
                                style = MaterialTheme.typography.titleSmall
                            )

                            existingImages.forEach { image ->
                                AuthenticatedImage(
                                    mediaUrl = image.mediaUrl,
                                    contentDescription = image.caption,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(200.dp)
                                        .clip(RoundedCornerShape(AppRadius.sm))
                                        .border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(AppRadius.sm)),
                                    contentScale = ContentScale.Crop
                                )
                            }
                        }
                    }
                }

                // Image upload section
                OrganicCard(
                    modifier = Modifier.fillMaxWidth(),
                    showBlob = false
                ) {
                    Column(
                        modifier = Modifier.padding(OrganicSpacing.cozy),
                        verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
                    ) {
                        Text(
                            if (isEditMode) {
                                stringResource(Res.string.documents_form_new_photos, selectedImages.size, maxImages)
                            } else {
                                stringResource(Res.string.documents_form_photos, selectedImages.size, maxImages)
                            },
                            style = MaterialTheme.typography.titleSmall
                        )

                        Row(
                            horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                        ) {
                            OutlinedButton(
                                onClick = { cameraPicker() },
                                modifier = Modifier.weight(1f),
                                enabled = selectedImages.size < maxImages
                            ) {
                                Icon(Icons.Default.CameraAlt, null, modifier = Modifier.size(18.dp))
                                Spacer(modifier = Modifier.width(AppSpacing.xs))
                                Text(stringResource(Res.string.documents_form_camera))
                            }

                            OutlinedButton(
                                onClick = { imagePicker() },
                                modifier = Modifier.weight(1f),
                                enabled = selectedImages.size < maxImages
                            ) {
                                Icon(Icons.Default.Photo, null, modifier = Modifier.size(18.dp))
                                Spacer(modifier = Modifier.width(AppSpacing.xs))
                                Text(stringResource(Res.string.documents_form_gallery))
                            }
                        }

                        // Display selected images
                        if (selectedImages.isNotEmpty()) {
                            Column(
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                            ) {
                                selectedImages.forEachIndexed { index, image ->
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.SpaceBetween,
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Row(
                                            horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Icon(
                                                Icons.Default.Image,
                                                contentDescription = null, // decorative
                                                tint = MaterialTheme.colorScheme.primary
                                            )
                                            Text(
                                                stringResource(Res.string.documents_form_image_number, index + 1),
                                                style = MaterialTheme.typography.bodyMedium
                                            )
                                        }
                                        IconButton(
                                            onClick = {
                                                selectedImages = selectedImages.filter { it != image }
                                            }
                                        ) {
                                            Icon(
                                                Icons.Default.Close,
                                                contentDescription = stringResource(Res.string.documents_form_remove_image),
                                                tint = MaterialTheme.colorScheme.error
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Error message
                if (operationState is ApiResult.Error) {
                    OrganicCard(
                        modifier = Modifier.fillMaxWidth(),
                        showBlob = false
                    ) {
                        Text(
                            com.tt.honeyDue.util.ErrorMessageParser.parse((operationState as ApiResult.Error).message),
                            modifier = Modifier.padding(AppSpacing.md),
                            color = MaterialTheme.colorScheme.error
                        )
                    }
                }

                // Error messages (need to be defined outside onClick)
                val selectResidenceError = stringResource(Res.string.documents_form_select_residence_error)
                val titleRequiredError = stringResource(Res.string.documents_form_title_error)
                val itemRequiredError = stringResource(Res.string.documents_form_item_name_error)
                val providerRequiredError = stringResource(Res.string.documents_form_provider_error)

                // Save Button
                OrganicPrimaryButton(
                    modifier = Modifier.testTag(AccessibilityIds.Document.saveButton),
                    text = when {
                        isEditMode && isWarranty -> stringResource(Res.string.documents_form_update_warranty)
                        isEditMode -> stringResource(Res.string.documents_form_update_document)
                        isWarranty -> stringResource(Res.string.documents_form_add_warranty)
                        else -> stringResource(Res.string.documents_form_add_document)
                    },
                    onClick = {
                        // Validate
                        var hasError = false

                        // Determine the actual residenceId to use
                        val actualResidenceId = if (needsResidenceSelection) {
                            if (selectedResidence == null) {
                                residenceError = selectResidenceError
                                hasError = true
                                -1
                            } else {
                                selectedResidence!!.id
                            }
                        } else {
                            residenceId ?: -1
                        }

                        if (title.isBlank()) {
                            titleError = titleRequiredError
                            hasError = true
                        }

                        if (isWarranty) {
                            if (itemName.isBlank()) {
                                itemNameError = itemRequiredError
                                hasError = true
                            }
                            if (provider.isBlank()) {
                                providerError = providerRequiredError
                                hasError = true
                            }
                        }

                        if (!hasError) {
                            if (isEditMode && existingDocumentId != null) {
                                documentViewModel.updateDocument(
                                    id = existingDocumentId,
                                    title = title,
                                    documentType = selectedDocumentType,
                                    description = description.ifBlank { null },
                                    category = selectedCategory,
                                    tags = tags.ifBlank { null },
                                    notes = notes.ifBlank { null },
                                    isActive = isActive,
                                    itemName = if (isWarranty) itemName else null,
                                    modelNumber = modelNumber.ifBlank { null },
                                    serialNumber = serialNumber.ifBlank { null },
                                    provider = if (isWarranty) provider else null,
                                    providerContact = providerContact.ifBlank { null },
                                    claimPhone = claimPhone.ifBlank { null },
                                    claimEmail = claimEmail.ifBlank { null },
                                    claimWebsite = claimWebsite.ifBlank { null },
                                    purchaseDate = purchaseDate.ifBlank { null },
                                    startDate = startDate.ifBlank { null },
                                    endDate = endDate.ifBlank { null },
                                    images = selectedImages
                                )
                            } else {
                                documentViewModel.createDocument(
                                    title = title,
                                    documentType = selectedDocumentType,
                                    residenceId = actualResidenceId,
                                    description = description.ifBlank { null },
                                    category = selectedCategory,
                                    tags = tags.ifBlank { null },
                                    notes = notes.ifBlank { null },
                                    contractorId = null,
                                    isActive = true,
                                    itemName = if (isWarranty) itemName else null,
                                    modelNumber = modelNumber.ifBlank { null },
                                    serialNumber = serialNumber.ifBlank { null },
                                    provider = if (isWarranty) provider else null,
                                    providerContact = providerContact.ifBlank { null },
                                    claimPhone = claimPhone.ifBlank { null },
                                    claimEmail = claimEmail.ifBlank { null },
                                    claimWebsite = claimWebsite.ifBlank { null },
                                    purchaseDate = purchaseDate.ifBlank { null },
                                    startDate = startDate.ifBlank { null },
                                    endDate = endDate.ifBlank { null },
                                    images = selectedImages
                                )
                            }
                        }
                    },
                    enabled = operationState !is ApiResult.Loading,
                    isLoading = operationState is ApiResult.Loading
                )
            }
        }
    }
}
