//
//  CompatibilityExplanationView.swift
//  lichunWebsocket
//
//  Modal view that explains compatibility score factors
//

import SwiftUI

struct CompatibilityExplanationView: View {
    @ObservedObject var person: Person
    @ObservedObject var currentPerson: Person
    @Environment(\.presentationMode) var presentationMode

    // Calculate shared interests
    var sharedInterests: [String] {
        let personInterestsLower = person.interests.map { $0.lowercased() }
        let currentInterestsLower = currentPerson.interests.map { $0.lowercased() }
        return person.interests.filter { interest in
            currentInterestsLower.contains(interest.lowercased())
        }
    }

    var sharedInterestsCount: Int {
        sharedInterests.count
    }

    var ageDifference: Int {
        abs(person.ageYears - currentPerson.ageYears)
    }

    var ageDifferenceText: String {
        if ageDifference == 0 {
            return "Same age"
        } else if ageDifference == 1 {
            return "1 year age difference"
        } else {
            return "\(ageDifference) years age difference"
        }
    }

    var statsSimilarity: Int {
        // Calculate average similarity across stats (0-100)
        let healthDiff = abs(Int(person.health) - Int(currentPerson.health))
        let happinessDiff = abs(person.happiness - currentPerson.happiness)
        let intelligenceDiff = abs(person.intelligence - currentPerson.intelligence)
        let prestigeDiff = abs(person.prestige - currentPerson.prestige)

        let avgDiff = (healthDiff + happinessDiff + intelligenceDiff + prestigeDiff) / 4
        return max(0, 100 - avgDiff)
    }

    var body: some View {
        ZStack {
            // Background gradient
            LinearGradient(
                colors: [
                    AppColors.primary.opacity(0.05),
                    AppColors.accent.opacity(0.03),
                    Color.clear
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()

            VStack(spacing: AppSpacing.lg) {
                // Header
                HStack {
                    Spacer()
                    Button(action: {
                        hapticFeedback(style: .light)
                        presentationMode.wrappedValue.dismiss()
                    }) {
                        ZStack {
                            Circle()
                                .fill(AppColors.secondaryText.opacity(0.1))
                                .frame(width: 32, height: 32)

                            Image(systemName: "xmark")
                                .font(.system(size: 14, weight: .semibold))
                                .foregroundColor(AppColors.secondaryText)
                        }
                    }
                }

                VStack(spacing: AppSpacing.sm) {
                    ZStack {
                        Circle()
                            .fill(
                                LinearGradient(
                                    colors: [
                                        AppColors.primary.opacity(0.2),
                                        AppColors.accent.opacity(0.15)
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                            .frame(width: 80, height: 80)

                        Image(systemName: "heart.circle.fill")
                            .font(.system(size: 48))
                            .foregroundColor(AppColors.primary)
                    }

                    Text("Why \(person.compatibilityScore)%?")
                        .font(.appTitle)
                        .foregroundColor(AppColors.primaryText)

                    Text("Compatibility is based on multiple factors")
                        .font(.appBody)
                        .foregroundColor(AppColors.secondaryText)
                        .multilineTextAlignment(.center)
                }

            Divider()
                .background(AppColors.secondaryText.opacity(0.2))

            // Factors
            VStack(alignment: .leading, spacing: AppSpacing.md) {
                if sharedInterestsCount > 0 {
                    ExplanationRow(
                        icon: "star.fill",
                        text: "\(sharedInterestsCount) shared interest\(sharedInterestsCount == 1 ? "" : "s")",
                        detail: sharedInterests.prefix(3).joined(separator: ", "),
                        positive: true,
                        impact: sharedInterestsCount * 10
                    )
                }

                ExplanationRow(
                    icon: "calendar",
                    text: ageDifferenceText,
                    detail: ageDifference <= 5 ? "Close in age" : "Larger age gap",
                    positive: ageDifference <= 5,
                    impact: ageDifference <= 5 ? 15 : -10
                )

                ExplanationRow(
                    icon: "chart.bar.fill",
                    text: "Similar life stats",
                    detail: "\(statsSimilarity)% similarity across stats",
                    positive: statsSimilarity >= 70,
                    impact: statsSimilarity >= 70 ? 20 : 0
                )

                if !person.occupation.isEmpty && !currentPerson.occupation.isEmpty {
                    let sameField = person.occupation.lowercased().contains(currentPerson.occupation.lowercased()) ||
                                  currentPerson.occupation.lowercased().contains(person.occupation.lowercased())
                    ExplanationRow(
                        icon: "briefcase.fill",
                        text: sameField ? "Similar career paths" : "Different career paths",
                        detail: "\(person.occupation) / \(currentPerson.occupation)",
                        positive: sameField,
                        impact: sameField ? 10 : 0
                    )
                }

                ExplanationRow(
                    icon: "sparkles",
                    text: "Mystery factor",
                    detail: "Some things just click!",
                    positive: person.compatibilityScore >= 70,
                    impact: Int.random(in: 5...15)
                )
            }

            Spacer()

            // Close button
            PrimaryButton(title: "Got it!") {
                presentationMode.wrappedValue.dismiss()
            }
            }
            .padding(AppSpacing.xl)
        }
        .background(AppColors.primaryBackground)
        .cornerRadius(AppSpacing.cornerRadius)
    }
}

// MARK: - Explanation Row Component
struct ExplanationRow: View {
    let icon: String
    let text: String
    let detail: String
    let positive: Bool
    let impact: Int

    var impactColor: Color {
        if impact > 0 {
            return AppColors.success
        } else if impact < 0 {
            return AppColors.error
        } else {
            return AppColors.secondaryText
        }
    }

    var body: some View {
        HStack(alignment: .top, spacing: AppSpacing.md) {
            ZStack {
                Circle()
                    .fill((positive ? AppColors.success : AppColors.warning).opacity(0.15))
                    .frame(width: 32, height: 32)

                Image(systemName: icon)
                    .font(.system(size: 16))
                    .foregroundColor(positive ? AppColors.success : AppColors.warning)
            }

            VStack(alignment: .leading, spacing: AppSpacing.xs) {
                Text(text)
                    .font(.appBodyBold)
                    .foregroundColor(AppColors.primaryText)

                Text(detail)
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)
            }

            Spacer()

            if impact != 0 {
                Text("\(impact > 0 ? "+" : "")\(impact)")
                    .font(.appCaptionBold)
                    .foregroundColor(impactColor)
                    .padding(.horizontal, AppSpacing.sm)
                    .padding(.vertical, 4)
                    .background(impactColor.opacity(0.15))
                    .cornerRadius(8)
            }
        }
        .padding(AppSpacing.sm)
        .background(
            ZStack {
                AppColors.cardBackground

                LinearGradient(
                    colors: [
                        (positive ? AppColors.success : AppColors.warning).opacity(0.05),
                        Color.clear
                    ],
                    startPoint: .leading,
                    endPoint: .trailing
                )
            }
        )
        .cornerRadius(AppSpacing.smallCornerRadius)
        .overlay(
            RoundedRectangle(cornerRadius: AppSpacing.smallCornerRadius)
                .stroke((positive ? AppColors.success : AppColors.warning).opacity(0.2), lineWidth: 1)
        )
        .shadow(color: (positive ? AppColors.success : AppColors.warning).opacity(0.08), radius: 6, x: 0, y: 3)
    }
}

// MARK: - Preview
#if DEBUG
struct CompatibilityExplanationView_Previews: PreviewProvider {
    static var previews: some View {
        let person1 = Person()
        person1.id = "1"
        person1.firstname = "Emma"
        person1.lastname = "Johnson"
        person1.ageYears = 28
        person1.sex = "Female"
        person1.occupation = "Software Engineer"
        person1.health = 85
        person1.happiness = 92
        person1.intelligence = 88
        person1.prestige = 65
        person1.compatibilityScore = 87
        person1.interests = ["music", "hiking", "photography", "cooking", "travel"]

        let person2 = Person()
        person2.id = "2"
        person2.firstname = "Alex"
        person2.lastname = "Smith"
        person2.ageYears = 26
        person2.sex = "Male"
        person2.occupation = "Data Scientist"
        person2.health = 80
        person2.happiness = 85
        person2.intelligence = 90
        person2.prestige = 70
        person2.interests = ["music", "travel", "cooking", "gaming", "reading"]

        return CompatibilityExplanationView(
            person: person1,
            currentPerson: person2
        )
        .padding()
        .background(Color.black.opacity(0.5))
    }
}
#endif
