//
//  ActivityView.swift
//  lichunWebsocket
//
//  Redesigned activity detail sheet with cozy iOS game design
//

import SwiftUI
import SDWebImageSwiftUI

struct ActivityView: View {
    @State private var selectedPerson: Person?
    @EnvironmentObject var webSocketService: WebSocketService
    @Environment(\.dismiss) var dismiss
    var activity: ActivityProtocol
    @State private var isFullScreenPresented = false
    @State private var headerScale: CGFloat = 1.0
    @State private var showContent = false

    private var matchingRecord: ActivityRecord? {
        // Match by record id OR locationId. Education records use a distinct
        // record id and store the school/activity id in `location` (locationId),
        // so matching on id alone misses every education record and leaves the
        // sheet empty. Jobs/extracurriculars have an empty `location`, so the
        // extra clause never false-matches them.
        webSocketService.person.activityRecords.first {
            $0.id == activity.id || $0.location == activity.id
        }
    }

    // MARK: - Body

    var body: some View {
        ZStack {
            // Background
            AppColors.background
                .ignoresSafeArea()

            ScrollView {
                VStack(spacing: AppSpacing.cardSpacing) {
                    // Hero Header
                    heroHeader
                        .padding(.bottom, AppSpacing.sm)

                    VStack(spacing: AppSpacing.cardSpacing) {
                        // Performance Card
                        if let record = matchingRecord {
                            performanceCard(record: record)
                                .transition(.scale.combined(with: .opacity))
                        }

                        // Focus Selection Card
                        if !webSocketService.player.focuses.isEmpty {
                            focusCard
                                .transition(.scale.combined(with: .opacity))
                        }

                        // People Section
                        if !relatedPeople.isEmpty {
                            peopleSection
                                .transition(.scale.combined(with: .opacity))
                        }

                        // Action Button
                        if let record = matchingRecord {
                            actionButton(record: record)
                                .transition(.scale.combined(with: .opacity))
                        }
                    }
                    .padding(.horizontal, AppSpacing.md)
                    .padding(.bottom, AppSpacing.xl)
                }
            }
            .scrollIndicators(.hidden)
        }
        .onAppear {
            AnalyticsManager.shared.trackScreenView("activity_detail", screenClass: "ActivityView")
            withAnimation(.spring(response: 0.6, dampingFraction: 0.8).delay(0.1)) {
                showContent = true
            }
        }
        .sheet(item: $selectedPerson) { character in
            PersonDetailView(personID: character.id)
                .onDisappear {
                    selectedPerson = nil
                }
        }
    }

    // MARK: - Hero Header

    private var heroHeader: some View {
        ZStack(alignment: .bottomLeading) {
            // Hero Image
            WebImage(url: URL(string: activity.image))
                .onSuccess { image, data, cacheType in
                    print("🎯 ActivityHero: ✅ Loaded '\(activity.title)' - size: \(image.size)")
                }
                .onFailure { error in
                    print("🎯 ActivityHero: ❌ Failed '\(activity.title)' - URL: \(activity.image) - Error: \(error.localizedDescription)")
                }
                .resizable()
                .placeholder {
                    Rectangle()
                        .fill(AppColors.surfaceElevated)
                        .overlay(
                            ProgressView()
                                .tint(AppColors.primary)
                        )
                        .onAppear {
                            print("🎯 ActivityHero: 🔄 Loading '\(activity.title)' from: \(activity.image)")
                        }
                }
                .indicator(.activity)
                .aspectRatio(contentMode: .fill)
                .frame(height: 280)
                .clipped()
                .scaleEffect(headerScale)

            // Gradient Overlay
            LinearGradient(
                colors: [
                    Color.black.opacity(0.0),
                    Color.black.opacity(0.3),
                    Color.black.opacity(0.7)
                ],
                startPoint: .top,
                endPoint: .bottom
            )
            .frame(height: 280)

            // Title Overlay
            VStack(alignment: .leading, spacing: AppSpacing.xs) {
                Text(activity.title)
                    .font(.appTitle)
                    .foregroundColor(.white)
                    .shadow(color: .black.opacity(0.3), radius: 8, x: 0, y: 4)

                if let record = matchingRecord {
                    activityTypeLabel(record: record)
                }
            }
            .padding(AppSpacing.md)
            .padding(.bottom, AppSpacing.sm)
        }
        .frame(height: 280)
        .cornerRadius(AppSpacing.largeCornerRadius, corners: [.bottomLeft, .bottomRight])
        .shadow(color: Color.black.opacity(0.15), radius: 20, x: 0, y: 10)
        .onAppear {
            withAnimation(
                .easeInOut(duration: 4.0)
                .repeatForever(autoreverses: true)
            ) {
                headerScale = 1.05
            }
        }
    }

    // MARK: - Activity Type Label

    private func activityTypeLabel(record: ActivityRecord) -> some View {
        HStack(spacing: 6) {
            Image(systemName: activityIcon(for: record.type))
                .font(.system(size: 12))
            Text(activityTypeText(for: record.type))
                .font(.appCaption)
        }
        .foregroundColor(AppColors.primaryText)
        .padding(.horizontal, 12)
        .padding(.vertical, 6)
        .background(Color.white.opacity(0.2))
        .cornerRadius(AppSpacing.smallCornerRadius)
        .shadow(color: .black.opacity(0.2), radius: 4, x: 0, y: 2)
    }

    // MARK: - Performance Card

    private func performanceCard(record: ActivityRecord) -> some View {
        BaseCard(
            backgroundColor: AppColors.surfaceElevated,
            showShadow: true,
            enableAnimation: false
        ) {
            VStack(spacing: AppSpacing.md) {
                // Header
                HStack {
                    Image(systemName: "chart.line.uptrend.xyaxis")
                        .font(.system(size: 20))
                        .foregroundColor(AppColors.primary)
                    Text("Performance")
                        .font(.appHeadline)
                        .foregroundColor(AppColors.primaryText)
                    Spacer()
                }

                // Job-specific stats
                if let level = record.level {
                    VStack(spacing: AppSpacing.sm) {
                        statRow(
                            label: "Position",
                            value: level.level,
                            icon: "briefcase.fill",
                            color: AppColors.primary
                        )

                        statRow(
                            label: "Salary",
                            value: "$\(level.salary) / month",
                            icon: "dollarsign.circle.fill",
                            color: AppColors.money
                        )

                        // Performance Progress
                        VStack(alignment: .leading, spacing: AppSpacing.xs) {
                            HStack {
                                Image(systemName: "star.fill")
                                    .font(.system(size: 12))
                                    .foregroundColor(AppColors.accent)
                                Text("Performance")
                                    .font(.appBody)
                                    .foregroundColor(AppColors.primaryText)
                                Spacer()
                                Text("\(record.performance)%")
                                    .font(.appBodyBold)
                                    .foregroundColor(AppColors.primaryText)
                            }

                            // Progress Bar
                            GeometryReader { geometry in
                                ZStack(alignment: .leading) {
                                    // Background
                                    RoundedRectangle(cornerRadius: 8)
                                        .fill(AppColors.background)
                                        .frame(height: 12)

                                    // Progress
                                    RoundedRectangle(cornerRadius: 8)
                                        .fill(
                                            LinearGradient(
                                                colors: [AppColors.success, AppColors.energy],
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .frame(width: geometry.size.width * CGFloat(record.performance) / 100.0, height: 12)
                                        .animation(.spring(response: 0.6, dampingFraction: 0.7), value: record.performance)
                                }
                            }
                            .frame(height: 12)
                        }
                    }
                }

                // Education-specific stats
                if let educationRecord = record as? EducationRecord,
                   activity.type == "high_school" || activity.type == "elementary_school" || activity.type == "college" {
                    VStack(spacing: AppSpacing.sm) {
                        statRow(
                            label: "Education Level",
                            value: educationRecord.educationLevel,
                            icon: "graduationcap.fill",
                            color: AppColors.intelligence
                        )

                        let gpa = GPpercentToGPA(GPPercent: Int(educationRecord.GPA.rounded(toPlaces: 1)))
                        statRow(
                            label: "GPA",
                            value: String(format: "%.1f", gpa),
                            icon: "chart.bar.fill",
                            color: AppColors.prestige
                        )

                        // GPA Progress
                        VStack(alignment: .leading, spacing: AppSpacing.xs) {
                            HStack {
                                Image(systemName: "brain.head.profile")
                                    .font(.system(size: 12))
                                    .foregroundColor(AppColors.intelligence)
                                Text("Academic Performance")
                                    .font(.appBody)
                                    .foregroundColor(AppColors.primaryText)
                                Spacer()
                                Text("\(Int(educationRecord.GPA))%")
                                    .font(.appBodyBold)
                                    .foregroundColor(AppColors.primaryText)
                            }

                            // Progress Bar
                            GeometryReader { geometry in
                                ZStack(alignment: .leading) {
                                    RoundedRectangle(cornerRadius: 8)
                                        .fill(AppColors.background)
                                        .frame(height: 12)

                                    RoundedRectangle(cornerRadius: 8)
                                        .fill(
                                            LinearGradient(
                                                colors: [AppColors.intelligence, AppColors.prestige],
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .frame(width: geometry.size.width * CGFloat(educationRecord.GPA) / 100.0, height: 12)
                                        .animation(.spring(response: 0.6, dampingFraction: 0.7), value: educationRecord.GPA)
                                }
                            }
                            .frame(height: 12)
                        }
                    }
                }

                // Focus Display
                if !record.focus.isEmpty {
                    Divider()
                        .background(AppColors.primaryText.opacity(0.2))

                    HStack(spacing: AppSpacing.sm) {
                        Image(systemName: "target")
                            .font(.system(size: 14))
                            .foregroundColor(AppColors.secondary)
                            .frame(width: 14)
                        Text("Current Focus:")
                            .font(.appBody)
                            .foregroundColor(AppColors.secondaryText)
                            .lineLimit(1)
                        Spacer(minLength: AppSpacing.xs)
                        Text(record.focus)
                            .font(.appBodyBold)
                            .foregroundColor(AppColors.primaryText)
                            .lineLimit(1)
                    }
                }
            }
        }
        .opacity(showContent ? 1 : 0)
        .offset(y: showContent ? 0 : 20)
    }

    // MARK: - Stat Row

    private func statRow(label: String, value: String, icon: String, color: Color) -> some View {
        HStack(spacing: AppSpacing.sm) {
            Image(systemName: icon)
                .font(.system(size: 14))
                .foregroundColor(color)
                .frame(width: 24)

            Text(label)
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)
                .lineLimit(1)

            Spacer(minLength: AppSpacing.xs)

            Text(value)
                .font(.appBodyBold)
                .foregroundColor(AppColors.primaryText)
                .lineLimit(1)
        }
    }

    // MARK: - Focus Card

    private var focusCard: some View {
        BaseCard(
            backgroundColor: AppColors.surfaceElevated,
            showShadow: true,
            enableAnimation: false
        ) {
            VStack(alignment: .leading, spacing: AppSpacing.md) {
                // Header
                HStack {
                    Image(systemName: "target")
                        .font(.system(size: 20))
                        .foregroundColor(AppColors.accent)
                    Text("Change Focus")
                        .font(.appHeadline)
                        .foregroundColor(AppColors.primaryText)
                    Spacer()
                }

                // Focus Chips
                FlowLayout(spacing: AppSpacing.sm) {
                    ForEach(webSocketService.player.focuses, id: \.id) { focus in
                        focusChip(focus: focus)
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)
            }
        }
        .opacity(showContent ? 1 : 0)
        .offset(y: showContent ? 0 : 20)
    }

    // MARK: - Focus Chip

    private func focusChip(focus: FocusOption) -> some View {
        let isSelected = matchingRecord?.focus == focus.focus_name

        return Button(action: {
            // Haptic feedback
            let generator = UIImpactFeedbackGenerator(style: .medium)
            generator.impactOccurred()

            webSocketService.sendMessage(message: WebSocketCommands.focusUpdate(
                activityId: activity.id,
                newFocus: focus.focus_name
            ))
            matchingRecord?.focus = focus.focus_name
        }) {
            Text(focus.focus_name)
                .font(.appBody)
                .foregroundColor(isSelected ? .white : AppColors.primaryText)
                .padding(.horizontal, AppSpacing.md)
                .padding(.vertical, AppSpacing.sm)
                .background(
                    isSelected ?
                    LinearGradient(
                        colors: [AppColors.primary, AppColors.accent],
                        startPoint: .leading,
                        endPoint: .trailing
                    ) :
                    LinearGradient(
                        colors: [AppColors.background, AppColors.background],
                        startPoint: .leading,
                        endPoint: .trailing
                    )
                )
                .cornerRadius(AppSpacing.pillCornerRadius)
                .overlay(
                    RoundedRectangle(cornerRadius: AppSpacing.pillCornerRadius)
                        .strokeBorder(
                            isSelected ? Color.clear : AppColors.primaryText.opacity(0.3),
                            lineWidth: 1.5
                        )
                )
                .shadow(
                    color: isSelected ? AppColors.primary.opacity(0.3) : Color.clear,
                    radius: 8,
                    x: 0,
                    y: 4
                )
        }
        .scaleEffect(isSelected ? 1.05 : 1.0)
        .animation(.spring(response: 0.3, dampingFraction: 0.6), value: isSelected)
    }

    // MARK: - People Section

    private var relatedPeople: [Person] {
        webSocketService.player.r.filter { person in
            if (activity.type == "high_school" || activity.type == "elementary_school" || activity.type == "college") {
                return person.relationships.contains("classmate") || person.relationships.contains("teacher")
            } else if activity.type == "job" {
                return person.relationships.contains("coworker") || person.relationships.contains("boss")
            }
            return false
        }.sorted { p1, p2 in
            let p1Priority = p1.relationships.contains("boss") || p1.relationships.contains("teacher")
            let p2Priority = p2.relationships.contains("boss") || p2.relationships.contains("teacher")
            return p1Priority && !p2Priority
        }
    }

    private var peopleSection: some View {
        BaseCard(
            backgroundColor: AppColors.surfaceElevated,
            showShadow: true,
            enableAnimation: false
        ) {
            VStack(alignment: .leading, spacing: AppSpacing.md) {
                // Header
                HStack {
                    Image(systemName: "person.2.fill")
                        .font(.system(size: 20))
                        .foregroundColor(AppColors.secondary)
                    Text(peopleSectionTitle)
                        .font(.appHeadline)
                        .foregroundColor(AppColors.primaryText)
                    Spacer()
                    Text("\(relatedPeople.count)")
                        .font(.appBodyBold)
                        .foregroundColor(AppColors.secondaryText)
                        .padding(.horizontal, 10)
                        .padding(.vertical, 4)
                        .background(AppColors.background)
                        .cornerRadius(8)
                }

                // People Grid
                LazyVGrid(
                    columns: [
                        GridItem(.flexible(), spacing: AppSpacing.sm),
                        GridItem(.flexible(), spacing: AppSpacing.sm)
                    ],
                    spacing: AppSpacing.sm
                ) {
                    ForEach(relatedPeople) { person in
                        personCard(person: person)
                    }
                }
            }
        }
        .opacity(showContent ? 1 : 0)
        .offset(y: showContent ? 0 : 20)
    }

    private var peopleSectionTitle: String {
        if activity.type == "high_school" || activity.type == "elementary_school" || activity.type == "college" {
            return "Classmates & Teachers"
        } else if activity.type == "job" {
            return "Coworkers & Bosses"
        }
        return "People"
    }

    // MARK: - Person Card

    private func personCard(person: Person) -> some View {
        Button(action: {
            // Haptic feedback
            let generator = UIImpactFeedbackGenerator(style: .light)
            generator.impactOccurred()

            retrievePerson(personID: person.id, webSocketService: webSocketService)
            selectedPerson = person
        }) {
            VStack(spacing: AppSpacing.xs) {
                // Avatar
                CharacterAvatar(
                    person: person,
                    size: 50,
                    showBorder: true,
                    borderGradient: [relationshipColor(for: person), relationshipColor(for: person).opacity(0.7)],
                    showGlow: true
                )

                // Name
                Text(person.firstname)
                    .font(.appCaption)
                    .foregroundColor(AppColors.primaryText)
                    .lineLimit(1)

                // Relationship Badge
                Text(primaryRelationship(for: person))
                    .font(.system(size: 10, weight: .medium, design: .rounded))
                    .foregroundColor(AppColors.primaryText)
                    .padding(.horizontal, 8)
                    .padding(.vertical, 3)
                    .background(relationshipColor(for: person).opacity(0.15))
                    .cornerRadius(6)
            }
            .padding(AppSpacing.sm)
            .frame(maxWidth: .infinity)
            .background(AppColors.background)
            .cornerRadius(AppSpacing.cornerRadius)
            .overlay(
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .strokeBorder(
                        AppColors.primaryText.opacity(0.1),
                        lineWidth: 1
                    )
            )
        }
    }

    // MARK: - Action Button

    private func actionButton(record: ActivityRecord) -> some View {
        Button(action: {
            // Haptic feedback
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.warning)

            if record.type == "extracurricular" {
                webSocketService.sendMessage(message: WebSocketCommands.quitExtracurricular(activity.id))
            } else {
                webSocketService.sendMessage(message: WebSocketCommands.quitJob(activity.id))
            }

            // Dismiss sheet
            dismiss()
        }) {
            HStack(spacing: AppSpacing.sm) {
                Image(systemName: quitIcon(for: record.type))
                    .font(.system(size: 16, weight: .semibold))
                Text(quitButtonText(for: record.type))
                    .font(.appBodyBold)
            }
            .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.3), radius: 12, x: 0, y: 6)
        }
        .padding(.top, AppSpacing.sm)
        .opacity(showContent ? 1 : 0)
        .offset(y: showContent ? 0 : 20)
    }

    // MARK: - Helper Functions

    private func activityIcon(for type: String) -> String {
        switch type {
        case "job": return "briefcase.fill"
        case "high_school", "elementary_school", "college": return "graduationcap.fill"
        case "extracurricular": return "star.fill"
        default: return "square.grid.2x2.fill"
        }
    }

    private func activityTypeText(for type: String) -> String {
        switch type {
        case "job": return "Occupation"
        case "high_school": return "High School"
        case "elementary_school": return "Elementary School"
        case "college": return "College"
        case "extracurricular": return "Extracurricular"
        default: return "Activity"
        }
    }

    private func quitIcon(for type: String) -> String {
        switch type {
        case "job": return "door.left.hand.open"
        case "extracurricular": return "xmark.circle.fill"
        default: return "xmark.circle.fill"
        }
    }

    private func quitButtonText(for type: String) -> String {
        switch type {
        case "job": return "Quit Job"
        case "extracurricular": return "Quit Activity"
        default: return "Leave Activity"
        }
    }

    private func relationshipColor(for person: Person) -> Color {
        if person.relationships.contains("boss") || person.relationships.contains("teacher") {
            return AppColors.prestige
        } else if person.relationships.contains("coworker") || person.relationships.contains("classmate") {
            return AppColors.friend
        }
        return AppColors.acquaintance
    }

    private func primaryRelationship(for person: Person) -> String {
        if person.relationships.contains("boss") {
            return "Boss"
        } else if person.relationships.contains("teacher") {
            return "Teacher"
        } else if person.relationships.contains("coworker") {
            return "Coworker"
        } else if person.relationships.contains("classmate") {
            return "Classmate"
        }
        return "Person"
    }
}

// MARK: - Flow Layout
// Note: FlowLayout is defined in Features/Dating/Components/EnhancedProfileCard.swift
