//
//  ActionsSection.swift
//  lichunWebsocket
//
//  Actions section with scalable grid and horizontal scroll per category
//

import SwiftUI

struct ActionsSection: View {
    @ObservedObject var person: Person
    let onAction: (ActionItem) -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.lg) {
            // Social Actions
            if !socialActions.isEmpty {
                ActionCategory(
                    title: "Social",
                    icon: "bubble.left.and.bubble.right.fill",
                    actions: socialActions,
                    onAction: onAction
                )
            }

            // Gift Actions (if appropriate affinity)
            if person.affinity >= 20 {
                ActionCategory(
                    title: "Gifts",
                    icon: "gift.fill",
                    actions: giftActions,
                    onAction: onAction
                )
            }

            // Romantic Actions (for partners/crushes with high affinity)
            if isRomanticRelationship && person.affinity >= 50 {
                ActionCategory(
                    title: "Romantic",
                    icon: "heart.fill",
                    actions: romanticActions,
                    onAction: onAction
                )
            }

            // Activities (shared activities)
            ActionCategory(
                title: "Activities",
                icon: "figure.walk",
                actions: activityActions,
                onAction: onAction
            )
        }
    }

    // MARK: - Computed Properties

    private var isRomanticRelationship: Bool {
        let relationships = person.relationships.map { $0.lowercased() }
        return relationships.contains("partner") ||
               relationships.contains("spouse") ||
               relationships.contains("crush") ||
               relationships.contains("dating")
    }

    private var socialActions: [ActionItem] {
        var actions: [ActionItem] = [
            ActionItem(id: "chat", title: "Chat", icon: "bubble.left.fill", color: AppColors.primary),
            ActionItem(id: "flatter", title: "Compliment", icon: "hand.thumbsup.fill", color: Color.green),
            ActionItem(id: "checkIn", title: "Check In", icon: "hand.wave.fill", color: Color.cyan)
        ]

        if person.affinity >= 30 {
            actions.append(ActionItem(id: "activity", title: "Hang Out", icon: "person.2.fill", color: AppColors.accent))
        }

        if person.affinity >= 50 {
            actions.append(ActionItem(id: "askAboutDay", title: "Deep Talk", icon: "brain.head.profile", color: Color.purple))
        }

        return actions
    }

    private var giftActions: [ActionItem] {
        // Backend has single gift action (partnerGift) that costs $100
        return [
            ActionItem(id: "partnerGift", title: "Give Gift", icon: "gift.fill", color: Color.pink)
        ]
    }

    private var romanticActions: [ActionItem] {
        // Check if already in a relationship
        let hasRelationship = person.relationships.contains { rel in
            let lower = rel.lowercased()
            return lower == "partner" || lower == "spouse" || lower == "dating"
        }

        if hasRelationship {
            // Already in relationship - romantic chat is handled by backend based on relationship type
            return [
                ActionItem(id: "chat", title: "Romantic Chat", icon: "heart.fill", color: Color.pink)
            ]
        } else {
            // Not in relationship - can try to start one
            return [
                ActionItem(id: "romance", title: "Ask Out", icon: "heart.fill", color: Color.pink)
            ]
        }
    }

    private var activityActions: [ActionItem] {
        // Date ideas from backend: getDateIdeas() in relationship_manager.py
        return [
            ActionItem(id: "Movie Night at Home", title: "Movie Night", icon: "tv.fill", color: Color.blue),
            ActionItem(id: "Picnic in the Park", title: "Picnic", icon: "leaf.fill", color: Color.green),
            ActionItem(id: "Fine Dining Experience", title: "Fine Dining", icon: "fork.knife", color: Color.orange),
            ActionItem(id: "Hiking Adventure", title: "Hiking", icon: "figure.hiking", color: Color.brown),
            ActionItem(id: "Beach Day", title: "Beach Day", icon: "sun.max.fill", color: Color.yellow)
        ]
    }
}

// MARK: - Action Item Model

struct ActionItem: Identifiable {
    let id: String
    let title: String
    let icon: String
    let color: Color
}

// MARK: - Action Category Component

private struct ActionCategory: View {
    let title: String
    let icon: String
    let actions: [ActionItem]
    let onAction: (ActionItem) -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            // Category header
            HStack(spacing: AppSpacing.xs) {
                Image(systemName: icon)
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(AppColors.secondaryText)

                Text(title)
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)
            }

            // Horizontal scroll of action buttons
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: AppSpacing.sm) {
                    ForEach(actions) { action in
                        ActionButton(action: action, onTap: { onAction(action) })
                    }
                }
                .padding(.horizontal, AppSpacing.xs)
            }
        }
    }
}

// MARK: - Action Button Component

private struct ActionButton: View {
    let action: ActionItem
    let onTap: () -> Void

    @State private var isPressed = false

    var body: some View {
        Button(action: {
            hapticFeedback(style: .medium)
            onTap()
        }) {
            VStack(spacing: AppSpacing.xs) {
                ZStack {
                    Circle()
                        .fill(action.color.opacity(0.15))
                        .frame(width: 50, height: 50)

                    Image(systemName: action.icon)
                        .font(.system(size: 20, weight: .semibold))
                        .foregroundColor(action.color)
                }

                Text(action.title)
                    .font(.appCaption)
                    .foregroundColor(AppColors.primaryText)
                    .lineLimit(1)
            }
            .frame(width: 70)
            .scaleEffect(isPressed ? 0.95 : 1.0)
        }
        .buttonStyle(PlainButtonStyle())
        .simultaneousGesture(
            DragGesture(minimumDistance: 0)
                .onChanged { _ in
                    withAnimation(.easeInOut(duration: 0.1)) {
                        isPressed = true
                    }
                }
                .onEnded { _ in
                    withAnimation(.easeInOut(duration: 0.1)) {
                        isPressed = false
                    }
                }
        )
    }
}

// MARK: - Preview

#if DEBUG
struct ActionsSection_Previews: PreviewProvider {
    static var previews: some View {
        let samplePerson = Person()
        samplePerson.id = "123"
        samplePerson.firstname = "Emma"
        samplePerson.lastname = "Johnson"
        samplePerson.affinity = 75
        samplePerson.relationships = ["friend", "crush"]

        return ScrollView {
            ActionsSection(person: samplePerson) { action in
                print("Action tapped: \(action.id)")
            }
            .padding()
        }
        .background(AppColors.background)
    }
}
#endif
