import SwiftUI
import SwiftData

struct PeopleListView: View {
    @Environment(\.nahbarTheme) var theme
    @Environment(\.modelContext) var modelContext
    @Environment(TourCoordinator.self) private var tourCoordinator
    @Query(sort: \Person.name) private var people: [Person]
    @StateObject private var store = StoreManager.shared

    @State private var searchText = ""
    @State private var selectedTag: PersonTag? = nil
    @State private var showingAddPerson = false
    @State private var showingPaywall = false
    @State private var selectedPerson: Person? = nil

    private let freeContactLimit = 3

    private var filteredPeople: [Person] {
        var result = people
        if let tag = selectedTag {
            result = result.filter { $0.tag == tag }
        }
        if !searchText.isEmpty {
            result = result.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
        }
        return result
    }

    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                // Custom header
                VStack(alignment: .leading, spacing: 14) {
                    HStack(alignment: .firstTextBaseline) {
                        VStack(alignment: .leading, spacing: 2) {
                            Text("Menschen")
                                .font(.system(size: 32, weight: .light, design: theme.displayDesign))
                                .foregroundStyle(theme.contentPrimary)
                            // Kontaktlimit-Hinweis für Free-Nutzer
                            if !store.isPro {
                                Button { showingPaywall = true } label: {
                                    Text("\(min(people.count, freeContactLimit)) von \(freeContactLimit) Kontakten – Pro für mehr")
                                        .font(.system(size: 11))
                                        .foregroundStyle(people.count >= freeContactLimit ? theme.accent : theme.contentTertiary)
                                }
                            }
                        }
                        Spacer()
                        Button {
                            if !store.isPro && people.count >= freeContactLimit {
                                showingPaywall = true
                            } else {
                                showingAddPerson = true
                            }
                        } label: {
                            Image(systemName: "plus")
                                .font(.system(size: 17, weight: .medium))
                                .foregroundStyle(theme.accent)
                                .frame(width: 36, height: 36)
                                .background(theme.accent.opacity(0.10))
                                .clipShape(Circle())
                        }
                        .accessibilityLabel("Person hinzufügen")
                        .tourTarget(.addContactButton)
                    }

                    // Search bar
                    HStack(spacing: 8) {
                        Image(systemName: "magnifyingglass")
                            .font(.system(size: 14))
                            .foregroundStyle(theme.contentTertiary)
                        TextField("Suchen…", text: $searchText)
                            .font(.system(size: 15))
                            .foregroundStyle(theme.contentPrimary)
                            .tint(theme.accent)
                        if !searchText.isEmpty {
                            Button { searchText = "" } label: {
                                Image(systemName: "xmark.circle.fill")
                                    .font(.system(size: 14))
                                    .foregroundStyle(theme.contentTertiary)
                            }
                        }
                    }
                    .padding(.horizontal, 12)
                    .padding(.vertical, 9)
                    .background(theme.backgroundSecondary)
                    .clipShape(RoundedRectangle(cornerRadius: 10))

                    // Tag filter chips
                    ScrollView(.horizontal, showsIndicators: false) {
                        HStack(spacing: 8) {
                            FilterChip(label: "Alle", isSelected: selectedTag == nil) {
                                selectedTag = nil
                            }
                            ForEach(PersonTag.allCases, id: \.self) { tag in
                                FilterChip(label: tag.rawValue, isSelected: selectedTag == tag) {
                                    selectedTag = (selectedTag == tag) ? nil : tag
                                }
                            }
                        }
                    }
                    .tourTarget(.filterChips)
                }
                .padding(.horizontal, 20)
                .padding(.top, 12)
                .padding(.bottom, 14)
                .background(theme.backgroundPrimary)

                // Content
                if filteredPeople.isEmpty {
                    Spacer()
                    emptyState
                    Spacer()
                } else {
                    ScrollView {
                        VStack(spacing: 0) {
                            ForEach(Array(filteredPeople.enumerated()), id: \.element.id) { index, person in
                                Button {
                                    selectedPerson = person
                                } label: {
                                    PersonRowView(person: person)
                                        .contentShape(Rectangle())
                                }
                                .buttonStyle(.plain)
                                .tourTarget(index == 0 ? TourTargetID.contactCardFirst : nil)
                                if index < filteredPeople.count - 1 {
                                    RowDivider()
                                }
                            }
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        .padding(.horizontal, 20)
                        .padding(.top, 4)
                        .padding(.bottom, 40)
                    }
                    .background(theme.backgroundPrimary)
                }
            }
            .background(theme.backgroundPrimary.ignoresSafeArea())
            .navigationBarHidden(true)
            .navigationDestination(item: $selectedPerson) { person in
                PersonDetailView(person: person)
            }
        }
        .sheet(isPresented: $showingAddPerson) {
            AddPersonView()
        }
        .sheet(isPresented: $showingPaywall) {
            PaywallView(targeting: .pro)
        }
        // Automatisch zum ersten Kontakt navigieren, wenn die Tour
        // den +Moment- oder +Todo-Button spotlighten möchte.
        .onChange(of: tourCoordinator.currentStep?.target) { _, target in
            guard target == .addMomentButton || target == .addTodoButton else { return }
            if selectedPerson == nil, let first = filteredPeople.first {
                selectedPerson = first
            }
        }
    }

    private var emptyState: some View {
        VStack(spacing: 10) {
            Text(searchText.isEmpty ? "Noch keine Menschen hier." : "Keine Treffer.")
                .font(.system(size: 18, weight: .light, design: theme.displayDesign))
                .foregroundStyle(theme.contentPrimary)
            if searchText.isEmpty {
                Text("Tippe auf + um jemanden hinzuzufügen.")
                    .font(.system(size: 14))
                    .foregroundStyle(theme.contentTertiary)
            }
        }
    }
}

// MARK: - Filter Chip

struct FilterChip: View {
    @Environment(\.nahbarTheme) var theme
    let label: String
    let isSelected: Bool
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            Text(label)
                .font(.system(size: 13, weight: isSelected ? .medium : .regular))
                .foregroundStyle(isSelected ? theme.accent : theme.contentSecondary)
                .padding(.horizontal, 12)
                .padding(.vertical, 6)
                .background(isSelected ? theme.accent.opacity(0.12) : theme.backgroundSecondary)
                .clipShape(Capsule())
        }
    }
}

// MARK: - Hilfsfunktion: letzter Eintrag formatieren

/// Gibt "Zuletzt <relativer Zeitausdruck>" auf Deutsch zurück.
/// `now` ist injizierbar für Tests.
func formatLastMoment(_ date: Date, relativeTo now: Date = Date()) -> String {
    let fmt = RelativeDateTimeFormatter()
    fmt.locale = Locale(identifier: "de_DE")
    fmt.unitsStyle = .full
    fmt.dateTimeStyle = .named      // "gestern", "vorgestern" statt "vor 1 Tag"
    return "Zuletzt \(fmt.localizedString(for: date, relativeTo: now))"
}

// MARK: - Person Row

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

    var body: some View {
        HStack(spacing: 12) {
            PersonAvatar(person: person, size: 44)

            VStack(alignment: .leading, spacing: 3) {
                Text(person.name)
                    .font(.system(size: 16, weight: .medium, design: theme.displayDesign))
                    .foregroundStyle(theme.contentPrimary)

                HStack(spacing: 5) {
                    Text(person.tag.rawValue)
                        .font(.system(size: 12))
                        .foregroundStyle(theme.contentTertiary)

                    if let last = person.lastMomentDate {
                        Text("·")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                        Text(formatLastMoment(last))
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                    }
                }
            }

            Spacer()

            if person.needsAttention {
                Circle()
                    .fill(theme.accent.opacity(0.55))
                    .frame(width: 7, height: 7)
            }

            Image(systemName: "chevron.right")
                .font(.system(size: 11, weight: .medium))
                .foregroundStyle(theme.contentTertiary)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}
