//
//  RelationshipEventModal.swift
//  lichunWebsocket
//
//  Relationship event modals for handling special relationship moments
//

import SwiftUI

// MARK: - Data Models

struct RelationshipEvent: Identifiable {
    let id: String
    let type: EventType
    let title: String
    let description: String
    let partnerName: String
    let partnerId: String
    let choices: [EventChoice]

    enum EventType: String {
        case argument
        case anniversary
        case jealousy
        case proposal
        case breakupThreat

        var icon: String {
            switch self {
            case .argument: return "exclamationmark.triangle.fill"
            case .anniversary: return "heart.circle.fill"
            case .jealousy: return "eyes"
            case .proposal: return "ring.circle.fill"
            case .breakupThreat: return "heart.slash.fill"
            }
        }

        var iconColor: Color {
            switch self {
            case .argument: return AppColors.warning
            case .anniversary: return AppColors.primary
            case .jealousy: return AppColors.error
            case .proposal: return AppColors.success
            case .breakupThreat: return AppColors.error
            }
        }

        var backgroundColor: Color {
            switch self {
            case .argument: return AppColors.warning.opacity(0.1)
            case .anniversary: return AppColors.primary.opacity(0.1)
            case .jealousy: return AppColors.error.opacity(0.1)
            case .proposal: return AppColors.success.opacity(0.1)
            case .breakupThreat: return AppColors.error.opacity(0.1)
            }
        }
    }
}

struct EventChoice: Identifiable {
    let id: String
    let text: String
    let affinityChange: Int
    let diamondCost: Int
    let moneyCost: Int
    let energyCost: Int

    init(
        id: String,
        text: String,
        affinityChange: Int,
        diamondCost: Int = 0,
        moneyCost: Int = 0,
        energyCost: Int = 0
    ) {
        self.id = id
        self.text = text
        self.affinityChange = affinityChange
        self.diamondCost = diamondCost
        self.moneyCost = moneyCost
        self.energyCost = energyCost
    }

    var hasAnyCost: Bool {
        return diamondCost > 0 || moneyCost > 0 || energyCost > 0
    }

    var isFree: Bool {
        return !hasAnyCost
    }
}

// MARK: - Relationship Event Modal View

struct RelationshipEventModal: View {
    @EnvironmentObject var webSocketService: WebSocketService
    let event: RelationshipEvent
    let onDismiss: () -> Void

    @State private var selectedChoice: EventChoice?
    @State private var isProcessing: Bool = false

    var body: some View {
        ZStack {
            // Overlay
            AppColors.modalOverlay
                .ignoresSafeArea()
                .onTapGesture {
                    if !isProcessing {
                        onDismiss()
                    }
                }

            // Modal Content
            VStack(spacing: 0) {
                // Header with event type
                headerSection

                // Event description
                descriptionSection

                // Soft divider with gradient
                Rectangle()
                    .fill(
                        LinearGradient(
                            colors: [
                                AppColors.secondaryText.opacity(0),
                                AppColors.secondaryText.opacity(0.2),
                                AppColors.secondaryText.opacity(0)
                            ],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .frame(height: 1)
                    .padding(.horizontal, AppSpacing.md)

                // Choices
                ScrollView {
                    VStack(spacing: AppSpacing.sm) {
                        ForEach(event.choices) { choice in
                            choiceCard(choice)
                        }
                    }
                    .padding(AppSpacing.md)
                }
            }
            .frame(maxWidth: 400)
            .background(
                // Warm gradient background
                LinearGradient(
                    colors: [
                        AppColors.surfaceElevated,
                        AppColors.background
                    ],
                    startPoint: .top,
                    endPoint: .bottom
                )
            )
            .cornerRadius(AppSpacing.largeCornerRadius)
            .shadow(
                color: AppColors.primary.opacity(0.2),
                radius: AppSpacing.Shadow.radiusLarge,
                x: 0,
                y: AppSpacing.Shadow.offsetYLarge
            )
            .shadow(
                color: Color.black.opacity(0.1),
                radius: AppSpacing.Shadow.radiusMedium,
                x: 0,
                y: AppSpacing.Shadow.offsetY
            )
            .padding(.horizontal, AppSpacing.lg)
        }
    }

    // MARK: - Header Section

    private var headerSection: some View {
        VStack(spacing: AppSpacing.sm) {
            // Decorative top accent
            HStack(spacing: AppSpacing.xs) {
                ForEach(0..<5) { index in
                    Circle()
                        .fill(
                            LinearGradient(
                                colors: [AppColors.primary.opacity(0.4), AppColors.secondary.opacity(0.4)],
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .frame(width: 6, height: 6)
                }
            }
            .padding(.top, AppSpacing.sm)

            // Icon with gradient background
            ZStack {
                // Outer glow
                Circle()
                    .fill(
                        RadialGradient(
                            colors: [
                                event.type.backgroundColor.opacity(0.8),
                                event.type.backgroundColor.opacity(0.3),
                                event.type.backgroundColor.opacity(0)
                            ],
                            center: .center,
                            startRadius: 20,
                            endRadius: 40
                        )
                    )
                    .frame(width: 80, height: 80)

                // Main circle
                Circle()
                    .fill(
                        LinearGradient(
                            colors: [
                                event.type.backgroundColor,
                                event.type.backgroundColor.opacity(0.7)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .frame(width: 64, height: 64)
                    .overlay(
                        Circle()
                            .stroke(event.type.iconColor.opacity(0.3), lineWidth: 2)
                    )

                Image(systemName: event.type.icon)
                    .font(.system(size: 30, weight: .semibold))
                    .foregroundColor(event.type.iconColor)
            }
            .padding(.vertical, AppSpacing.xs)

            // Title with decorative lines
            VStack(spacing: AppSpacing.xs) {
                Text(event.title)
                    .font(.appLargeTitle)
                    .foregroundColor(AppColors.primaryText)
                    .multilineTextAlignment(.center)

                // Subtle decorative line
                Rectangle()
                    .fill(
                        LinearGradient(
                            colors: [
                                event.type.iconColor.opacity(0),
                                event.type.iconColor.opacity(0.4),
                                event.type.iconColor.opacity(0)
                            ],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .frame(height: 2)
                    .frame(maxWidth: 120)
            }

            // Partner name
            Text("with \(event.partnerName)")
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)
                .padding(.bottom, AppSpacing.sm)
        }
        .padding(.horizontal, AppSpacing.md)
    }

    // MARK: - Description Section

    private var descriptionSection: some View {
        Text(event.description)
            .font(.appBody)
            .foregroundColor(AppColors.primaryText)
            .multilineTextAlignment(.center)
            .lineSpacing(4)
            .padding(.horizontal, AppSpacing.lg)
            .padding(.vertical, AppSpacing.md)
            .background(
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .fill(AppColors.surfaceSubtle)
                    .shadow(
                        color: AppColors.primary.opacity(0.08),
                        radius: 6,
                        x: 0,
                        y: 2
                    )
            )
            .padding(.horizontal, AppSpacing.md)
            .padding(.bottom, AppSpacing.sm)
    }

    // MARK: - Choice Card

    private func choiceCard(_ choice: EventChoice) -> some View {
        Button(action: {
            selectChoice(choice)
        }) {
            VStack(alignment: .leading, spacing: AppSpacing.sm) {
                // Choice text
                Text(choice.text)
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)
                    .multilineTextAlignment(.leading)
                    .frame(maxWidth: .infinity, alignment: .leading)

                HStack(spacing: AppSpacing.md) {
                    // Affinity change
                    HStack(spacing: AppSpacing.xs) {
                        Image(systemName: choice.affinityChange >= 0 ? "heart.fill" : "heart.slash.fill")
                            .foregroundColor(choice.affinityChange >= 0 ? AppColors.success : AppColors.error)
                            .font(.system(size: AppSpacing.iconSizeSmall))

                        Text("\(choice.affinityChange >= 0 ? "+" : "")\(choice.affinityChange) Affinity")
                            .font(.appCaption)
                            .foregroundColor(choice.affinityChange >= 0 ? AppColors.success : AppColors.error)
                    }

                    Spacer()

                    // Costs
                    if choice.isFree {
                        Text("Free")
                            .font(.appCaptionBold)
                            .foregroundColor(AppColors.success)
                    } else {
                        HStack(spacing: AppSpacing.sm) {
                            if choice.energyCost > 0 {
                                HStack(spacing: 4) {
                                    Image(systemName: "bolt.fill")
                                        .foregroundColor(AppColors.energy)
                                        .font(.system(size: AppSpacing.iconSizeSmall))
                                    Text("\(choice.energyCost)")
                                        .font(.appCaption)
                                        .foregroundColor(AppColors.primaryText)
                                }
                            }

                            if choice.moneyCost > 0 {
                                HStack(spacing: 4) {
                                    Image(systemName: "dollarsign.circle.fill")
                                        .foregroundColor(AppColors.money)
                                        .font(.system(size: AppSpacing.iconSizeSmall))
                                    Text("\(choice.moneyCost)")
                                        .font(.appCaption)
                                        .foregroundColor(AppColors.primaryText)
                                }
                            }

                            if choice.diamondCost > 0 {
                                HStack(spacing: 4) {
                                    Image(systemName: "diamond.fill")
                                        .foregroundColor(AppColors.diamond)
                                        .font(.system(size: AppSpacing.iconSizeSmall))
                                    Text("\(choice.diamondCost)")
                                        .font(.appCaption)
                                        .foregroundColor(AppColors.primaryText)
                                }
                            }
                        }
                    }
                }
            }
            .padding(AppSpacing.md)
            .background(
                Group {
                    if selectedChoice?.id == choice.id {
                        // Selected state with warm gradient
                        LinearGradient(
                            colors: [
                                event.type.iconColor.opacity(0.25),
                                event.type.iconColor.opacity(0.15)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    } else {
                        // Default state with subtle gradient
                        LinearGradient(
                            colors: [
                                AppColors.surfaceElevated,
                                AppColors.background.opacity(0.8)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    }
                }
            )
            .cornerRadius(AppSpacing.cornerRadius)
            .overlay(
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .stroke(
                        selectedChoice?.id == choice.id
                            ? event.type.iconColor.opacity(0.6)
                            : AppColors.secondaryText.opacity(0.2),
                        lineWidth: selectedChoice?.id == choice.id ? 2 : 1.5
                    )
            )
            .shadow(
                color: selectedChoice?.id == choice.id
                    ? event.type.iconColor.opacity(0.3)
                    : AppColors.primary.opacity(0.1),
                radius: selectedChoice?.id == choice.id ? 8 : 4,
                x: 0,
                y: selectedChoice?.id == choice.id ? 4 : 2
            )
        }
        .disabled(isProcessing || !canAfford(choice))
        .opacity(canAfford(choice) ? 1.0 : 0.5)
        .scaleEffect(selectedChoice?.id == choice.id ? 0.98 : 1.0)
        .animation(.spring(response: 0.3, dampingFraction: 0.6), value: selectedChoice?.id)
    }

    // MARK: - Helper Methods

    private func canAfford(_ choice: EventChoice) -> Bool {
        let hasEnoughEnergy = webSocketService.person.calcEnergy >= choice.energyCost
        let hasEnoughMoney = webSocketService.person.money >= choice.moneyCost
        let hasEnoughDiamonds = webSocketService.person.diamonds >= choice.diamondCost

        return hasEnoughEnergy && hasEnoughMoney && hasEnoughDiamonds
    }

    private func selectChoice(_ choice: EventChoice) {
        guard canAfford(choice) else { return }

        selectedChoice = choice
        isProcessing = true

        // Send to WebSocket
        webSocketService.sendMessage(message: WebSocketCommands.relationshipEventResponse(
            eventId: event.id,
            choiceId: choice.id
        ))

        // Dismiss after a short delay
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            onDismiss()
        }
    }
}

// MARK: - Preview

#if DEBUG
struct RelationshipEventModal_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            // Argument Event
            RelationshipEventModal(
                event: RelationshipEvent(
                    id: "event1",
                    type: .argument,
                    title: "Argument",
                    description: "You and Sarah had a disagreement about future plans. How do you want to handle this?",
                    partnerName: "Sarah",
                    partnerId: "partner123",
                    choices: [
                        EventChoice(
                            id: "choice1",
                            text: "Apologize and discuss calmly",
                            affinityChange: 10
                        ),
                        EventChoice(
                            id: "choice2",
                            text: "Buy an apology gift",
                            affinityChange: 25,
                            diamondCost: 20
                        ),
                        EventChoice(
                            id: "choice3",
                            text: "Ignore the problem",
                            affinityChange: -10
                        )
                    ]
                ),
                onDismiss: {}
            )
            .previewDisplayName("Argument")

            // Anniversary Event
            RelationshipEventModal(
                event: RelationshipEvent(
                    id: "event2",
                    type: .anniversary,
                    title: "Anniversary!",
                    description: "It's your one-year anniversary with Emma! How would you like to celebrate?",
                    partnerName: "Emma",
                    partnerId: "partner456",
                    choices: [
                        EventChoice(
                            id: "choice1",
                            text: "Cook a romantic dinner",
                            affinityChange: 15,
                            moneyCost: 50,
                            energyCost: 20
                        ),
                        EventChoice(
                            id: "choice2",
                            text: "Plan an extravagant date",
                            affinityChange: 30,
                            diamondCost: 50
                        ),
                        EventChoice(
                            id: "choice3",
                            text: "Just spend time together",
                            affinityChange: 8
                        )
                    ]
                ),
                onDismiss: {}
            )
            .previewDisplayName("Anniversary")

            // Proposal Event
            RelationshipEventModal(
                event: RelationshipEvent(
                    id: "event3",
                    type: .proposal,
                    title: "Marriage Proposal",
                    description: "You're thinking about proposing to Alex. This is a big step!",
                    partnerName: "Alex",
                    partnerId: "partner789",
                    choices: [
                        EventChoice(
                            id: "choice1",
                            text: "Propose with a simple ring",
                            affinityChange: 50,
                            moneyCost: 500
                        ),
                        EventChoice(
                            id: "choice2",
                            text: "Grand proposal with diamond ring",
                            affinityChange: 100,
                            diamondCost: 100,
                            moneyCost: 1000
                        ),
                        EventChoice(
                            id: "choice3",
                            text: "Wait for a better time",
                            affinityChange: 0
                        )
                    ]
                ),
                onDismiss: {}
            )
            .previewDisplayName("Proposal")
        }
    }
}
#endif
