import SwiftUI
import SwiftData

struct PeopleListView: View {
    @Environment(\.nahbarTheme) var theme
    @Environment(\.modelContext) var modelContext
    @Query(sort: \Person.name) private var people: [Person]

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

    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) {
                        Text("Menschen")
                            .font(.system(size: 34, weight: .light, design: theme.displayDesign))
                            .foregroundStyle(theme.contentPrimary)
                        Spacer()
                        Button {
                            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")
                    }

                    // 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
                                }
                            }
                        }
                    }
                }
                .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
                                NavigationLink(destination: PersonDetailView(person: person)) {
                                    PersonRowView(person: person)
                                }
                                .buttonStyle(.plain)
                                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)
        }
        .sheet(isPresented: $showingAddPerson) {
            AddPersonView()
        }
    }

    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: - 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(last, style: .relative)
                            .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)
    }
}
