//
//  MatchExplanationToast.swift
//  lichunWebsocket
//
//  Brief toast notification explaining why a match occurred
//

import SwiftUI

// MARK: - Data Model

struct MatchExplanation: Identifiable {
    let id = UUID()
    let matchedPersonName: String
    let compatibilityScore: Int
    let reasons: [String]

    init(matchedPersonName: String, compatibilityScore: Int, reasons: [String]) {
        self.matchedPersonName = matchedPersonName
        self.compatibilityScore = compatibilityScore
        self.reasons = reasons
    }

    /// Generate a match explanation from a Person object
    static func generate(for person: Person, currentPersonInterests: [String]) -> MatchExplanation {
        var reasons: [String] = []

        // Compatibility score reason
        if person.compatibilityScore > 0 {
            reasons.append("\(person.compatibilityScore)% compatible")
        }

        // Shared interests
        let sharedInterests = person.interests.filter { interest in
            currentPersonInterests.contains { $0.lowercased() == interest.lowercased() }
        }
        if !sharedInterests.isEmpty {
            reasons.append("\(sharedInterests.count) shared interest\(sharedInterests.count == 1 ? "" : "s")")
        }

        // Similar age
        // Note: In a real implementation, you'd compare with current person's age
        if person.ageYears >= 20 && person.ageYears <= 35 {
            reasons.append("Similar age and life stage")
        }

        // Similar stats (intelligence, happiness, etc.)
        if person.intelligence > 70 {
            reasons.append("Highly intelligent")
        }

        if person.happiness > 80 {
            reasons.append("Very happy person")
        }

        // Occupation
        if !person.occupation.isEmpty {
            reasons.append("Stable career")
        }

        // Fallback if no reasons
        if reasons.isEmpty {
            reasons.append("Good match potential")
        }

        // Limit to top 3 reasons
        let topReasons = Array(reasons.prefix(3))

        return MatchExplanation(
            matchedPersonName: person.firstname,
            compatibilityScore: person.compatibilityScore,
            reasons: topReasons
        )
    }
}

// MARK: - Match Explanation Toast View

struct MatchExplanationToast: View {
    let explanation: MatchExplanation
    let onDismiss: () -> Void

    @State private var isVisible: Bool = false

    var body: some View {
        VStack {
            toastContent
                .offset(y: isVisible ? 0 : -150)
                .opacity(isVisible ? 1 : 0)

            Spacer()
        }
        .onAppear {
            withAnimation(.spring(response: 0.5, dampingFraction: 0.7)) {
                isVisible = true
            }

            // Auto-dismiss after 4 seconds
            DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
                dismissToast()
            }
        }
    }

    // MARK: - Toast Content

    private var toastContent: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            // Header
            HStack(spacing: AppSpacing.sm) {
                // Icon with gradient background
                ZStack {
                    Circle()
                        .fill(
                            RadialGradient(
                                colors: [
                                    AppColors.primary.opacity(0.3),
                                    AppColors.primary.opacity(0.1),
                                    AppColors.primary.opacity(0)
                                ],
                                center: .center,
                                startRadius: 10,
                                endRadius: 20
                            )
                        )
                        .frame(width: 40, height: 40)

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

                Text("Great Match!")
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)

                Spacer()

                Button(action: {
                    dismissToast()
                }) {
                    Image(systemName: "xmark.circle.fill")
                        .foregroundColor(AppColors.secondaryText.opacity(0.6))
                        .font(.system(size: 20))
                }
            }

            // Reasons with improved styling
            VStack(alignment: .leading, spacing: AppSpacing.xs) {
                ForEach(explanation.reasons, id: \.self) { reason in
                    HStack(spacing: AppSpacing.xs) {
                        Circle()
                            .fill(
                                LinearGradient(
                                    colors: [AppColors.primary, AppColors.primary.opacity(0.7)],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                            .frame(width: 6, height: 6)

                        Text(reason)
                            .font(.appBody)
                            .foregroundColor(AppColors.primaryText)
                    }
                }
            }
            .padding(.top, 2)
        }
        .padding(AppSpacing.md)
        .background(
            RoundedRectangle(cornerRadius: AppSpacing.largeCornerRadius)
                .fill(
                    LinearGradient(
                        colors: [
                            AppColors.surfaceElevated,
                            AppColors.background
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .overlay(
                    RoundedRectangle(cornerRadius: AppSpacing.largeCornerRadius)
                        .stroke(
                            LinearGradient(
                                colors: [AppColors.primary.opacity(0.3), AppColors.secondary.opacity(0.2)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 1.5
                        )
                )
        )
        .shadow(
            color: AppColors.primary.opacity(0.15),
            radius: 12,
            x: 0,
            y: 6
        )
        .shadow(
            color: Color.black.opacity(0.1),
            radius: 6,
            x: 0,
            y: 3
        )
        .padding(.horizontal, AppSpacing.md)
        .padding(.top, AppSpacing.md)
        .onTapGesture {
            dismissToast()
        }
    }

    // MARK: - Helper Methods

    private func dismissToast() {
        withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
            isVisible = false
        }

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            onDismiss()
        }
    }
}

// MARK: - Compact Version (Alternative Style)

struct MatchExplanationToastCompact: View {
    let explanation: MatchExplanation
    let onDismiss: () -> Void

    @State private var isVisible: Bool = false

    var body: some View {
        VStack {
            toastContent
                .offset(y: isVisible ? 0 : -100)
                .opacity(isVisible ? 1 : 0)

            Spacer()
        }
        .onAppear {
            withAnimation(.spring(response: 0.5, dampingFraction: 0.7)) {
                isVisible = true
            }

            DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
                dismissToast()
            }
        }
    }

    private var toastContent: some View {
        HStack(spacing: AppSpacing.sm) {
            // Icon with subtle gradient glow
            ZStack {
                Circle()
                    .fill(
                        RadialGradient(
                            colors: [
                                AppColors.primary.opacity(0.3),
                                AppColors.primary.opacity(0.1),
                                AppColors.primary.opacity(0)
                            ],
                            center: .center,
                            startRadius: 15,
                            endRadius: 30
                        )
                    )
                    .frame(width: 56, height: 56)

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

            VStack(alignment: .leading, spacing: 4) {
                Text("Great Match!")
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)

                Text(explanation.reasons.joined(separator: " • "))
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)
                    .lineLimit(2)
            }

            Spacer()

            Button(action: {
                dismissToast()
            }) {
                Image(systemName: "xmark.circle.fill")
                    .foregroundColor(AppColors.secondaryText.opacity(0.6))
                    .font(.system(size: 20))
            }
        }
        .padding(AppSpacing.md)
        .background(
            RoundedRectangle(cornerRadius: AppSpacing.largeCornerRadius)
                .fill(
                    LinearGradient(
                        colors: [
                            AppColors.surfaceElevated,
                            AppColors.background
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .overlay(
                    RoundedRectangle(cornerRadius: AppSpacing.largeCornerRadius)
                        .stroke(
                            LinearGradient(
                                colors: [AppColors.primary.opacity(0.3), AppColors.secondary.opacity(0.2)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 1.5
                        )
                )
        )
        .shadow(
            color: AppColors.primary.opacity(0.15),
            radius: 12,
            x: 0,
            y: 6
        )
        .shadow(
            color: Color.black.opacity(0.1),
            radius: 6,
            x: 0,
            y: 3
        )
        .padding(.horizontal, AppSpacing.md)
        .padding(.top, AppSpacing.md)
        .onTapGesture {
            dismissToast()
        }
    }

    private func dismissToast() {
        withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
            isVisible = false
        }

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            onDismiss()
        }
    }
}

// MARK: - Preview

#if DEBUG
struct MatchExplanationToast_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            // Standard version
            ZStack {
                AppColors.primaryBackground
                    .ignoresSafeArea()

                MatchExplanationToast(
                    explanation: MatchExplanation(
                        matchedPersonName: "Sarah",
                        compatibilityScore: 87,
                        reasons: [
                            "87% compatible",
                            "3 shared interests",
                            "Similar life goals"
                        ]
                    ),
                    onDismiss: {}
                )
            }
            .previewDisplayName("Standard Toast")

            // Compact version
            ZStack {
                AppColors.primaryBackground
                    .ignoresSafeArea()

                MatchExplanationToastCompact(
                    explanation: MatchExplanation(
                        matchedPersonName: "Emma",
                        compatibilityScore: 92,
                        reasons: [
                            "92% compatible",
                            "5 shared interests",
                            "Highly intelligent"
                        ]
                    ),
                    onDismiss: {}
                )
            }
            .previewDisplayName("Compact Toast")

            // Long text example
            ZStack {
                AppColors.primaryBackground
                    .ignoresSafeArea()

                MatchExplanationToast(
                    explanation: MatchExplanation(
                        matchedPersonName: "Alex",
                        compatibilityScore: 78,
                        reasons: [
                            "78% compatible",
                            "Similar age and life stage",
                            "Stable career"
                        ]
                    ),
                    onDismiss: {}
                )
            }
            .previewDisplayName("Long Text")
        }
    }
}
#endif
