import SwiftUI

/// Einfache Personen-Darstellung für die Share Extension (aus UserDefaults-Cache).
struct CachedPerson: Identifiable, Equatable {
    let id: UUID
    let name: String
    let tag: String
}

struct ShareExtensionView: View {
    let sharedText: String
    let onDismiss: () -> Void

    @State private var text: String
    @State private var momentType: MomentType = .conversation
    @State private var momentSource: MomentSource = .other
    @State private var people: [CachedPerson] = []
    @State private var selectedPerson: CachedPerson?
    @State private var searchText = ""
    @State private var isSaving = false
    @State private var errorMessage: String?
    @State private var isProUser: Bool = false

    init(sharedText: String, onDismiss: @escaping () -> Void) {
        self.sharedText = sharedText
        self.onDismiss = onDismiss
        self._text = State(initialValue: sharedText)
    }

    private var filteredPeople: [CachedPerson] {
        searchText.isEmpty ? people : people.filter {
            $0.name.localizedCaseInsensitiveContains(searchText)
        }
    }

    var body: some View {
        NavigationStack {
            if !isProUser {
                proRequiredView
            } else {
            Form {
                Section("Nachricht") {
                    TextEditor(text: $text)
                        .frame(minHeight: 80)
                        .font(.system(size: 15))
                }

                Section("Typ") {
                    Picker("Typ", selection: $momentType) {
                        ForEach(MomentType.allCases, id: \.self) { type in
                            Label(type.displayName, systemImage: type.icon).tag(type)
                        }
                    }
                    .pickerStyle(.segmented)
                    .labelsHidden()
                }

                Section("Herkunft") {
                    Picker("Messenger", selection: $momentSource) {
                        ForEach(MomentSource.allCases, id: \.self) { source in
                            Label(source.rawValue, systemImage: source.icon).tag(source)
                        }
                    }
                    .pickerStyle(.menu)
                }

                Section("Kontakt") {
                    if people.isEmpty {
                        Text("Keine Kontakte gefunden. Öffne nahbar einmal, damit die Kontakte hier erscheinen.")
                            .foregroundStyle(.secondary)
                            .font(.system(size: 14))
                    } else {
                        TextField("Suchen…", text: $searchText)
                        ForEach(filteredPeople) { person in
                            PersonPickerRow(
                                name: person.name,
                                tag: person.tag,
                                isSelected: selectedPerson?.id == person.id
                            ) {
                                selectedPerson = (selectedPerson?.id == person.id) ? nil : person
                            }
                        }
                    }
                }

                if let error = errorMessage {
                    Section {
                        Text(error)
                            .foregroundStyle(.red)
                            .font(.caption)
                    }
                }
            }
            .navigationTitle("In nahbar speichern")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Abbrechen", action: onDismiss)
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Speichern") { save() }
                        .disabled(selectedPerson == nil || text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isSaving)
                }
            }
            } // end if isProUser
        }
        .onAppear {
            isProUser = AppGroup.isProUser
            if isProUser { loadPeople() }
        }
    }

    // MARK: - Pro Required

    private var proRequiredView: some View {
        VStack(spacing: 20) {
            Spacer()
            Image(systemName: "lock.fill")
                .font(.system(size: 40))
                .foregroundStyle(.secondary)
            Text("nahbar Pro erforderlich")
                .font(.headline)
            Text("Die Teilen-Funktion ist in nahbar Pro enthalten. Öffne nahbar, um dein Abo zu verwalten.")
                .font(.subheadline)
                .foregroundStyle(.secondary)
                .multilineTextAlignment(.center)
                .padding(.horizontal, 32)
            Button("Schließen", action: onDismiss)
                .buttonStyle(.borderedProminent)
            Spacer()
        }
        .navigationTitle("In nahbar speichern")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .cancellationAction) {
                Button("Abbrechen", action: onDismiss)
            }
        }
    }

    // MARK: - Subviews

    struct PersonPickerRow: View {
        let name: String
        let tag: String
        let isSelected: Bool
        let onTap: () -> Void

        var body: some View {
            Button(action: onTap) {
                HStack {
                    VStack(alignment: .leading, spacing: 2) {
                        Text(name).foregroundStyle(.primary)
                        Text(tag).font(.caption).foregroundStyle(.secondary)
                    }
                    Spacer()
                    if isSelected {
                        Image(systemName: "checkmark").foregroundStyle(Color.accentColor)
                    }
                }
            }
            .buttonStyle(.plain)
        }
    }

    // MARK: - Data

    private func loadPeople() {
        people = AppGroup.cachedPeople.compactMap { dict in
            guard let idString = dict["id"], let id = UUID(uuidString: idString),
                  let name = dict["name"], let tag = dict["tag"] else { return nil }
            return CachedPerson(id: id, name: name, tag: tag)
        }
    }

    private func save() {
        guard let person = selectedPerson else { return }
        let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return }
        isSaving = true
        AppGroup.enqueueMoment(personID: person.id, personName: person.name, text: trimmed, type: momentType.rawValue, source: momentSource.rawValue)
        onDismiss()
    }
}
