//
//  RelationshipsView.swift
//  lichunWebsocket
//
//  View for browsing all characters with relationship filtering
//

import SwiftUI

struct RelationshipsView: View {
    @State private var selectedPerson: Person?
    @EnvironmentObject var webSocketService: WebSocketService
    @EnvironmentObject var appViewModel: AppViewModel
    @State private var filter: String? = nil

    var filteredPeople: [Person] {
        webSocketService.player.r.filter { person in
            guard let filter = filter else { return true }
            return person.relationships.contains(filter)
        }
    }

    var body: some View {
        // Note: NavigationView is provided by ContentView, don't add another one here
        ZStack {
            // Romantic gradient background
            LinearGradient(
                    colors: [
                        AppColors.background,
                        Color(hex: 0xFFF0F5).opacity(0.5),
                        AppColors.background
                    ],
                    startPoint: .top,
                    endPoint: .bottom
                )
                .ignoresSafeArea()

                VStack(spacing: AppSpacing.md) {
                    // Header with romantic styling
                    HStack(spacing: AppSpacing.xs) {
                        Image(systemName: "person.2.fill")
                            .font(.system(size: 22))
                            .foregroundStyle(
                                LinearGradient(
                                    colors: [
                                        AppColors.secondary,
                                        AppColors.secondaryDark
                                    ],
                                    startPoint: .top,
                                    endPoint: .bottom
                                )
                            )

                        Text("Characters")
                            .font(.appLargeTitle)
                            .foregroundColor(AppColors.primaryText)

                        Spacer()

                        // Character count badge
                        Text("\(filteredPeople.count)")
                            .font(.appBodyBold)
                            .foregroundColor(.white)
                            .padding(.horizontal, AppSpacing.sm)
                            .padding(.vertical, AppSpacing.xs)
                            .background(
                                Capsule()
                                    .fill(
                                        LinearGradient(
                                            colors: [
                                                AppColors.secondary,
                                                AppColors.secondaryDark
                                            ],
                                            startPoint: .leading,
                                            endPoint: .trailing
                                        )
                                    )
                            )
                            .shadow(color: AppColors.secondary.opacity(0.3), radius: 4, x: 0, y: 2)
                    }
                    .padding(.horizontal, AppSpacing.md)
                    .padding(.top, AppSpacing.sm)

                    // Romantic filter picker
                    Picker("Filter", selection: $filter) {
                        Text("All").tag(String?.none)
                        Text("Family").tag(String?("family"))
                        Text("Friends").tag(String?("friend"))
                        Text("Colleagues").tag(String?("coworker"))
                        Text("Classmates").tag(String?("classmate"))
                    }
                    .pickerStyle(SegmentedPickerStyle())
                    .padding(.horizontal, AppSpacing.md)

                    // Character list
                    ScrollView {
                        LazyVStack(spacing: AppSpacing.sm) {
                            ForEach(filteredPeople) { person in
                                Button(action: {
                                    selectedPerson = person
                                }) {
                                    RelationshipCard(person: person)
                                }
                                .buttonStyle(PlainButtonStyle())
                            }
                        }
                        .padding(AppSpacing.md)
                        .padding(.bottom, 100) // Space for tab bar
                    }
                }
            }
        .onAppear {
            appViewModel.shouldNavigateToRelationships = false
        }
        // Use fullScreenCover instead of NavigationLink for more stable navigation
        .fullScreenCover(item: $selectedPerson) { person in
            NavigationView {
                PersonDetailView(personID: person.id)
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbar {
                        ToolbarItem(placement: .navigationBarLeading) {
                            Button("Back") {
                                selectedPerson = nil
                            }
                        }
                    }
            }
            .environmentObject(webSocketService)
            .environmentObject(appViewModel)
        }
    }
}

// MARK: - Supporting Views

private struct RelationshipCard: View {
    let person: Person

    var body: some View {
        HStack(spacing: AppSpacing.md) {
            // Avatar with romantic border
            CharacterAvatar(
                person: person,
                size: 56,
                showBorder: true,
                borderGradient: [
                    relationshipColor(for: person.relationships).opacity(0.8),
                    relationshipColor(for: person.relationships).opacity(0.5)
                ],
                showGlow: false
            )

            // Info section
            VStack(alignment: .leading, spacing: AppSpacing.xs) {
                // Name
                Text(person.firstname + " " + person.lastname)
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)

                // Relationships with romantic tags
                HStack(spacing: AppSpacing.xs) {
                    ForEach(person.relationships.prefix(2), id: \.self) { relationship in
                        HStack(spacing: 2) {
                            Image(systemName: relationshipIcon(for: relationship))
                                .font(.system(size: 10))
                                .foregroundColor(relationshipColor(for: [relationship]))

                            Text(relationship.replacingOccurrences(of: "_", with: " ").capitalized)
                                .font(.appCaption)
                                .foregroundColor(AppColors.secondaryText)
                        }
                        .padding(.horizontal, AppSpacing.xs)
                        .padding(.vertical, 2)
                        .background(relationshipColor(for: [relationship]).opacity(0.15))
                        .cornerRadius(AppSpacing.smallCornerRadius)
                    }
                }
            }

            Spacer()

            // Affinity badge with romantic styling
            VStack(spacing: 2) {
                Image(systemName: "heart.fill")
                    .font(.system(size: 14))
                    .foregroundColor(getAffinityColor(for: person.affinity))

                Text("\(person.affinity)")
                    .font(.appCaptionBold)
                    .foregroundColor(getAffinityColor(for: person.affinity))
            }
            .padding(.horizontal, AppSpacing.sm)
            .padding(.vertical, AppSpacing.xs)
            .background(
                RoundedRectangle(cornerRadius: AppSpacing.smallCornerRadius)
                    .fill(getAffinityColor(for: person.affinity).opacity(0.15))
            )
        }
        .padding(AppSpacing.md)
        .background(
            ZStack {
                // Subtle gradient background
                LinearGradient(
                    colors: [
                        AppColors.cardBackground,
                        relationshipColor(for: person.relationships).opacity(0.05)
                    ],
                    startPoint: .leading,
                    endPoint: .trailing
                )

                // Border
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .stroke(AppColors.secondaryText.opacity(0.1), lineWidth: 1)
            }
        )
        .cornerRadius(AppSpacing.cornerRadius)
        .shadow(color: AppColors.secondaryText.opacity(0.1), radius: 4, x: 0, y: 2)
    }

    // Helper function for relationship colors
    private func relationshipColor(for relationships: [String]) -> Color {
        if relationships.contains("dating") || relationships.contains("dating_match") {
            return AppColors.primary
        } else if relationships.contains("family") {
            return AppColors.family
        } else if relationships.contains("friend") {
            return AppColors.friend
        } else if relationships.contains("coworker") {
            return AppColors.acquaintance
        }
        return AppColors.secondary
    }

    // Helper function for relationship icons
    private func relationshipIcon(for relationship: String) -> String {
        switch relationship.lowercased() {
        case "dating", "dating_match":
            return "heart.fill"
        case "family":
            return "house.fill"
        case "friend":
            return "person.2.fill"
        case "coworker":
            return "briefcase.fill"
        case "classmate":
            return "book.fill"
        default:
            return "person.fill"
        }
    }
}

// MARK: - Preview
// Preview removed - requires backend connection
