//
//  MessagesHeaderCard.swift
//  lichunWebsocket
//
//  Header card for messages view with search and filter
//

import SwiftUI

struct MessagesHeaderCard: View {
    @Binding var searchText: String
    @Binding var selectedFilter: MessageFilter

    @State private var isSearchFocused = false

    var totalMessageCount: Int

    // MARK: - Body

    var body: some View {
        BaseCard(
            backgroundColor: AppColors.surfaceElevated,
            borderColor: AppColors.primary.opacity(0.2),
            showShadow: true
        ) {
            VStack(spacing: AppSpacing.md) {
                // Title and count
                HStack {
                    VStack(alignment: .leading, spacing: 4) {
                        Text("Messages")
                            .font(.appTitle2)
                            .foregroundColor(AppColors.primaryText)

                        Text("\(totalMessageCount) conversation\(totalMessageCount == 1 ? "" : "s")")
                            .font(.appCaption)
                            .foregroundColor(AppColors.secondaryText)
                    }

                    Spacer()

                    // Message icon with pulse
                    Image(systemName: "message.fill")
                        .font(.system(size: 28))
                        .foregroundColor(AppColors.primary)
                }

                // Cozy search bar
                HStack(spacing: 8) {
                    Image(systemName: "magnifyingglass")
                        .font(.system(size: 14))
                        .foregroundColor(isSearchFocused ? AppColors.primary : AppColors.secondaryText)

                    TextField("Search conversations...", text: $searchText)
                        .font(.appBody)
                        .foregroundColor(AppColors.primaryText)
                        .accessibilityLabel("Search conversations")
                        .onTapGesture {
                            withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
                                isSearchFocused = true
                            }
                        }

                    if !searchText.isEmpty {
                        Button(action: {
                            searchText = ""
                            hideKeyboard()
                        }) {
                            Image(systemName: "xmark.circle.fill")
                                .font(.system(size: 16))
                                .foregroundColor(AppColors.secondaryText)
                        }
                        .accessibilityLabel("Clear search")
                    }
                }
                .padding(.horizontal, 12)
                .padding(.vertical, 10)
                .background(
                    AppColors.surfaceSubtle // Adaptive search background
                )
                .cornerRadius(16) // More rounded
                .overlay(
                    RoundedRectangle(cornerRadius: 16)
                        .strokeBorder(
                            isSearchFocused ? AppColors.primary.opacity(0.25) : AppColors.secondaryText.opacity(0.12),
                            lineWidth: 1.5
                        )
                )
                .shadow(
                    color: isSearchFocused ? AppColors.primary.opacity(0.08) : Color.black.opacity(0.02),
                    radius: isSearchFocused ? 6 : 3,
                    x: 0,
                    y: 2
                )

                // Filter chips
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: AppSpacing.sm) {
                        ForEach(MessageFilter.allCases, id: \.self) { filter in
                            MessageFilterChip(
                                title: filter.rawValue,
                                icon: filter.icon,
                                isSelected: selectedFilter == filter,
                                action: {
                                    withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
                                        selectedFilter = filter
                                    }

                                    // Haptic feedback
                                    let generator = UIImpactFeedbackGenerator(style: .light)
                                    generator.impactOccurred()
                                }
                            )
                        }
                    }
                }
            }
        }
    }

    private func hideKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

// MARK: - Filter Chip Component

private struct MessageFilterChip: View {
    let title: String
    let icon: String
    let isSelected: Bool
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            HStack(spacing: 6) {
                Image(systemName: icon)
                    .font(.system(size: 12))

                Text(title)
                    .font(.appCaptionBold)
            }
            .foregroundColor(isSelected ? .white : AppColors.primaryText)
            .padding(.horizontal, 12)
            .padding(.vertical, 8)
            .background(
                isSelected
                    ? LinearGradient(
                        colors: [AppColors.primary, AppColors.accent],
                        startPoint: .leading,
                        endPoint: .trailing
                    )
                    : LinearGradient(
                        colors: [AppColors.background],
                        startPoint: .leading,
                        endPoint: .trailing
                    )
            )
            .cornerRadius(12)
            .overlay(
                RoundedRectangle(cornerRadius: 12)
                    .strokeBorder(
                        isSelected ? Color.clear : AppColors.primary.opacity(0.2),
                        lineWidth: 1
                    )
            )
        }
        .scaleEffect(isSelected ? 1.0 : 0.95)
        .animation(.spring(response: 0.3, dampingFraction: 0.7), value: isSelected)
        .accessibilityLabel(title)
        .accessibilityAddTraits(isSelected ? .isSelected : [])
    }
}

// MARK: - Message Filter Enum

enum MessageFilter: String, CaseIterable {
    case all = "All"
    case friends = "Friends"
    case family = "Family"
    case romantic = "Romantic"

    var icon: String {
        switch self {
        case .all:
            return "tray.fill"
        case .friends:
            return "person.2.fill"
        case .family:
            return "house.fill"
        case .romantic:
            return "heart.fill"
        }
    }
}

// MARK: - Preview
#Preview {
    VStack {
        MessagesHeaderCard(
            searchText: .constant(""),
            selectedFilter: .constant(.all),
            totalMessageCount: 5
        )

        Spacer()
    }
    .padding()
    .background(AppColors.background)
}
