import SwiftUI
import SwiftData

// MARK: - Interest Tag Helper

/// Rein-statische Hilfsfunktionen für kommaseparierte Interessen-Tags.
enum InterestTagHelper {

    /// Zerlegt einen kommaseparierten String in bereinigte, nicht-leere Tags.
    static func parse(_ text: String) -> [String] {
        text.split(separator: ",")
            .map { $0.trimmingCharacters(in: .whitespaces) }
            .filter { !$0.isEmpty }
    }

    /// Sortiert Tags alphabetisch und verbindet sie zu einem kommaseparierten String.
    static func join(_ tags: [String]) -> String {
        tags.sorted(by: { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending })
            .joined(separator: ", ")
    }

    /// Fügt einen Tag hinzu (ignoriert Duplikate, Groß-/Kleinschreibung irrelevant).
    /// Ergebnis ist alphabetisch sortiert.
    static func addTag(_ tag: String, to text: String) -> String {
        let trimmed = tag.trimmingCharacters(in: .whitespaces)
        guard !trimmed.isEmpty else { return text }
        var current = parse(text)
        let alreadyExists = current.contains { $0.localizedCaseInsensitiveCompare(trimmed) == .orderedSame }
        guard !alreadyExists else { return text }
        current.append(trimmed)
        return join(current)
    }

    /// Entfernt einen Tag aus dem kommaseparierten String.
    static func removeTag(_ tag: String, from text: String) -> String {
        let updated = parse(text).filter { $0.localizedCaseInsensitiveCompare(tag) != .orderedSame }
        return join(updated)
    }

    /// Sammelt alle vorhandenen Tags aus Personen-Interessen, User-Likes und Dislikes.
    /// Dedupliziert und alphabetisch sortiert.
    static func allSuggestions(from people: [Person], likes: String, dislikes: String) -> [String] {
        let personTags = people.flatMap { parse($0.interests ?? "") }
        let userTags   = parse(likes) + parse(dislikes)
        let combined   = Set(personTags + userTags)
        return combined.sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }
    }
}

// MARK: - Interest Chip Row (Display-only)

/// Zeigt kommaseparierte Interessen-Tags als horizontale Chip-Reihe an.
/// Verwendung in PersonDetailView und IchView (Display-Modus).
struct InterestChipRow: View {
    @Environment(\.nahbarTheme) private var theme
    let label: String
    let text: String
    let color: Color

    private var tags: [String] { InterestTagHelper.parse(text) }

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(label)
                .font(.system(size: 13))
                .foregroundStyle(theme.contentTertiary)
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 6) {
                    ForEach(tags, id: \.self) { tag in
                        Text(tag)
                            .font(.system(size: 13))
                            .foregroundStyle(color)
                            .padding(.horizontal, 10)
                            .padding(.vertical, 5)
                            .background(color.opacity(0.12))
                            .clipShape(Capsule())
                    }
                }
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}

// MARK: - Interest Tag Editor

/// Bearbeitbares Tag-Eingabefeld mit Autocomplete.
/// Bestehendes Tags werden als entfernbare farbige Chips gezeigt.
/// Beim Tippen erscheint eine horizontale Chip-Reihe passender Vorschläge.
struct InterestTagEditor: View {
    @Environment(\.nahbarTheme) private var theme
    let label: String
    @Binding var text: String
    let suggestions: [String]
    let tagColor: Color

    @State private var inputText = ""
    @FocusState private var inputFocused: Bool

    private var tags: [String] { InterestTagHelper.parse(text) }

    private var filteredSuggestions: [String] {
        let q = inputText.trimmingCharacters(in: .whitespaces)
        guard !q.isEmpty else { return [] }
        return suggestions.filter { suggestion in
            suggestion.localizedCaseInsensitiveContains(q) &&
            !tags.contains { $0.localizedCaseInsensitiveCompare(suggestion) == .orderedSame }
        }
    }

    private func addTag(_ tag: String) {
        text = InterestTagHelper.addTag(tag, to: text)
        inputText = ""
    }

    private func removeTag(_ tag: String) {
        text = InterestTagHelper.removeTag(tag, from: text)
    }

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

            // Zeile 1: bestehende Tags + ggf. Platzhalter
            HStack(alignment: .top, spacing: 12) {
                Text(label)
                    .font(.system(size: 15))
                    .foregroundStyle(theme.contentTertiary)
                    .frame(width: 80, alignment: .leading)
                    .padding(.top, tags.isEmpty ? 0 : 2)

                if tags.isEmpty {
                    Text("noch keine")
                        .font(.system(size: 15))
                        .foregroundStyle(theme.contentTertiary.opacity(0.45))
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .contentShape(Rectangle())
                        .onTapGesture { inputFocused = true }
                } else {
                    ScrollView(.horizontal, showsIndicators: false) {
                        HStack(spacing: 6) {
                            ForEach(tags, id: \.self) { tag in
                                HStack(spacing: 3) {
                                    Text(tag)
                                        .font(.system(size: 13))
                                    Button {
                                        removeTag(tag)
                                    } label: {
                                        Image(systemName: "xmark")
                                            .font(.system(size: 9, weight: .bold))
                                    }
                                }
                                .foregroundStyle(tagColor)
                                .padding(.leading, 10)
                                .padding(.trailing, 7)
                                .padding(.vertical, 5)
                                .background(tagColor.opacity(0.12))
                                .clipShape(Capsule())
                            }
                        }
                    }
                }
            }

            // Zeile 2: Texteingabe
            HStack(spacing: 12) {
                Spacer().frame(width: 80)
                TextField("Tag hinzufügen…", text: $inputText)
                    .font(.system(size: 14))
                    .foregroundStyle(theme.contentPrimary)
                    .tint(theme.accent)
                    .focused($inputFocused)
                    .submitLabel(.done)
                    .onSubmit {
                        addTag(inputText)
                    }
                    .onChange(of: inputText) { _, new in
                        // Komma-Eingabe als Trennzeichen
                        if new.hasSuffix(",") {
                            let candidate = String(new.dropLast())
                            addTag(candidate)
                        }
                    }
            }

            // Zeile 3: Vorschlags-Chips (nur während Eingabe)
            if !filteredSuggestions.isEmpty {
                HStack(spacing: 12) {
                    Spacer().frame(width: 80)
                    ScrollView(.horizontal, showsIndicators: false) {
                        HStack(spacing: 6) {
                            ForEach(filteredSuggestions, id: \.self) { suggestion in
                                Button { addTag(suggestion) } label: {
                                    Text(suggestion)
                                        .font(.system(size: 12))
                                        .foregroundStyle(theme.contentSecondary)
                                        .padding(.horizontal, 10)
                                        .padding(.vertical, 4)
                                        .background(theme.backgroundSecondary)
                                        .clipShape(Capsule())
                                        .overlay(
                                            Capsule().stroke(theme.borderSubtle, lineWidth: 0.5)
                                        )
                                }
                            }
                        }
                    }
                }
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}

// MARK: - Person Avatar

struct PersonAvatar: View {
    @Environment(\.nahbarTheme) var theme
    let person: Person
    let size: CGFloat

    var body: some View {
        Group {
            // currentPhotoData bevorzugt photo?.imageData (V3), fällt auf
            // das Legacy-Feld photoData zurück bis der Repair-Pass gelaufen ist.
            if let data = person.currentPhotoData, let uiImage = UIImage(data: data) {
                Image(uiImage: uiImage)
                    .resizable()
                    .scaledToFill()
            } else {
                Text(person.initials)
                    .font(.system(size: size * 0.38, weight: .medium, design: theme.displayDesign))
                    .foregroundStyle(theme.accent)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(theme.accent.opacity(0.12))
            }
        }
        .frame(width: size, height: size)
        .clipShape(Circle())
    }
}

// MARK: - Tag Badge

struct TagBadge: View {
    @Environment(\.nahbarTheme) var theme
    let text: String

    var body: some View {
        Text(text)
            .font(.system(size: 11, weight: .medium))
            .foregroundStyle(theme.contentTertiary)
            .padding(.horizontal, 8)
            .padding(.vertical, 3)
            .background(theme.backgroundSecondary)
            .clipShape(Capsule())
    }
}

// MARK: - Pro Badge

struct ProBadge: View {
    @Environment(\.nahbarTheme) var theme
    @StateObject private var store = StoreManager.shared

    var body: some View {
        if !store.isPro {
            Text("PRO")
                .font(.system(size: 10, weight: .bold))
                .foregroundStyle(theme.accent)
                .padding(.horizontal, 7)
                .padding(.vertical, 3)
                .background(theme.accent.opacity(0.10))
                .clipShape(Capsule())
        }
    }
}

// MARK: - Max Badge

struct MaxBadge: View {
    @Environment(\.nahbarTheme) var theme
    @StateObject private var store = StoreManager.shared

    var body: some View {
        if !store.isMax {
            Text("MAX")
                .font(.system(size: 10, weight: .bold))
                .foregroundStyle(theme.accent)
                .padding(.horizontal, 7)
                .padding(.vertical, 3)
                .background(theme.accent.opacity(0.10))
                .clipShape(Capsule())
        }
    }
}

// MARK: - Section Header

struct SectionHeader: View {
    @Environment(\.nahbarTheme) var theme
    let title: LocalizedStringKey
    let icon: String

    var body: some View {
        HStack(spacing: 6) {
            Image(systemName: icon)
                .font(.system(size: theme.sectionHeaderSize, weight: .medium))
                .foregroundStyle(theme.sectionHeaderColor)
            Text(title)
                .textCase(.uppercase)
                .font(.system(size: theme.sectionHeaderSize, weight: .semibold))
                .tracking(0.8)
                .foregroundStyle(theme.sectionHeaderColor)
        }
    }
}

// MARK: - Divider Row

struct RowDivider: View {
    @Environment(\.nahbarTheme) var theme

    var body: some View {
        Rectangle()
            .fill(theme.borderSubtle)
            .frame(height: 0.5)
            .padding(.leading, 16)
            .allowsHitTesting(false)
    }
}

// MARK: - Themed Navigation Bar Modifier

private struct ThemedNavBar: ViewModifier {
    @Environment(\.nahbarTheme) var theme

    func body(content: Content) -> some View {
        content
            .toolbarBackground(theme.backgroundPrimary.opacity(0.92), for: .navigationBar)
            .toolbarBackground(.visible, for: .navigationBar)
            .toolbarColorScheme(theme.id.isDark ? .dark : .light, for: .navigationBar)
    }
}

extension View {
    func themedNavBar() -> some View {
        modifier(ThemedNavBar())
    }
}
