import SwiftUI
import SwiftData
import Contacts
import PhotosUI

struct AddPersonView: View {
    @Environment(\.nahbarTheme) var theme
    @Environment(\.modelContext) var modelContext
    @Environment(\.dismiss) var dismiss

    var existingPerson: Person? = nil

    @Query private var allPeople: [Person]

    @State private var name = ""
    @State private var selectedTag: PersonTag = .other
    @State private var occupation = ""
    @State private var location = ""
    @State private var interests = ""
    @State private var generalNotes = ""
    @State private var culturalBackground = ""
    @State private var phoneNumber = ""
    @State private var emailAddress = ""
    @State private var hasBirthday = false
    @State private var birthday = Date()
    @State private var nudgeFrequency: NudgeFrequency = .monthly

    @State private var showingContactPicker = false
    @State private var importedName: String? = nil  // tracks whether fields were pre-filled
    @State private var pendingCnIdentifier: String? = nil
    @State private var showingDeleteConfirmation = false

    @State private var selectedPhoto: UIImage? = nil
    @State private var photoPickerItem: PhotosPickerItem? = nil

    private var isEditing: Bool { existingPerson != nil }
    private var isValid: Bool { !name.trimmingCharacters(in: .whitespaces).isEmpty }

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(alignment: .leading, spacing: 24) {

                    // Photo picker
                    photoSection

                    // Contact import button (only when adding, not editing)
                    if !isEditing {
                        importButton
                    }

                    // Name
                    formSection("Name") {
                        TextField("Wie heißt diese Person?", text: $name)
                            .font(.system(size: 22, weight: .light, design: theme.displayDesign))
                            .foregroundStyle(theme.contentPrimary)
                            .tint(theme.accent)
                            .padding(.horizontal, 16)
                            .padding(.vertical, 14)
                            .background(theme.surfaceCard)
                            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    }

                    // Tag
                    formSection("Kontext") {
                        ScrollView(.horizontal, showsIndicators: false) {
                            HStack(spacing: 8) {
                                ForEach(PersonTag.allCases, id: \.self) { tag in
                                    Button {
                                        selectedTag = tag
                                    } label: {
                                        Text(tag.rawValue)
                                            .font(.system(size: 13, weight: selectedTag == tag ? .medium : .regular))
                                            .foregroundStyle(selectedTag == tag ? theme.accent : theme.contentSecondary)
                                            .padding(.horizontal, 14)
                                            .padding(.vertical, 8)
                                            .background(selectedTag == tag ? theme.accent.opacity(0.12) : theme.surfaceCard)
                                            .clipShape(Capsule())
                                    }
                                }
                            }
                        }
                    }

                    // Optional fields
                    formSection("Optional") {
                        VStack(spacing: 0) {
                            inlineField("Beruf", text: $occupation)
                            RowDivider()
                            inlineField("Wohnort", text: $location)
                            RowDivider()
                            InterestTagEditor(
                                label: "Interessen",
                                text: $interests,
                                suggestions: interestSuggestions,
                                tagColor: .green
                            )
                            RowDivider()
                            inlineField("Herkunft", text: $culturalBackground)
                            RowDivider()
                            inlineField("Notizen", text: $generalNotes)
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    }

                    // Kontaktdaten (Telefon + E-Mail)
                    formSection("Kontakt") {
                        VStack(spacing: 0) {
                            inlineField("Telefon", text: $phoneNumber)
                                .keyboardType(.phonePad)
                            RowDivider()
                            inlineField("E-Mail", text: $emailAddress)
                                .keyboardType(.emailAddress)
                                .textInputAutocapitalization(.never)
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    }

                    // Kontakt aktualisieren (nur im Bearbeiten-Modus)
                    if isEditing {
                        refreshContactButton
                    }

                    // Birthday
                    formSection("Geburtstag") {
                        VStack(spacing: 0) {
                            HStack {
                                Text("Geburtstag bekannt")
                                    .font(.system(size: 15))
                                    .foregroundStyle(theme.contentPrimary)
                                Spacer()
                                Toggle("", isOn: $hasBirthday.animation())
                                    .labelsHidden()
                                    .tint(theme.accent)
                            }
                            .padding(.horizontal, 16)
                            .padding(.vertical, 12)

                            if hasBirthday {
                                RowDivider()
                                DatePicker(
                                    "Datum",
                                    selection: $birthday,
                                    displayedComponents: .date
                                )
                                .datePickerStyle(.compact)
                                .font(.system(size: 15))
                                .foregroundStyle(theme.contentPrimary)
                                .tint(theme.accent)
                                .environment(\.locale, Locale(identifier: "de_DE"))
                                .padding(.horizontal, 16)
                                .padding(.vertical, 12)
                            }
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    }

                    // Nudge frequency
                    formSection("Wie oft melden?") {
                        VStack(alignment: .leading, spacing: 8) {
                            Text("Nahbar erinnert dich, wenn du diese Person seit der gewählten Zeit nicht mehr kontaktiert hast.")
                                .font(.system(size: 12))
                                .foregroundStyle(theme.contentTertiary)

                            VStack(spacing: 0) {
                                ForEach(NudgeFrequency.allCases, id: \.self) { freq in
                                    Button {
                                        nudgeFrequency = freq
                                    } label: {
                                        HStack {
                                            Text(freq.rawValue)
                                                .font(.system(size: 15))
                                                .foregroundStyle(theme.contentPrimary)
                                            Spacer()
                                            if nudgeFrequency == freq {
                                                Image(systemName: "checkmark")
                                                    .font(.system(size: 13, weight: .semibold))
                                                    .foregroundStyle(theme.accent)
                                            }
                                        }
                                        .padding(.horizontal, 16)
                                        .padding(.vertical, 12)
                                    }
                                    if freq != NudgeFrequency.allCases.last {
                                        RowDivider()
                                    }
                                }
                            }
                            .background(theme.surfaceCard)
                            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        }
                    }

                    // Delete link — only in edit mode
                    if isEditing {
                        Button {
                            showingDeleteConfirmation = true
                        } label: {
                            Text("Löschen")
                                .font(.system(size: 15))
                                .foregroundStyle(.red)
                        }
                        .frame(maxWidth: .infinity)
                        .padding(.top, 8)
                    }
                }
                .padding(.horizontal, 20)
                .padding(.top, 8)
                .padding(.bottom, 40)
            }
            .background(theme.backgroundPrimary.ignoresSafeArea())
            .navigationTitle(isEditing ? (existingPerson?.name ?? "") : "Jemanden hinzufügen")
            .navigationBarTitleDisplayMode(.inline)
            .themedNavBar()
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button("Abbrechen") { dismiss() }
                        .foregroundStyle(theme.contentSecondary)
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Button(isEditing ? "Fertig" : "Hinzufügen") { save() }
                        .font(.system(size: 15, weight: .semibold))
                        .foregroundStyle(isValid ? theme.accent : theme.contentTertiary)
                        .disabled(!isValid)
                }
            }
        }

        .confirmationDialog(
            "Diese Person wirklich löschen?",
            isPresented: $showingDeleteConfirmation,
            titleVisibility: .visible
        ) {
            Button("Löschen", role: .destructive) { deletePerson() }
            Button("Abbrechen", role: .cancel) {}
        } message: {
            Text("Alle Momente und Notizen zu dieser Person werden unwiderruflich gelöscht.")
        }
        .onAppear { loadExisting() }
        .overlay(alignment: .center) {
            SingleContactPickerTrigger(isPresented: $showingContactPicker, onSelect: applyContact)
                .frame(width: 0, height: 0)
                .allowsHitTesting(false)
        }
    }

    // MARK: - Photo Section

    private var photoSection: some View {
        VStack(spacing: 10) {
            PhotosPicker(selection: $photoPickerItem, matching: .images) {
                ZStack(alignment: .bottomTrailing) {
                    Group {
                        if let photo = selectedPhoto {
                            Image(uiImage: photo)
                                .resizable()
                                .scaledToFill()
                                .frame(width: 88, height: 88)
                                .clipShape(Circle())
                        } else {
                            Circle()
                                .fill(theme.accent.opacity(0.10))
                                .frame(width: 88, height: 88)
                                .overlay(
                                    Text(previewInitials)
                                        .font(.system(size: 32, weight: .medium, design: theme.displayDesign))
                                        .foregroundStyle(theme.accent)
                                )
                        }
                    }

                    Image(systemName: "camera.circle.fill")
                        .font(.system(size: 26))
                        .foregroundStyle(theme.accent)
                        .background(theme.backgroundPrimary, in: Circle())
                }
            }
            .onChange(of: photoPickerItem) { _, item in
                Task {
                    if let data = try? await item?.loadTransferable(type: Data.self),
                       let image = UIImage(data: data),
                       let resized = image.resizedForAvatar() {
                        selectedPhoto = resized
                    }
                }
            }

            if selectedPhoto != nil {
                Button {
                    selectedPhoto = nil
                    photoPickerItem = nil
                } label: {
                    Text("Foto entfernen")
                        .font(.system(size: 13))
                        .foregroundStyle(theme.contentTertiary)
                }
            }
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 4)
    }

    // Initials preview using current name input
    private var previewInitials: String {
        let parts = name.split(separator: " ")
        if parts.count >= 2 {
            return (parts[0].prefix(1) + parts[1].prefix(1)).uppercased()
        }
        return String(name.prefix(2)).uppercased().isEmpty ? "?" : String(name.prefix(2)).uppercased()
    }

    // MARK: - Import Button

    private var importButton: some View {
        Button {
            showingContactPicker = true
        } label: {
            HStack(spacing: 10) {
                Image(systemName: "person.crop.circle")
                    .font(.system(size: 16))
                    .foregroundStyle(theme.accent)

                VStack(alignment: .leading, spacing: 1) {
                    Text(importedName == nil ? "Aus Kontakten auswählen" : "Anderen Kontakt wählen")
                        .font(.system(size: 15, weight: .medium))
                        .foregroundStyle(theme.accent)
                    if let imported = importedName {
                        Text("Felder aus \"\(imported)\" übernommen")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                    } else {
                        Text("Felder werden automatisch ausgefüllt")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                    }
                }

                Spacer()

                Image(systemName: "chevron.right")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundStyle(theme.contentTertiary)
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 13)
            .background(theme.accent.opacity(0.07))
            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
            .overlay(
                RoundedRectangle(cornerRadius: theme.radiusCard)
                    .stroke(theme.accent.opacity(0.20), lineWidth: 1)
            )
        }
    }

    // MARK: - Vom Kontakt aktualisieren (Bearbeiten-Modus)

    private var refreshContactButton: some View {
        Button {
            showingContactPicker = true
        } label: {
            HStack(spacing: 10) {
                Image(systemName: "arrow.clockwise.circle")
                    .font(.system(size: 16))
                    .foregroundStyle(theme.contentSecondary)

                VStack(alignment: .leading, spacing: 1) {
                    Text("Vom Kontakt aktualisieren")
                        .font(.system(size: 15, weight: .medium))
                        .foregroundStyle(theme.contentSecondary)
                    Text("Leere Felder werden aus dem Adressbuch ergänzt")
                        .font(.system(size: 12))
                        .foregroundStyle(theme.contentTertiary)
                }

                Spacer()

                Image(systemName: "chevron.right")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundStyle(theme.contentTertiary)
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 13)
            .background(theme.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
        }
    }

    // MARK: - Contact Mapping

    private func applyContact(_ contact: CNContact) {
        let imported = ContactImport.from(contact)

        if !imported.name.isEmpty {
            name = imported.name
            importedName = imported.name
        }
        if !imported.occupation.isEmpty {
            occupation = imported.occupation
        }
        if !imported.location.isEmpty {
            location = imported.location
        }
        if let bday = imported.birthday {
            birthday = bday
            hasBirthday = true
        }
        if let data = imported.photoData {
            selectedPhoto = UIImage(data: data)
        }
        // Telefon und E-Mail: im Hinzufügen-Modus immer übernehmen,
        // im Bearbeiten-Modus nur wenn noch leer (nicht-destruktiv)
        if let phone = imported.phoneNumber, !phone.isEmpty {
            if phoneNumber.isEmpty { phoneNumber = phone }
        }
        if let email = imported.emailAddress, !email.isEmpty {
            if emailAddress.isEmpty { emailAddress = email }
        }
        pendingCnIdentifier = imported.cnIdentifier
    }

    // MARK: - Helpers

    @ViewBuilder
    private func formSection<Content: View>(_ label: String, @ViewBuilder content: () -> Content) -> some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(label.uppercased())
                .font(.system(size: 11, weight: .semibold))
                .tracking(0.8)
                .foregroundStyle(theme.contentTertiary)
            content()
        }
    }

    @ViewBuilder
    private func inlineField(_ label: String, text: Binding<String>) -> some View {
        HStack(spacing: 12) {
            Text(label)
                .font(.system(size: 15))
                .foregroundStyle(theme.contentTertiary)
                .frame(width: 80, alignment: .leading)
            TextField(label, text: text)
                .font(.system(size: 15))
                .foregroundStyle(theme.contentPrimary)
                .tint(theme.accent)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

    private var interestSuggestions: [String] {
        InterestTagHelper.allSuggestions(
            from: allPeople,
            likes: UserProfileStore.shared.likes,
            dislikes: UserProfileStore.shared.dislikes
        )
    }

    private func loadExisting() {
        guard let p = existingPerson else { return }
        name = p.name
        selectedTag = p.tag
        occupation = p.occupation ?? ""
        location = p.location ?? ""
        interests = p.interests ?? ""
        culturalBackground = p.culturalBackground ?? ""
        generalNotes = p.generalNotes ?? ""
        phoneNumber = p.phoneNumber ?? ""
        emailAddress = p.emailAddress ?? ""
        hasBirthday = p.birthday != nil
        birthday = p.birthday ?? Date()
        nudgeFrequency = p.nudgeFrequency
        // Bevorzuge migriertes PersonPhoto, falle auf Legacy-Feld zurück
        if let data = p.currentPhotoData {
            selectedPhoto = UIImage(data: data)
        }
    }

    private func save() {
        let trimmed = name.trimmingCharacters(in: .whitespaces)
        guard !trimmed.isEmpty else { return }

        let newPhotoData = selectedPhoto?.jpegData(compressionQuality: 0.8)

        if let p = existingPerson {
            p.name = trimmed
            p.tag = selectedTag
            p.occupation = occupation.isEmpty ? nil : occupation
            p.location = location.isEmpty ? nil : location
            p.interests = interests.isEmpty ? nil : interests
            p.culturalBackground = culturalBackground.isEmpty ? nil : culturalBackground
            p.generalNotes = generalNotes.isEmpty ? nil : generalNotes
            p.birthday = hasBirthday ? birthday : nil
            p.nudgeFrequency = nudgeFrequency
            p.phoneNumber = phoneNumber.isEmpty ? nil : phoneNumber
            p.emailAddress = emailAddress.isEmpty ? nil : emailAddress
            if let cn = pendingCnIdentifier { p.cnIdentifier = cn }
            p.touch()
            applyPhoto(newPhotoData, to: p)
        } else {
            let person = Person(
                name: trimmed,
                tag: selectedTag,
                birthday: hasBirthday ? birthday : nil,
                occupation: occupation.isEmpty ? nil : occupation,
                location: location.isEmpty ? nil : location,
                interests: interests.isEmpty ? nil : interests,
                generalNotes: generalNotes.isEmpty ? nil : generalNotes,
                culturalBackground: culturalBackground.isEmpty ? nil : culturalBackground,
                nudgeFrequency: nudgeFrequency
            )
            person.phoneNumber = phoneNumber.isEmpty ? nil : phoneNumber
            person.emailAddress = emailAddress.isEmpty ? nil : emailAddress
            person.cnIdentifier = pendingCnIdentifier
            modelContext.insert(person)
            applyPhoto(newPhotoData, to: person)
        }
        dismiss()
    }

    /// Speichert Foto als PersonPhoto (externalStorage) und räumt Legacy-Feld auf.
    private func applyPhoto(_ data: Data?, to person: Person) {
        if let data {
            if let existing = person.photo {
                existing.imageData = data
            } else {
                let photo = PersonPhoto(imageData: data)
                modelContext.insert(photo)
                person.photo = photo
            }
            person.photoData = nil   // Legacy bereinigen
        } else {
            person.photo    = nil    // Cascade löscht PersonPhoto
            person.photoData = nil
        }
    }

    private func deletePerson() {
        guard let p = existingPerson else { return }
        modelContext.delete(p)
        dismiss()
    }
}
