//
//  DatingView.swift
//  lichunWebsocket
//
//  Created by Craig Vander Galien on 8/14/23.
//

import SwiftUI
import SDWebImageSwiftUI

/// Wrapper to reliably trigger fullScreenCover with embedded character ID
struct ChatPresentationItem: Identifiable {
    let id: String  // character ID
}

struct DatingView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @State private var isSwipeDatingViewPresented = false
    @State private var chatPresentation: ChatPresentationItem?  // Use Identifiable wrapper for reliable presentation
    @State private var showPopover = false
    // INTEGRATION: Date mini-game
    @State private var showDateMiniGame = false
    // INTEGRATION: Relationship details
    @State private var showRelationshipDetail = false
    // INTEGRATION: Confirmation dialogs
    @State private var showBreakUpConfirmation = false
    /// Relationship statuses that represent an active romance the player can view/manage.
    /// Mirrors the backend's ACTIVE_RELATIONSHIP_STATUSES (relationship_manager.ts).
    private static let activeRelationshipStatuses: Set<String> = ["Prospect", "Dating", "Engaged", "Married"]

    var relationship: Relationship? {
        // Derive the current romance directly from relData rather than relying on the
        // character's scalar `relationship` ID. The backend does not serialize that ID
        // on the character object, so matching by it always failed and the screen fell
        // back to the empty state. relData itself is fully populated and decodes cleanly,
        // so find the active relationship by status (matching RelationshipDetailView's
        // resolution approach).
        let relationshipId = webSocketService.person.relationship
        if !relationshipId.isEmpty,
           let byId = webSocketService.player.relData.first(where: { $0.id == relationshipId }) {
            return byId
        }
        return webSocketService.player.relData.first(where: {
            Self.activeRelationshipStatuses.contains($0.relationshipStatus)
        })
    }

    var partner: Person? {
        guard let relationship = relationship else {
            return nil
        }
        // The player may be stored as either person1 or person2; the partner is the other side.
        let partnerId = relationship.person1 == webSocketService.person.id
            ? relationship.person2
            : relationship.person1
        return webSocketService.player.r.first(where: { $0.id == partnerId })
    }


    
    var body: some View {
        VStack {
            if let relationshipStatus = relationship?.relationshipStatus, !relationshipStatus.isEmpty, let partner = partner {
                // NEW ROMANTIC LAYOUT
                ScrollView {
                    VStack(spacing: AppSpacing.lg) {
                        // 1. Hero Card - Partner Spotlight
                        RomanticHeroCard(
                            partner: partner,
                            relationship: relationship!
                        )

                        // 2. Quick Actions
                        QuickActionsBar(
                            partner: partner,
                            onDateTap: { showPopover = true },
                            onGiftTap: {
                                webSocketService.sendMessage(message: WebSocketCommands.partnerGift(partnerId: partner.id))
                            },
                            onChatTap: {
                                chatPresentation = ChatPresentationItem(id: partner.id)
                            }
                        )

                        // 3. Snapshot Stats
                        RelationshipSnapshotCard(
                            relationship: relationship!,
                            sharedInterestsCount: relationship!.commonInterests.count
                        )

                        // 4. Recent Moments
                        if !relationship!.eventsLog.isEmpty {
                            RecentMomentsCard(
                                events: relationship!.eventsLog,
                                onViewAllTap: { showRelationshipDetail = true }
                            )
                        }

                        // 5. View Full Details Button
                        SecondaryButton(title: "View Relationship Details") {
                            showRelationshipDetail = true
                        }

                        // 6. Destructive Action (bottom, separated)
                        Button(action: {
                            hapticFeedback(style: .heavy)
                            showBreakUpConfirmation = true
                        }) {
                            Text(relationship!.relationshipStatus == "Married" ? "Divorce" : "Break Up")
                                .font(.appBody)
                                .foregroundColor(.white)
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, AppSpacing.sm)
                                .background(AppColors.error)
                                .cornerRadius(AppSpacing.cornerRadius)
                        }
                        .padding(.top, AppSpacing.xl)
                        .padding(.bottom, 100) // Space for tab bar
                    }
                    .padding(AppSpacing.md)
                    .padding(.top, AppSpacing.sm) // Additional top spacing for header visibility
                }
                .background(AppColors.primaryBackground)
                // INTEGRATION: Using new DateActivitySelectionView
                .sheet(isPresented: $showPopover) {
                    DateActivitySelectionView(
                        partner: partner,
                        onActivitySelected: { activity in
                            webSocketService.sendMessage(message: WebSocketCommands.dateNight(activityName: activity.name))
                            showPopover = false
                        }
                    )
                    .environmentObject(webSocketService)
                }
                .fullScreenCover(item: $chatPresentation) { presentation in
                    ChatView(characterID: presentation.id)
                        .environmentObject(webSocketService)
                }
                // INTEGRATION: Date mini-game sheet
                .sheet(isPresented: $showDateMiniGame) {
                    DateMiniGameView(
                        gameState: DateMiniGameState(
                            id: UUID().uuidString,
                            partnerId: partner.id,
                            partnerName: "\(partner.firstname) \(partner.lastname)",
                            activityId: "date_activity",
                            questions: []
                        ),
                        partner: partner
                    )
                    .environmentObject(webSocketService)
                }
                // INTEGRATION: Relationship detail sheet
                .sheet(isPresented: $showRelationshipDetail) {
                    if let relationship = relationship {
                        RelationshipDetailView(relationshipId: relationship.id)
                            .environmentObject(webSocketService)
                    }
                }
                // INTEGRATION: Confirmation dialog with romantic styling
                .sheet(isPresented: $showBreakUpConfirmation) {
                    if let relationship = relationship {
                        let isMarried = relationship.relationshipStatus == "Married"
                        ZStack {
                            // Soft background
                            AppColors.primaryBackground.ignoresSafeArea()

                            VStack(spacing: AppSpacing.lg) {
                                Spacer()

                                BaseCard {
                                    VStack(spacing: AppSpacing.lg) {
                                        // Sad icon with subtle styling
                                        ZStack {
                                            Circle()
                                                .fill(AppColors.error.opacity(0.15))
                                                .frame(width: 100, height: 100)

                                            Image(systemName: "heart.slash.fill")
                                                .font(.system(size: 56))
                                                .foregroundStyle(
                                                    LinearGradient(
                                                        colors: [
                                                            AppColors.error,
                                                            AppColors.error.opacity(0.7)
                                                        ],
                                                        startPoint: .top,
                                                        endPoint: .bottom
                                                    )
                                                )
                                                .shadow(color: AppColors.error.opacity(0.3), radius: 8, x: 0, y: 4)
                                        }

                                        Text(isMarried ? "End Marriage?" : "End Relationship?")
                                            .font(.appLargeTitle)
                                            .foregroundColor(AppColors.primaryText)

                                        Text(isMarried ? "Are you sure you want to end this marriage? This decision is permanent." : "Are you sure you want to end this relationship? This decision is permanent.")
                                            .font(.appBody)
                                            .foregroundColor(AppColors.secondaryText)
                                            .multilineTextAlignment(.center)
                                            .padding(.horizontal, AppSpacing.md)

                                        // Action buttons
                                        VStack(spacing: AppSpacing.sm) {
                                            Button(action: {
                                                showBreakUpConfirmation = false
                                            }) {
                                                Text("Cancel")
                                                    .font(.appHeadline)
                                                    .foregroundColor(AppColors.primaryText)
                                                    .frame(maxWidth: .infinity)
                                                    .padding(.vertical, AppSpacing.md)
                                                    .background(AppColors.surfaceElevated)
                                                    .cornerRadius(AppSpacing.cornerRadius)
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                                                            .stroke(AppColors.secondaryText.opacity(0.3), lineWidth: 1)
                                                    )
                                            }

                                            Button(action: {
                                                let messageType = isMarried ? "divorce" : "breakUp"
                                                let message = isMarried
                                                    ? WebSocketCommands.divorce(partnerId: partner.id)
                                                    : WebSocketCommands.breakUp(partnerId: partner.id)
                                                webSocketService.sendMessage(message: message)
                                                showBreakUpConfirmation = false
                                            }) {
                                                Text(isMarried ? "End Marriage" : "End Relationship")
                                                    .font(.appHeadline)
                                                    .foregroundColor(.white)
                                                    .frame(maxWidth: .infinity)
                                                    .padding(.vertical, AppSpacing.md)
                                                    .background(
                                                        LinearGradient(
                                                            colors: [
                                                                AppColors.error,
                                                                AppColors.error.opacity(0.8)
                                                            ],
                                                            startPoint: .leading,
                                                            endPoint: .trailing
                                                        )
                                                    )
                                                    .cornerRadius(AppSpacing.cornerRadius)
                                                    .shadow(color: AppColors.error.opacity(0.4), radius: 8, x: 0, y: 4)
                                            }
                                        }
                                    }
                                    .padding(AppSpacing.lg)
                                }
                                .padding(.horizontal, AppSpacing.lg)

                                Spacer()
                            }
                        }
                    }
                }
            } else {
                // SINGLE STATE - COZY ROMANTIC DESIGN
                ScrollView {
                    VStack(spacing: AppSpacing.lg) {
                        // Hero Card - Find Love with romantic gradient
                        BaseCard {
                            ZStack {
                                // Soft romantic gradient background (pinks, corals, purples)
                                LinearGradient(
                                    colors: [
                                        AppColors.primary.opacity(0.2),
                                        Color(hex: 0xFFB3C1).opacity(0.15),
                                        Color(hex: 0xD4A5F5).opacity(0.1)
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                                .cornerRadius(AppSpacing.cornerRadius)

                                VStack(spacing: AppSpacing.md) {
                                    // Pulsing heart icon with romantic glow
                                    ZStack {
                                        // Soft glow effect
                                        Circle()
                                            .fill(
                                                RadialGradient(
                                                    colors: [
                                                        AppColors.primary.opacity(0.3),
                                                        AppColors.primary.opacity(0.0)
                                                    ],
                                                    center: .center,
                                                    startRadius: 20,
                                                    endRadius: 50
                                                )
                                            )
                                            .frame(width: 100, height: 100)

                                        Image(systemName: "heart.fill")
                                            .font(.system(size: 64))
                                            .foregroundStyle(
                                                LinearGradient(
                                                    colors: [
                                                        AppColors.primary,
                                                        AppColors.primaryDark
                                                    ],
                                                    startPoint: .top,
                                                    endPoint: .bottom
                                                )
                                            )
                                            .shadow(color: AppColors.primary.opacity(0.5), radius: 15, x: 0, y: 5)
                                    }

                                    // Encouraging text with romantic styling
                                    Text("Your love story awaits")
                                        .font(.appLargeTitle)
                                        .foregroundColor(AppColors.primaryText)
                                        .multilineTextAlignment(.center)
                                        .shadow(color: AppColors.primary.opacity(0.1), radius: 2, x: 0, y: 1)

                                    Text("Start swiping to find your perfect match")
                                        .font(.appBody)
                                        .foregroundColor(AppColors.secondaryText)
                                        .multilineTextAlignment(.center)
                                        .padding(.horizontal, AppSpacing.sm)

                                    // Start Swiping Button with romantic styling
                                    Button(action: {
                                        hapticFeedback(style: .medium)
                                        isSwipeDatingViewPresented.toggle()
                                    }) {
                                        HStack(spacing: AppSpacing.xs) {
                                            Image(systemName: "sparkles")
                                                .font(.system(size: 16, weight: .semibold))

                                            Text("Start Swiping")
                                                .font(.appHeadline)

                                            Image(systemName: "heart.fill")
                                                .font(.system(size: 14, weight: .semibold))
                                        }
                                        .foregroundColor(.white)
                                        .frame(maxWidth: .infinity)
                                        .padding(.vertical, AppSpacing.md)
                                        .background(
                                            LinearGradient(
                                                colors: [
                                                    AppColors.primary,
                                                    AppColors.primaryDark
                                                ],
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .cornerRadius(AppSpacing.cornerRadius)
                                        .shadow(color: AppColors.primary.opacity(0.4), radius: 8, x: 0, y: 4)
                                    }
                                    .padding(.top, AppSpacing.sm)
                                }
                                .padding(AppSpacing.lg)
                            }
                        }
                        .sheet(isPresented: $isSwipeDatingViewPresented) {
                            SwipeDatingView()
                        }

                        // Matches Section with romantic styling
                        if webSocketService.player.r.contains(where: { $0.relationships.contains("dating_match") }) {
                            VStack(alignment: .leading, spacing: AppSpacing.md) {
                                // Section Header with romantic flair
                                HStack(spacing: AppSpacing.xs) {
                                    // Gradient heart icon
                                    Image(systemName: "heart.circle.fill")
                                        .font(.system(size: 24))
                                        .foregroundStyle(
                                            LinearGradient(
                                                colors: [
                                                    AppColors.primary,
                                                    AppColors.primaryDark
                                                ],
                                                startPoint: .top,
                                                endPoint: .bottom
                                            )
                                        )
                                        .shadow(color: AppColors.primary.opacity(0.3), radius: 4, x: 0, y: 2)

                                    Text("Your Matches")
                                        .font(.appTitle)
                                        .foregroundColor(AppColors.primaryText)

                                    // Sparkle decoration
                                    Image(systemName: "sparkles")
                                        .font(.system(size: 14))
                                        .foregroundColor(AppColors.accent)
                                }
                                .padding(.horizontal, AppSpacing.sm)

                                // Match Cards with enhanced styling
                                VStack(spacing: AppSpacing.sm) {
                                    ForEach(webSocketService.player.r) { person in
                                        if person.relationships.contains("dating_match") {
                                            Button(action: {
                                                hapticFeedback(style: .light)
                                                chatPresentation = ChatPresentationItem(id: person.id)
                                            }) {
                                                MatchCard(person: person)
                                            }
                                            .buttonStyle(PlainButtonStyle())
                                        }
                                    }
                                }
                            }
                            .padding(.bottom, 100) // Space for tab bar
                        } else {
                            // Empty Matches State with romantic touch
                            BaseCard {
                                ZStack {
                                    // Subtle romantic gradient background
                                    LinearGradient(
                                        colors: [
                                            Color(hex: 0xFFE5E5).opacity(0.3),
                                            Color(hex: 0xF5E5FF).opacity(0.2)
                                        ],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    )
                                    .cornerRadius(AppSpacing.cornerRadius)

                                    VStack(spacing: AppSpacing.md) {
                                        // Sparkles with glow
                                        ZStack {
                                            Circle()
                                                .fill(
                                                    RadialGradient(
                                                        colors: [
                                                            AppColors.accent.opacity(0.2),
                                                            AppColors.accent.opacity(0.0)
                                                        ],
                                                        center: .center,
                                                        startRadius: 10,
                                                        endRadius: 40
                                                    )
                                                )
                                                .frame(width: 80, height: 80)

                                            Image(systemName: "sparkles")
                                                .font(.system(size: 44))
                                                .foregroundStyle(
                                                    LinearGradient(
                                                        colors: [
                                                            AppColors.accent,
                                                            AppColors.accentDark
                                                        ],
                                                        startPoint: .top,
                                                        endPoint: .bottom
                                                    )
                                                )
                                        }

                                        Text("No matches yet")
                                            .font(.appTitle)
                                            .foregroundColor(AppColors.primaryText)

                                        Text("Keep swiping to find your special someone!")
                                            .font(.appBody)
                                            .foregroundColor(AppColors.secondaryText)
                                            .multilineTextAlignment(.center)
                                            .padding(.horizontal, AppSpacing.md)
                                    }
                                    .padding(AppSpacing.lg)
                                }
                            }
                            .padding(.bottom, 100) // Space for tab bar
                        }
                    }
                    .padding(AppSpacing.md)
                    .padding(.top, AppSpacing.sm) // Additional top spacing for header visibility
                }
                .background(AppColors.primaryBackground)
                .fullScreenCover(item: $chatPresentation) { presentation in
                    ChatView(characterID: presentation.id)
                        .environmentObject(webSocketService)
                }
            }
        }
        .onAppear {
            AnalyticsManager.shared.trackScreenView("dating", screenClass: "DatingView")
        }
    }
}


struct DatingView_Previews: PreviewProvider {
    static var previews: some View {
        DatingView()
    }
}


#Preview {
    DatingView()
}
