import SwiftUI
import SwiftData
import EventKit

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

    let person: Person

    @State private var text = ""
    @State private var selectedType: MomentType = .conversation
    @FocusState private var isFocused: Bool

    // Calendar
    @State private var addToCalendar = false
    @State private var eventDate: Date = {
        let cal = Calendar.current
        let hour = cal.component(.hour, from: Date())
        return cal.date(bySettingHour: hour + 1, minute: 0, second: 0, of: Date()) ?? Date()
    }()
    @State private var eventDuration: Double = 3600 // seconds; -1 = all-day

    private var isValid: Bool { !text.trimmingCharacters(in: .whitespaces).isEmpty }
    private var showsCalendarSection: Bool { selectedType == .meeting || selectedType == .intention }

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

                // Person context chip
                HStack(spacing: 10) {
                    PersonAvatar(person: person, size: 36)
                    Text(person.name)
                        .font(.system(size: 16, weight: .medium, design: theme.displayDesign))
                        .foregroundStyle(theme.contentPrimary)
                    Spacer()
                    Text(Date(), format: .dateTime.day().month(.abbreviated).locale(Locale(identifier: "de_DE")))
                        .font(.system(size: 13))
                        .foregroundStyle(theme.contentTertiary)
                }
                .padding(.horizontal, 20)
                .padding(.top, 8)

                // Type selector
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: 8) {
                        ForEach(MomentType.allCases, id: \.self) { type in
                            Button {
                                selectedType = type
                            } label: {
                                HStack(spacing: 5) {
                                    Image(systemName: type.icon)
                                        .font(.system(size: 12))
                                    Text(type.rawValue)
                                        .font(.system(size: 13, weight: selectedType == type ? .medium : .regular))
                                }
                                .foregroundStyle(selectedType == type ? theme.accent : theme.contentSecondary)
                                .padding(.horizontal, 12)
                                .padding(.vertical, 7)
                                .background(selectedType == type ? theme.accent.opacity(0.10) : theme.backgroundSecondary)
                                .clipShape(Capsule())
                            }
                        }
                    }
                    .padding(.horizontal, 20)
                }

                // Text input
                ZStack(alignment: .topLeading) {
                    if text.isEmpty {
                        Text("Was war der Kern des Gesprächs?\nWas möchtest du nicht vergessen?")
                            .font(.system(size: 16))
                            .foregroundStyle(theme.contentTertiary)
                            .padding(.horizontal, 16)
                            .padding(.vertical, 14)
                            .allowsHitTesting(false)
                    }
                    TextEditor(text: $text)
                        .font(.system(size: 16, design: theme.displayDesign))
                        .foregroundStyle(theme.contentPrimary)
                        .tint(theme.accent)
                        .scrollContentBackground(.hidden)
                        .padding(.horizontal, 12)
                        .padding(.vertical, 10)
                        .focused($isFocused)
                }
                .frame(minHeight: 180)
                .background(theme.surfaceCard)
                .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                .padding(.horizontal, 20)

                // Calendar section — shown for Treffen and Vorhaben
                if showsCalendarSection {
                    calendarSection
                        .transition(.opacity.combined(with: .move(edge: .top)))
                }

                Spacer()
            }
            .animation(.easeInOut(duration: 0.2), value: showsCalendarSection)
            .animation(.easeInOut(duration: 0.2), value: addToCalendar)
            .background(theme.backgroundPrimary.ignoresSafeArea())
            .navigationTitle("Moment festhalten")
            .navigationBarTitleDisplayMode(.inline)
            .themedNavBar()
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button("Abbrechen") { dismiss() }
                        .foregroundStyle(theme.contentSecondary)
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Button("Speichern") { save() }
                        .font(.system(size: 15, weight: .semibold))
                        .foregroundStyle(isValid ? theme.accent : theme.contentTertiary)
                        .disabled(!isValid)
                }
            }
        }
        .onAppear { isFocused = true }
    }

    // MARK: - Calendar Section

    private var calendarSection: some View {
        VStack(spacing: 0) {
            HStack {
                Image(systemName: "calendar")
                    .font(.system(size: 14))
                    .foregroundStyle(addToCalendar ? theme.accent : theme.contentTertiary)
                Text("Termin anlegen")
                    .font(.system(size: 15))
                    .foregroundStyle(theme.contentPrimary)
                Spacer()
                Toggle("", isOn: $addToCalendar)
                    .tint(theme.accent)
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 12)

            if addToCalendar {
                RowDivider()

                DatePicker(
                    "Wann?",
                    selection: $eventDate,
                    in: Date()...,
                    displayedComponents: [.date, .hourAndMinute]
                )
                .font(.system(size: 15))
                .foregroundStyle(theme.contentPrimary)
                .tint(theme.accent)
                .padding(.horizontal, 16)
                .padding(.vertical, 10)

                RowDivider()

                HStack {
                    Text("Dauer")
                        .font(.system(size: 15))
                        .foregroundStyle(theme.contentPrimary)
                    Spacer()
                    Picker("", selection: $eventDuration) {
                        Text("30 Min").tag(1800.0)
                        Text("1 Std").tag(3600.0)
                        Text("2 Std").tag(7200.0)
                        Text("Halbtag").tag(14400.0)
                        Text("Ganztag").tag(-1.0)
                    }
                    .tint(theme.accent)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 4)
            }
        }
        .background(theme.surfaceCard)
        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
        .padding(.horizontal, 20)
    }

    // MARK: - Save

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

        let moment = Moment(text: trimmed, type: selectedType, person: person)
        modelContext.insert(moment)
        person.moments?.append(moment)

        guard addToCalendar else {
            dismiss()
            return
        }

        let dateStr = eventDate.formatted(.dateTime.day().month(.abbreviated).hour().minute().locale(Locale(identifier: "de_DE")))
        let calEntry = LogEntry(
            type: .calendarEvent,
            title: "Treffen mit \(person.firstName) — \(dateStr)",
            person: person
        )
        modelContext.insert(calEntry)
        person.logEntries?.append(calEntry)

        // Kein async/await — Callback-API vermeidet "unsafeForcedSync"
        createCalendarEvent(notes: trimmed)
    }

    // MARK: - EventKit (callback-basiert, kein Swift Concurrency)

    private func createCalendarEvent(notes: String) {
        let store = EKEventStore()

        let completion: (Bool, Error?) -> Void = { [store] granted, _ in
            guard granted, let calendar = store.defaultCalendarForNewEvents else {
                DispatchQueue.main.async { self.dismiss() }
                return
            }

            let event = EKEvent(eventStore: store)
            event.title = "Treffen mit \(self.person.firstName)"
            event.notes = notes.isEmpty ? nil : notes
            event.calendar = calendar

            if self.eventDuration < 0 {
                event.isAllDay = true
                let dayStart = Calendar.current.startOfDay(for: self.eventDate)
                event.startDate = dayStart
                event.endDate = Calendar.current.date(byAdding: .day, value: 1, to: dayStart) ?? dayStart
            } else {
                event.startDate = self.eventDate
                event.endDate = self.eventDate.addingTimeInterval(self.eventDuration)
            }

            try? store.save(event, span: .thisEvent)
            DispatchQueue.main.async { self.dismiss() }
        }

        if #available(iOS 17.0, *) {
            store.requestWriteOnlyAccessToEvents(completion: completion)
        } else {
            store.requestAccess(to: .event, completion: completion)
        }
    }
}
