import SwiftUI
import ComposeApp
import PhotosUI

struct DocumentFormView: View {
    let residenceId: Int32?
    let existingDocument: Document?
    let initialDocumentType: String
    @Binding var isPresented: Bool
    @ObservedObject var documentViewModel: DocumentViewModel
    @StateObject private var residenceViewModel = ResidenceViewModel()
    @Environment(\.dismiss) private var dismiss

    private var isEditMode: Bool {
        existingDocument != nil
    }

    private var needsResidenceSelection: Bool {
        residenceId == nil && !isEditMode
    }

    // Form fields
    @State private var title = ""
    @State private var description = ""
    @State private var selectedDocumentType: String
    @State private var selectedCategory: String? = nil
    @State private var notes = ""
    @State private var tags = ""
    @State private var isActive = true

    // Warranty-specific fields
    @State private var itemName = ""
    @State private var modelNumber = ""
    @State private var serialNumber = ""
    @State private var provider = ""
    @State private var providerContact = ""
    @State private var claimPhone = ""
    @State private var claimEmail = ""
    @State private var claimWebsite = ""
    @State private var purchaseDate = ""
    @State private var startDate = ""
    @State private var endDate = ""

    // Residence selection
    @State private var selectedResidenceId: Int? = nil

    // Image management
    @State private var existingImages: [DocumentImage] = []
    @State private var imagesToDelete: Set<Int32> = []
    @State private var selectedPhotoItems: [PhotosPickerItem] = []
    @State private var selectedImages: [UIImage] = []
    @State private var showCamera = false

    // Focus management for keyboard transitions
    enum DocumentFormField: Hashable {
        case title, itemName, modelNumber, serialNumber, provider, providerContact, notes
    }
    @FocusState private var focusedField: DocumentFormField?

    // Validation errors
    @State private var titleError = ""
    @State private var itemNameError = ""
    @State private var providerError = ""
    @State private var residenceError = ""

    // UI state
    @State private var isProcessing = false
    @State private var showAlert = false
    @State private var alertMessage = ""

    init(residenceId: Int32?, existingDocument: Document?, initialDocumentType: String, isPresented: Binding<Bool>, documentViewModel: DocumentViewModel) {
        self.residenceId = residenceId
        self.existingDocument = existingDocument
        self.initialDocumentType = initialDocumentType
        self._isPresented = isPresented
        self.documentViewModel = documentViewModel
        self._selectedDocumentType = State(initialValue: existingDocument?.documentType ?? initialDocumentType)

        // Initialize state from existing document
        if let doc = existingDocument {
            self._title = State(initialValue: doc.title)
            self._description = State(initialValue: doc.description_ ?? "")
            self._selectedCategory = State(initialValue: doc.category)
            self._tags = State(initialValue: doc.tags ?? "")
            self._notes = State(initialValue: doc.notes ?? "")
            self._isActive = State(initialValue: doc.isActive)
            self._itemName = State(initialValue: doc.itemName ?? "")
            self._modelNumber = State(initialValue: doc.modelNumber ?? "")
            self._serialNumber = State(initialValue: doc.serialNumber ?? "")
            self._provider = State(initialValue: doc.provider ?? "")
            self._providerContact = State(initialValue: doc.providerContact ?? "")
            self._claimPhone = State(initialValue: doc.claimPhone ?? "")
            self._claimEmail = State(initialValue: doc.claimEmail ?? "")
            self._claimWebsite = State(initialValue: doc.claimWebsite ?? "")
            self._purchaseDate = State(initialValue: doc.purchaseDate ?? "")
            self._startDate = State(initialValue: doc.startDate ?? "")
            self._endDate = State(initialValue: doc.endDate ?? "")
        }
    }

    var isWarranty: Bool {
        selectedDocumentType == "warranty"
    }

    var canSave: Bool {
        !title.isEmpty &&
        (!needsResidenceSelection || selectedResidenceId != nil) &&
        (!isWarranty || (!itemName.isEmpty && !provider.isEmpty))
    }

    var residencesArray: [(id: Int, name: String)] {
        guard let residences = residenceViewModel.myResidences?.residences else {
            return []
        }
        return residences.map { residenceWithTasks in
            (id: Int(residenceWithTasks.id), name: residenceWithTasks.name)
        }
    }

    @ViewBuilder
    private var warrantySection: some View {
        if isWarranty {
            Section {
                TextField(L10n.Documents.itemName, text: $itemName)
                    .focused($focusedField, equals: .itemName)
                    .submitLabel(.next)
                    .onSubmit { focusedField = .modelNumber }
                    .accessibilityIdentifier(AccessibilityIdentifiers.Document.itemNameField)
                if !itemNameError.isEmpty {
                    Text(itemNameError)
                        .font(.caption)
                        .foregroundColor(Color.appError)
                }

                TextField(L10n.Documents.modelNumberOptional, text: $modelNumber)
                    .focused($focusedField, equals: .modelNumber)
                    .submitLabel(.next)
                    .onSubmit { focusedField = .serialNumber }
                    .accessibilityIdentifier(AccessibilityIdentifiers.Document.modelNumberField)
                TextField(L10n.Documents.serialNumberOptional, text: $serialNumber)
                    .focused($focusedField, equals: .serialNumber)
                    .submitLabel(.next)
                    .onSubmit { focusedField = .provider }
                    .accessibilityIdentifier(AccessibilityIdentifiers.Document.serialNumberField)

                TextField(L10n.Documents.providerCompany, text: $provider)
                    .focused($focusedField, equals: .provider)
                    .textContentType(.organizationName)
                    .submitLabel(.next)
                    .onSubmit { focusedField = .providerContact }
                    .accessibilityIdentifier(AccessibilityIdentifiers.Document.providerField)
                if !providerError.isEmpty {
                    Text(providerError)
                        .font(.caption)
                        .foregroundColor(Color.appError)
                }

                TextField(L10n.Documents.providerContactOptional, text: $providerContact)
                    .focused($focusedField, equals: .providerContact)
                    .textContentType(.telephoneNumber)
                    .submitLabel(.done)
                    .onSubmit { focusedField = nil }
                    .accessibilityIdentifier(AccessibilityIdentifiers.Document.providerContactField)
            } header: {
                Text(L10n.Documents.warrantyDetails)
                    .accessibilityAddTraits(.isHeader)
            } footer: {
                Text(L10n.Documents.requiredWarrantyFields)
                    .font(.caption)
                    .foregroundColor(Color.appError)
            }
            .sectionBackground()

            Section(L10n.Documents.warrantyClaims) {
                TextField(L10n.Documents.claimPhoneOptional, text: $claimPhone)
                    .keyboardType(.phonePad)
                    .keyboardDismissToolbar()
                TextField(L10n.Documents.claimEmailOptional, text: $claimEmail)
                    .keyboardType(.emailAddress)
                TextField(L10n.Documents.claimWebsiteOptional, text: $claimWebsite)
                    .keyboardType(.URL)
            }
            .sectionBackground()

            Section(L10n.Documents.warrantyDates) {
                TextField(L10n.Documents.purchaseDate, text: $purchaseDate)
                TextField(L10n.Documents.startDate, text: $startDate)
                TextField(L10n.Documents.endDate, text: $endDate)
            }
            .sectionBackground()
        }
    }

    @ViewBuilder
    private var photosSections: some View {
        if isEditMode && !existingImages.isEmpty {
            Section(L10n.Documents.existingPhotos) {
                ForEach(existingImages, id: \.id) { image in
                    AuthenticatedImage(mediaURL: image.mediaUrl)
                        .frame(height: 200)
                }
            }
            .sectionBackground()
        }

        Section(L10n.Documents.photos) {
            PhotosPicker(selection: $selectedPhotoItems, maxSelectionCount: isEditMode ? 10 : 5, matching: .images) {
                Label(L10n.Documents.selectFromLibrary, systemImage: "photo")
            }

            Button {
                showCamera = true
            } label: {
                Label(L10n.Documents.takePhoto, systemImage: "camera")
            }

            if !selectedImages.isEmpty {
                Text(String(format: L10n.Documents.photosSelected, selectedImages.count))
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
        }
        .sectionBackground()
    }

    var body: some View {
        NavigationStack {
            Form {
                formContent
            }
            .listStyle(.plain)
            .scrollContentBackground(.hidden)
            .background(Color.appBackgroundPrimary)
            .navigationTitle(isEditMode ? (isWarranty ? L10n.Documents.editWarranty : L10n.Documents.editDocument) : (isWarranty ? L10n.Documents.addWarranty : L10n.Documents.addDocument))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button(L10n.Common.cancel) {
                        if isEditMode {
                            dismiss()
                        } else {
                            isPresented = false
                        }
                    }
                    .accessibilityIdentifier(AccessibilityIdentifiers.Document.formCancelButton)
                }

                ToolbarItem(placement: .confirmationAction) {
                    Button(isEditMode ? L10n.Common.save : L10n.Common.add) {
                        submitForm()
                    }
                    .disabled(!canSave || isProcessing)
                    .accessibilityIdentifier(AccessibilityIdentifiers.Document.saveButton)
                }
            }
            .sheet(isPresented: $showCamera) {
                ImagePicker(image: Binding(
                    get: { nil },
                    set: { image in
                        if let image = image {
                            selectedImages.append(image)
                        }
                    }
                ))
            }
            .onChange(of: selectedPhotoItems) { _, items in
                Task {
                    selectedImages.removeAll()
                    for item in items {
                        if let data = try? await item.loadTransferable(type: Data.self),
                           let image = UIImage(data: data) {
                            selectedImages.append(image)
                        }
                    }
                }
            }
            .onAppear {
                // Track screen view for new documents
                if !isEditMode {
                    let docType = isWarranty ? "warranty" : "document"
                    AnalyticsManager.shared.trackScreen(.newDocument, properties: ["type": docType])
                }
                if needsResidenceSelection {
                    residenceViewModel.loadMyResidences()
                }
                if isEditMode, let doc = existingDocument {
                    existingImages = doc.images
                }
            }
            .alert(L10n.Common.error, isPresented: $showAlert) {
                Button(L10n.Common.ok, role: .cancel) {}
            } message: {
                Text(alertMessage)
            }
        }
    }

    @ViewBuilder
    private var formContent: some View {
                // Residence Selection (Add mode only, if needed)
                if needsResidenceSelection {
                    Section {
                        if residenceViewModel.isLoading {
                            ProgressView()
                        } else {
                            Picker(L10n.Documents.selectProperty, selection: $selectedResidenceId) {
                                Text(L10n.Documents.selectProperty).tag(nil as Int?)
                                ForEach(residencesArray, id: \.id) { residence in
                                    Text(residence.name).tag(residence.id as Int?)
                                }
                            }
                            .accessibilityIdentifier(AccessibilityIdentifiers.Document.residencePicker)

                            if !residenceError.isEmpty {
                                Text(residenceError)
                                    .font(.caption)
                                    .foregroundColor(Color.appError)
                            }
                        }
                    } header: {
                        Text(L10n.Documents.property)
                    } footer: {
                        Text(L10n.Documents.required)
                            .font(.caption)
                            .foregroundColor(Color.appError)
                    }
                    .sectionBackground()
                }

                // Document Type
                Section {
                    if isEditMode {
                        HStack {
                            Text(L10n.Documents.documentType)
                            Spacer()
                            Text(DocumentTypeHelper.displayName(for: selectedDocumentType))
                                .foregroundColor(.secondary)
                        }
                        Text(L10n.Documents.documentTypeCannotChange)
                            .font(.caption)
                            .foregroundColor(.secondary)
                    } else {
                        Picker(L10n.Documents.documentType, selection: $selectedDocumentType) {
                            ForEach(DocumentTypeHelper.allTypes, id: \.self) { type in
                                Text(DocumentTypeHelper.displayName(for: type)).tag(type)
                            }
                        }
                    }
                }
                .sectionBackground()

                // Basic Information
                Section {
                    TextField(L10n.Documents.titleField, text: $title)
                        .accessibilityIdentifier(AccessibilityIdentifiers.Document.titleField)
                    if !titleError.isEmpty {
                        Text(titleError)
                            .font(.caption)
                            .foregroundColor(Color.appError)
                    }

                    TextField(L10n.Documents.descriptionOptional, text: $description, axis: .vertical)
                        .lineLimit(3...6)
                        .keyboardDismissToolbar()
                } header: {
                    Text(L10n.Documents.basicInformation)
                        .accessibilityAddTraits(.isHeader)
                } footer: {
                    Text(L10n.Documents.requiredTitle)
                        .font(.caption)
                        .foregroundColor(Color.appError)
                }
                .sectionBackground()

                // Warranty-specific fields
                warrantySection

                // Category
                if isWarranty || ["inspection", "manual", "receipt"].contains(selectedDocumentType) {
                    Section(L10n.Documents.category) {
                        Picker(L10n.Documents.categoryOptional, selection: $selectedCategory) {
                            Text(L10n.Documents.none).tag(nil as String?)
                            ForEach(DocumentCategoryHelper.allCategories, id: \.self) { category in
                                Text(DocumentCategoryHelper.displayName(for: category)).tag(category as String?)
                            }
                        }
                        .accessibilityIdentifier(AccessibilityIdentifiers.Document.categoryPicker)
                    }
                    .sectionBackground()
                }

                // Additional Information
                Section(L10n.Documents.additionalInformation) {
                    TextField(L10n.Documents.tagsOptional, text: $tags)
                        .accessibilityIdentifier(AccessibilityIdentifiers.Document.tagsField)
                        .textInputAutocapitalization(.never)
                    TextField(L10n.Documents.notesOptional, text: $notes, axis: .vertical)
                        .lineLimit(3...6)
                        .keyboardDismissToolbar()
                        .accessibilityIdentifier(AccessibilityIdentifiers.Document.notesField)
                }
                .sectionBackground()

                // Active Status (Edit mode only)
                if isEditMode {
                    Section {
                        Toggle(L10n.Documents.active, isOn: $isActive)
                    }
                    .sectionBackground()
                }

                // Photos
                photosSections
    }

    private func validateForm() -> Bool {
        var isValid = true

        titleError = ""
        itemNameError = ""
        providerError = ""
        residenceError = ""

        if title.isEmpty {
            titleError = L10n.Documents.titleRequired
            isValid = false
        }

        if needsResidenceSelection && selectedResidenceId == nil {
            residenceError = L10n.Documents.propertyRequired
            isValid = false
        }

        if isWarranty {
            if itemName.isEmpty {
                itemNameError = L10n.Documents.itemNameRequired
                isValid = false
            }
            if provider.isEmpty {
                providerError = L10n.Documents.providerRequired
                isValid = false
            }
        }

        return isValid
    }

    private func submitForm() {
        guard validateForm() else {
            alertMessage = L10n.Documents.fillRequiredFields
            showAlert = true
            return
        }

        isProcessing = true

        let actualResidenceId: Int32
        if let existingDoc = existingDocument {
            actualResidenceId = Int32(existingDoc.residence)
        } else if let providedId = residenceId {
            actualResidenceId = providedId
        } else if let selectedId = selectedResidenceId {
            actualResidenceId = Int32(selectedId)
        } else {
            isProcessing = false
            alertMessage = L10n.Documents.noResidenceSelected
            showAlert = true
            return
        }

        if isEditMode, let doc = existingDocument {
            // Update document
            guard let docId = doc.id else {
                isProcessing = false
                alertMessage = L10n.Documents.documentIdMissing
                showAlert = true
                return
            }

            documentViewModel.updateDocument(
                id: Int32(docId.intValue),
                title: title,
                documentType: selectedDocumentType,
                description: description.isEmpty ? nil : description,
                category: selectedCategory,
                tags: tags.isEmpty ? nil : tags,
                notes: notes.isEmpty ? nil : notes,
                contractorId: nil,
                isActive: isActive,
                itemName: itemName.isEmpty ? nil : itemName,
                modelNumber: modelNumber.isEmpty ? nil : modelNumber,
                serialNumber: serialNumber.isEmpty ? nil : serialNumber,
                provider: provider.isEmpty ? nil : provider,
                providerContact: providerContact.isEmpty ? nil : providerContact,
                claimPhone: claimPhone.isEmpty ? nil : claimPhone,
                claimEmail: claimEmail.isEmpty ? nil : claimEmail,
                claimWebsite: claimWebsite.isEmpty ? nil : claimWebsite,
                purchaseDate: purchaseDate.isEmpty ? nil : purchaseDate,
                startDate: startDate.isEmpty ? nil : startDate,
                endDate: endDate.isEmpty ? nil : endDate,
                newImages: selectedImages
            ) { success, error in
                isProcessing = false
                if success {
                    // Reload documents to show updated item
                    documentViewModel.loadDocuments(residenceId: residenceId)
                    dismiss()
                } else {
                    alertMessage = error ?? L10n.Documents.failedToUpdate
                    showAlert = true
                }
            }
        } else {
            // Create document
            documentViewModel.createDocument(
                title: title,
                documentType: selectedDocumentType,
                residenceId: actualResidenceId,
                description: description.isEmpty ? nil : description,
                category: selectedCategory,
                tags: tags.isEmpty ? nil : tags,
                notes: notes.isEmpty ? nil : notes,
                contractorId: nil,
                isActive: isActive,
                itemName: itemName.isEmpty ? nil : itemName,
                modelNumber: modelNumber.isEmpty ? nil : modelNumber,
                serialNumber: serialNumber.isEmpty ? nil : serialNumber,
                provider: provider.isEmpty ? nil : provider,
                providerContact: providerContact.isEmpty ? nil : providerContact,
                claimPhone: claimPhone.isEmpty ? nil : claimPhone,
                claimEmail: claimEmail.isEmpty ? nil : claimEmail,
                claimWebsite: claimWebsite.isEmpty ? nil : claimWebsite,
                purchaseDate: purchaseDate.isEmpty ? nil : purchaseDate,
                startDate: startDate.isEmpty ? nil : startDate,
                endDate: endDate.isEmpty ? nil : endDate,
                images: selectedImages
            ) { success, error in
                isProcessing = false
                if success {
                    // Track document creation
                    let docType = isWarranty ? "warranty" : "document"
                    AnalyticsManager.shared.track(.documentCreated(type: docType))
                    // Reload documents to show new item
                    documentViewModel.loadDocuments(residenceId: actualResidenceId)
                    isPresented = false
                } else {
                    alertMessage = error ?? L10n.Documents.failedToCreate
                    showAlert = true
                }
            }
        }
    }
}

// Simple image picker wrapper
struct ImagePicker: UIViewControllerRepresentable {
    @Binding var image: UIImage?
    @Environment(\.dismiss) private var dismiss

    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        picker.sourceType = .camera
        return picker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        let parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
            if let image = info[.originalImage] as? UIImage {
                parent.image = image
            }
            parent.dismiss()
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            parent.dismiss()
        }
    }
}
