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

import SwiftUI
import SDWebImageSwiftUI

struct SwipeDatingView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @Environment(\.dismiss) var dismiss
    @State private var dragAmount: CGSize = .zero
    @State private var showMatchPopup: Bool = false
    @State private var match: Person?
    @State private var chatPresentation: ChatPresentationItem?  // Open chat with a new match
    @State private var showCompatibilityExplanation: Bool = false

    // Card dimensions - using safe area aware calculations
    private var cardWidth: CGFloat {
        UIScreen.main.bounds.width - (AppSpacing.md * 2)
    }
    private var cardHeight: CGFloat {
        UIScreen.main.bounds.height * 0.65
    }

    var body: some View {
        ZStack {
            // Romantic gradient background
            LinearGradient(
                colors: [
                    AppColors.background,
                    Color(hex: 0xFFE8F0).opacity(0.3),
                    AppColors.background
                ],
                startPoint: .top,
                endPoint: .bottom
            )
            .ignoresSafeArea()

            VStack(spacing: 0) {
                // Header with romantic styling
                HStack {
                    // Heart icon decoration
                    Image(systemName: "heart.fill")
                        .font(.system(size: 20))
                        .foregroundStyle(
                            LinearGradient(
                                colors: [
                                    AppColors.primary,
                                    AppColors.primaryDark
                                ],
                                startPoint: .top,
                                endPoint: .bottom
                            )
                        )

                    Text("Find Your Match")
                        .font(.appTitle)
                        .foregroundColor(AppColors.primaryText)

                    Spacer()

                    Button(action: {
                        hapticFeedback(style: .light)
                        dismiss()
                    }) {
                        HStack(spacing: AppSpacing.xs) {
                            Text("Done")
                                .font(.appHeadline)
                                .foregroundColor(.white)
                        }
                        .padding(.horizontal, AppSpacing.md)
                        .padding(.vertical, AppSpacing.sm)
                        .background(
                            LinearGradient(
                                colors: [
                                    AppColors.primary.opacity(0.8),
                                    AppColors.primaryDark.opacity(0.8)
                                ],
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .cornerRadius(AppSpacing.cornerRadius)
                        .shadow(color: AppColors.primary.opacity(0.3), radius: 4, x: 0, y: 2)
                    }
                }
                .padding(.horizontal, AppSpacing.md)
                .padding(.top, AppSpacing.md)
                .padding(.bottom, AppSpacing.sm)

                Spacer()
                    .frame(height: AppSpacing.md)

                if let character = webSocketService.swipeCharacter {
                    // Enhanced Profile Card
                    EnhancedProfileCard(
                        person: character,
                        currentPersonInterests: webSocketService.person.interests,
                        onExplainCompatibility: {
                            showCompatibilityExplanation = true
                        }
                    )
                    .frame(width: cardWidth, height: cardHeight)
                    .offset(dragAmount)
                    .rotationEffect(.degrees(Double(dragAmount.width) / 20))
                    .gesture(
                        DragGesture()
                            .onChanged { gesture in
                                self.dragAmount = gesture.translation
                            }
                            .onEnded { gesture in
                                withAnimation(.easeOut(duration: 0.3)) {
                                    if abs(gesture.translation.width) > 100 {
                                        swipe(left: gesture.translation.width < 0, character: character)
                                    } else {
                                        self.dragAmount = .zero
                                    }
                                }
                            }
                    )

                    // Swipe indicators
                    swipeIndicators

                } else {
                    // INTEGRATION: Using SkeletonView for better loading experience
                    SkeletonView()
                        .frame(width: cardWidth, height: cardHeight)
                        .cornerRadius(AppSpacing.cornerRadius)
                }
            }
            .padding(.bottom, AppSpacing.lg)

            // Compatibility explanation sheet with romantic overlay
            if showCompatibilityExplanation, let character = webSocketService.swipeCharacter {
                // Romantic soft overlay
                LinearGradient(
                    colors: [
                        AppColors.primary.opacity(0.3),
                        Color.black.opacity(0.5),
                        AppColors.primary.opacity(0.3)
                    ],
                    startPoint: .top,
                    endPoint: .bottom
                )
                .ignoresSafeArea()
                .onTapGesture {
                    withAnimation(.easeOut(duration: 0.3)) {
                        showCompatibilityExplanation = false
                    }
                }

                CompatibilityExplanationView(
                    person: character,
                    currentPerson: webSocketService.person
                )
                .frame(width: cardWidth, height: cardHeight * 0.8)
                .transition(.move(edge: .bottom).combined(with: .opacity))
                .shadow(color: AppColors.primary.opacity(0.3), radius: 20, x: 0, y: 10)
            }
        }
        .onAppear {
            fetchCharacter()
        }
        // Post-match celebration: shows who you matched with and offers clear next
        // steps (message them now or keep swiping) instead of a transient toast.
        .fullScreenCover(isPresented: $showMatchPopup) {
            if let match = match {
                MatchCelebrationView(
                    partner: match,
                    explanation: MatchExplanation.generate(
                        for: match,
                        currentPersonInterests: webSocketService.person.interests
                    ),
                    onSendMessage: {
                        showMatchPopup = false
                        // Present the chat after the celebration dismisses to avoid
                        // competing full-screen transitions.
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                            chatPresentation = ChatPresentationItem(id: match.id)
                        }
                    },
                    onKeepSwiping: {
                        showMatchPopup = false
                        dragAmount = .zero
                        fetchCharacter()
                    }
                )
                .environmentObject(webSocketService)
            }
        }
        // Chat with the new match, opened from the celebration screen.
        // When the chat closes, dismiss swiping too so the player lands back on the
        // Dating page, which now shows their active relationship.
        .fullScreenCover(item: $chatPresentation, onDismiss: { dismiss() }) { presentation in
            ChatView(characterID: presentation.id)
                .environmentObject(webSocketService)
        }
    }

    // MARK: - Swipe Indicators with romantic styling
    private var swipeIndicators: some View {
        HStack(spacing: AppSpacing.xxl) {
            // Dislike indicator (left swipe) with glow
            ZStack {
                // Glow effect
                if dragAmount.width < -50 {
                    Circle()
                        .fill(
                            RadialGradient(
                                colors: [
                                    AppColors.error.opacity(0.3),
                                    AppColors.error.opacity(0.0)
                                ],
                                center: .center,
                                startRadius: 20,
                                endRadius: 60
                            )
                        )
                        .frame(width: 120, height: 120)
                }

                Image(systemName: "xmark.circle.fill")
                    .font(.system(size: 72, weight: .bold))
                    .foregroundStyle(
                        LinearGradient(
                            colors: [
                                AppColors.error,
                                AppColors.error.opacity(0.7)
                            ],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .shadow(color: AppColors.error.opacity(0.5), radius: 12, x: 0, y: 4)
                    .opacity(dragAmount.width < -50 ? Double(-dragAmount.width) / 100 : 0)
            }

            Spacer()

            // Like indicator (right swipe) with romantic glow
            ZStack {
                // Romantic glow effect
                if dragAmount.width > 50 {
                    Circle()
                        .fill(
                            RadialGradient(
                                colors: [
                                    AppColors.primary.opacity(0.4),
                                    AppColors.primary.opacity(0.0)
                                ],
                                center: .center,
                                startRadius: 20,
                                endRadius: 60
                            )
                        )
                        .frame(width: 120, height: 120)
                }

                Image(systemName: "heart.circle.fill")
                    .font(.system(size: 72, weight: .bold))
                    .foregroundStyle(
                        LinearGradient(
                            colors: [
                                AppColors.primary,
                                AppColors.primaryDark
                            ],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .shadow(color: AppColors.primary.opacity(0.6), radius: 12, x: 0, y: 4)
                    .opacity(dragAmount.width > 50 ? Double(dragAmount.width) / 100 : 0)
            }
        }
        .padding(.horizontal, AppSpacing.xl)
    }

    // MARK: - Helper Functions
    func swipe(left: Bool, character:Person) {
            let didMatch = !left && Bool.random()

            // INTEGRATION: Track swipe analytics
            AnalyticsManager.shared.track(.datingSwipe(
                direction: left ? "left" : "right",
                characterId: character.id
            ))
            if didMatch {
                AnalyticsManager.shared.track(.datingMatch(characterId: character.id))
            }

            if left {
                // Add your action for left swipe if any
            } else {
                // If there's a match
                if didMatch {
                    // INTEGRATION: Play achievement sound on match
                    SoundManager.shared.playSound(.achievement)
                    performCozyHaptic(.celebration)

                    // Remember who we matched with so the celebration shows the
                    // right person even after the swipe card is replaced.
                    match = character

                    webSocketService.sendMessage(message: WebSocketCommands.swipeMatch(characterId: character.id))
                    character.relationships.append("dating_match")
                    webSocketService.player.r.append(character)

                    showMatchPopup = true
                }
            }

            // Animate card off screen
            dragAmount = CGSize(width: left ? -UIScreen.main.bounds.width : UIScreen.main.bounds.width, height: 0)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                // Fetch new character
                if !showMatchPopup {
                    dragAmount = .zero
                    fetchCharacter()
                }
            }
        }
        
        func fetchCharacter() {
            
            let preferredSex = (webSocketService.person.sex == "Male") ? "Female" : "Male"
        
            webSocketService.sendMessage(message: WebSocketCommands.getSwipeCharacter(preferredSex: preferredSex))
            // Handle the incoming character in your WebSocketService and assign it to currentCharacter
        }

    func isMatch() -> Bool {
        // For now, it's a 50% chance
        return Bool.random()
    }
}



#Preview {
    SwipeDatingView()
}

