//
//  DateMiniGameView.swift
//  lichunWebsocket
//
//  Interactive conversation-based mini-game during dates
//

import SwiftUI

// MARK: - Data Models

struct DateQuestion: Identifiable {
    let id: String
    let text: String
    let responses: [DateResponse]
    let round: Int
}

struct DateResponse: Identifiable {
    let id: String
    let text: String
    let isCorrect: Bool
    let affinityImpact: Int
}

class DateMiniGameState: ObservableObject, Identifiable {
    let id: String
    let partnerId: String
    let partnerName: String
    let activityId: String
    @Published var currentRound: Int = 0
    @Published var correctAnswers: Int = 0
    @Published var totalAffinity: Int = 0
    var questions: [DateQuestion]
    @Published var isComplete: Bool = false
    @Published var selectedResponse: DateResponse?
    @Published var showFeedback: Bool = false

    init(
        id: String,
        partnerId: String,
        partnerName: String,
        activityId: String,
        questions: [DateQuestion]
    ) {
        self.id = id
        self.partnerId = partnerId
        self.partnerName = partnerName
        self.activityId = activityId
        self.questions = questions
    }

    var totalRounds: Int {
        return questions.count
    }

    var currentQuestion: DateQuestion? {
        guard currentRound < questions.count else { return nil }
        return questions[currentRound]
    }

    var performance: String {
        let percentage = Double(correctAnswers) / Double(totalRounds) * 100
        switch percentage {
        case 90...100: return "Excellent"
        case 70..<90: return "Great"
        case 50..<70: return "Good"
        default: return "Okay"
        }
    }

    var performanceColor: Color {
        let percentage = Double(correctAnswers) / Double(totalRounds) * 100
        switch percentage {
        case 90...100: return AppColors.success
        case 70..<90: return AppColors.primary
        case 50..<70: return AppColors.warning
        default: return AppColors.error
        }
    }
}

// MARK: - Date Mini Game View

struct DateMiniGameView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @Environment(\.dismiss) var dismiss
    @ObservedObject var gameState: DateMiniGameState

    let partner: Person

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

            if gameState.isComplete {
                resultsView
            } else {
                gameView
            }
        }
    }

    // MARK: - Game View

    private var gameView: some View {
        VStack(spacing: 0) {
            // Header with progress
            headerSection

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

            ScrollView {
                VStack(spacing: AppSpacing.lg) {
                    // Partner avatar and dialogue
                    partnerDialogueSection

                    // Response options
                    if let question = gameState.currentQuestion {
                        responseOptionsSection(question: question)
                    }
                }
                .padding(AppSpacing.md)
            }
        }
    }

    // MARK: - Header Section

    private var headerSection: some View {
        VStack(spacing: AppSpacing.sm) {
            HStack {
                // Round indicator with romantic styling
                HStack(spacing: AppSpacing.xs) {
                    Image(systemName: "heart.circle.fill")
                        .font(.system(size: 16))
                        .foregroundStyle(
                            LinearGradient(
                                colors: [
                                    AppColors.primary,
                                    AppColors.primaryDark
                                ],
                                startPoint: .top,
                                endPoint: .bottom
                            )
                        )

                    Text("Round \(gameState.currentRound + 1)/\(gameState.totalRounds)")
                        .font(.appHeadline)
                        .foregroundColor(AppColors.primaryText)
                }

                Spacer()

                // Score with romantic hearts
                HStack(spacing: AppSpacing.xs) {
                    Text("Score:")
                        .font(.appBody)
                        .foregroundColor(AppColors.secondaryText)

                    Text("\(gameState.correctAnswers)/\(gameState.currentRound)")
                        .font(.appBodyBold)
                        .foregroundColor(AppColors.primary)

                    // Romantic heart indicators
                    ForEach(0..<min(3, gameState.correctAnswers), id: \.self) { _ in
                        Image(systemName: "heart.fill")
                            .foregroundStyle(
                                LinearGradient(
                                    colors: [
                                        AppColors.primary,
                                        AppColors.primaryDark
                                    ],
                                    startPoint: .top,
                                    endPoint: .bottom
                                )
                            )
                            .font(.system(size: 14))
                            .shadow(color: AppColors.primary.opacity(0.4), radius: 3, x: 0, y: 1)
                    }
                }
            }

            // Romantic progress bar with gradient
            GeometryReader { geometry in
                ZStack(alignment: .leading) {
                    // Background
                    RoundedRectangle(cornerRadius: 3)
                        .fill(AppColors.secondaryText.opacity(0.15))
                        .frame(height: 6)

                    // Progress with romantic gradient
                    RoundedRectangle(cornerRadius: 3)
                        .fill(
                            LinearGradient(
                                colors: [
                                    AppColors.primary,
                                    AppColors.primaryDark,
                                    AppColors.primary
                                ],
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .frame(
                            width: geometry.size.width * CGFloat(gameState.currentRound) / CGFloat(gameState.totalRounds),
                            height: 6
                        )
                        .shadow(color: AppColors.primary.opacity(0.5), radius: 4, x: 0, y: 2)
                }
            }
            .frame(height: 6)
        }
        .padding(.horizontal, AppSpacing.md)
        .padding(.vertical, AppSpacing.md)
        .background(AppColors.cardBackground.opacity(0.7))
    }

    // MARK: - Partner Dialogue Section

    private var partnerDialogueSection: some View {
        VStack(spacing: AppSpacing.md) {
            // Partner avatar with romantic border
            CharacterAvatar(
                person: partner,
                size: AppSpacing.avatarSizeLarge,
                showBorder: true,
                borderGradient: [AppColors.primary, AppColors.primaryDark],
                borderWidth: 3,
                showGlow: true
            )

            // Speech bubble with romantic styling
            if let question = gameState.currentQuestion {
                VStack(alignment: .leading, spacing: AppSpacing.sm) {
                    HStack {
                        HStack(spacing: AppSpacing.xs) {
                            Image(systemName: "heart.fill")
                                .foregroundColor(AppColors.primary)
                                .font(.system(size: 12))

                            Text(gameState.partnerName)
                                .font(.appHeadline)
                                .foregroundColor(AppColors.primaryText)
                        }

                        Spacer()

                        Image(systemName: "bubble.left.fill")
                            .foregroundStyle(
                                LinearGradient(
                                    colors: [
                                        AppColors.primary,
                                        AppColors.primaryDark
                                    ],
                                    startPoint: .top,
                                    endPoint: .bottom
                                )
                            )
                            .font(.system(size: 16))
                    }

                    Text(question.text)
                        .font(.appBody)
                        .foregroundColor(AppColors.primaryText)
                        .multilineTextAlignment(.leading)
                }
                .padding(AppSpacing.md)
                .background(
                    ZStack {
                        // Subtle romantic gradient
                        LinearGradient(
                            colors: [
                                AppColors.cardBackground,
                                AppColors.primary.opacity(0.05)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )

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

    // MARK: - Response Options Section

    private func responseOptionsSection(question: DateQuestion) -> some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            Text("Your Response:")
                .font(.appHeadline)
                .foregroundColor(AppColors.primaryText)

            ForEach(question.responses) { response in
                responseButton(response)
            }
        }
    }

    // MARK: - Response Button

    private func responseButton(_ response: DateResponse) -> some View {
        Button(action: {
            selectResponse(response)
        }) {
            HStack {
                Text(response.text)
                    .font(.appBody)
                    .foregroundColor(AppColors.primaryText)
                    .multilineTextAlignment(.leading)

                Spacer()

                if gameState.showFeedback && gameState.selectedResponse?.id == response.id {
                    HStack(spacing: AppSpacing.xs) {
                        Image(systemName: response.isCorrect ? "checkmark.circle.fill" : "xmark.circle.fill")
                            .foregroundColor(response.isCorrect ? AppColors.success : AppColors.error)

                        Text("\(response.affinityImpact >= 0 ? "+" : "")\(response.affinityImpact)")
                            .font(.appCaptionBold)
                            .foregroundColor(response.isCorrect ? AppColors.success : AppColors.error)
                    }
                }
            }
            .padding(AppSpacing.md)
            .background(
                gameState.showFeedback && gameState.selectedResponse?.id == response.id
                    ? (response.isCorrect ? AppColors.success.opacity(0.2) : AppColors.error.opacity(0.2))
                    : AppColors.cardBackground
            )
            .cornerRadius(AppSpacing.cornerRadius)
            .overlay(
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .stroke(
                        gameState.showFeedback && gameState.selectedResponse?.id == response.id
                            ? (response.isCorrect ? AppColors.success : AppColors.error)
                            : AppColors.secondaryText.opacity(0.3),
                        lineWidth: gameState.showFeedback && gameState.selectedResponse?.id == response.id ? 2 : 1
                    )
            )
        }
        .disabled(gameState.showFeedback)
    }

    // MARK: - Results View

    private var resultsView: some View {
        VStack(spacing: AppSpacing.lg) {
            Spacer()

            // Success icon with romantic glow
            ZStack {
                // Romantic glow effect
                Circle()
                    .fill(
                        RadialGradient(
                            colors: [
                                gameState.performanceColor.opacity(0.4),
                                gameState.performanceColor.opacity(0.0)
                            ],
                            center: .center,
                            startRadius: 30,
                            endRadius: 80
                        )
                    )
                    .frame(width: 160, height: 160)

                Circle()
                    .fill(gameState.performanceColor.opacity(0.2))
                    .frame(width: 120, height: 120)

                Image(systemName: "heart.circle.fill")
                    .font(.system(size: 72))
                    .foregroundStyle(
                        LinearGradient(
                            colors: [
                                gameState.performanceColor,
                                gameState.performanceColor.opacity(0.7)
                            ],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .shadow(color: gameState.performanceColor.opacity(0.5), radius: 12, x: 0, y: 6)

                // Sparkles decoration
                Image(systemName: "sparkles")
                    .font(.system(size: 24))
                    .foregroundColor(AppColors.accent)
                    .offset(x: -50, y: -50)

                Image(systemName: "sparkles")
                    .font(.system(size: 20))
                    .foregroundColor(AppColors.accent)
                    .offset(x: 50, y: 40)
            }

            // Results text with romantic styling
            VStack(spacing: AppSpacing.sm) {
                Text("Date Complete!")
                    .font(.appLargeTitle)
                    .foregroundColor(AppColors.primaryText)
                    .shadow(color: gameState.performanceColor.opacity(0.2), radius: 4, x: 0, y: 2)

                HStack(spacing: AppSpacing.xs) {
                    Image(systemName: "star.fill")
                        .foregroundColor(gameState.performanceColor)

                    Text("Performance: \(gameState.performance)")
                        .font(.appTitle)
                        .foregroundColor(gameState.performanceColor)

                    Image(systemName: "star.fill")
                        .foregroundColor(gameState.performanceColor)
                }

                Text("\(gameState.correctAnswers) out of \(gameState.totalRounds) correct answers")
                    .font(.appBody)
                    .foregroundColor(AppColors.secondaryText)
            }

            // Affinity gained card with romantic styling
            BaseCard {
                ZStack {
                    // Romantic gradient background
                    LinearGradient(
                        colors: [
                            AppColors.primary.opacity(0.15),
                            Color(hex: 0xFFE8F0).opacity(0.2),
                            AppColors.primary.opacity(0.1)
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                    .cornerRadius(AppSpacing.cornerRadius)

                    VStack(spacing: AppSpacing.md) {
                        HStack(spacing: AppSpacing.xs) {
                            Image(systemName: "heart.fill")
                                .font(.system(size: 20))
                                .foregroundStyle(
                                    LinearGradient(
                                        colors: [
                                            AppColors.primary,
                                            AppColors.primaryDark
                                        ],
                                        startPoint: .top,
                                        endPoint: .bottom
                                    )
                                )

                            Text("Affinity Gained")
                                .font(.appHeadline)
                                .foregroundColor(AppColors.primaryText)

                            Image(systemName: "heart.fill")
                                .font(.system(size: 20))
                                .foregroundStyle(
                                    LinearGradient(
                                        colors: [
                                            AppColors.primary,
                                            AppColors.primaryDark
                                        ],
                                        startPoint: .top,
                                        endPoint: .bottom
                                    )
                                )
                        }

                        Text("+\(gameState.totalAffinity)")
                            .font(.system(size: 48, weight: .bold))
                            .foregroundStyle(
                                LinearGradient(
                                    colors: [
                                        AppColors.primary,
                                        AppColors.primaryDark
                                    ],
                                    startPoint: .top,
                                    endPoint: .bottom
                                )
                            )
                            .shadow(color: AppColors.primary.opacity(0.4), radius: 8, x: 0, y: 4)

                        Text("with \(gameState.partnerName)")
                            .font(.appBody)
                            .foregroundColor(AppColors.secondaryText)
                    }
                    .padding(AppSpacing.lg)
                }
            }
            .padding(.horizontal, AppSpacing.lg)

            Spacer()

            // Continue button with romantic styling
            Button(action: {
                hapticFeedback(style: .medium)
                dismiss()
            }) {
                HStack(spacing: AppSpacing.xs) {
                    Image(systemName: "checkmark.circle.fill")
                        .font(.system(size: 18))

                    Text("Continue")
                        .font(.appHeadline)

                    Image(systemName: "sparkles")
                        .font(.system(size: 14))
                }
                .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(.horizontal, AppSpacing.lg)
        }
        .padding(AppSpacing.lg)
    }

    // MARK: - Helper Methods

    private func selectResponse(_ response: DateResponse) {
        guard !gameState.showFeedback else { return }

        gameState.selectedResponse = response
        gameState.showFeedback = true

        // Update stats
        if response.isCorrect {
            gameState.correctAnswers += 1
        }
        gameState.totalAffinity += response.affinityImpact

        // Send to server
        webSocketService.sendMessage(message: WebSocketCommands.dateMiniGameResponse(
            gameId: gameState.id,
            round: gameState.currentRound,
            responseId: response.id
        ))

        // Move to next round after delay
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            gameState.showFeedback = false
            gameState.selectedResponse = nil
            gameState.currentRound += 1

            if gameState.currentRound >= gameState.totalRounds {
                gameState.isComplete = true
            }
        }
    }
}

// MARK: - Preview

#if DEBUG
struct DateMiniGameView_Previews: PreviewProvider {
    static var previews: some View {
        let samplePerson = Person()
        samplePerson.id = "partner123"
        samplePerson.firstname = "Sarah"
        samplePerson.lastname = "Johnson"
        samplePerson.image = "https://api.dicebear.com/7.x/avataaars/svg?seed=Sarah"

        let questions = [
            DateQuestion(
                id: "q1",
                text: "I love going to concerts! What kind of music do you like?",
                responses: [
                    DateResponse(id: "r1", text: "Me too! What's your favorite genre?", isCorrect: true, affinityImpact: 3),
                    DateResponse(id: "r2", text: "That's nice.", isCorrect: false, affinityImpact: 0),
                    DateResponse(id: "r3", text: "I prefer staying home.", isCorrect: false, affinityImpact: -1)
                ],
                round: 0
            ),
            DateQuestion(
                id: "q2",
                text: "I'm thinking about traveling to Japan next year. Have you been?",
                responses: [
                    DateResponse(id: "r4", text: "That sounds amazing! Tell me more about your plans.", isCorrect: true, affinityImpact: 3),
                    DateResponse(id: "r5", text: "Cool.", isCorrect: false, affinityImpact: 0),
                    DateResponse(id: "r6", text: "I don't like traveling.", isCorrect: false, affinityImpact: -2)
                ],
                round: 1
            ),
            DateQuestion(
                id: "q3",
                text: "What do you value most in a relationship?",
                responses: [
                    DateResponse(id: "r7", text: "Trust and communication are key for me.", isCorrect: true, affinityImpact: 4),
                    DateResponse(id: "r8", text: "Having fun together.", isCorrect: true, affinityImpact: 2),
                    DateResponse(id: "r9", text: "I don't know.", isCorrect: false, affinityImpact: -1)
                ],
                round: 2
            )
        ]

        let gameState = DateMiniGameState(
            id: "game123",
            partnerId: "partner123",
            partnerName: "Sarah",
            activityId: "dinner",
            questions: questions
        )

        return DateMiniGameView(
            gameState: gameState,
            partner: samplePerson
        )
        .environmentObject(WebSocketService(
            urlSession: URLSession.shared,
            delegateQueue: OperationQueue()
        ))
    }
}
#endif
