//
//  NPCProfileView.swift
//  lichunWebsocket
//
//  Unified NPC profile view with header and accordion sections
//

import SwiftUI

struct NPCProfileView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @EnvironmentObject var playerViewModel: PlayerViewModel
    @Environment(\.presentationMode) var presentationMode

    var personID: String

    @State private var character: Person?
    @State private var expandedSection: ProfileSection? = .actions
    @State private var showChatFullScreen = false
    @State private var showInteractionsSheet = false

    var body: some View {
        ZStack {
            // Background
            LinearGradient(
                colors: [
                    AppColors.background,
                    AppColors.background.lighter(by: 0.03)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .edgesIgnoringSafeArea(.all)

            if let character = character {
                ScrollView {
                    VStack(spacing: AppSpacing.lg) {
                        // Profile Header (Quick Glance)
                        ProfileHeader(person: character)

                        // Accordion Sections
                        VStack(spacing: AppSpacing.sm) {
                            // Actions Section
                            AccordionSection(
                                title: ProfileSection.actions.rawValue,
                                icon: ProfileSection.actions.icon,
                                isExpanded: sectionBinding(for: .actions)
                            ) {
                                ActionsSection(person: character) { action in
                                    handleAction(action, for: character)
                                }
                            }

                            // Personality Section
                            AccordionSection(
                                title: ProfileSection.personality.rawValue,
                                icon: ProfileSection.personality.icon,
                                isExpanded: sectionBinding(for: .personality)
                            ) {
                                PersonalitySection(person: character)
                            }

                            // Relationship Section
                            AccordionSection(
                                title: ProfileSection.relationship.rawValue,
                                icon: ProfileSection.relationship.icon,
                                isExpanded: sectionBinding(for: .relationship)
                            ) {
                                RelationshipSection(person: character) {
                                    showChatFullScreen = true
                                }
                            }

                            // Life Story Section
                            AccordionSection(
                                title: ProfileSection.lifeStory.rawValue,
                                icon: ProfileSection.lifeStory.icon,
                                isExpanded: sectionBinding(for: .lifeStory)
                            ) {
                                LifeStorySection(
                                    person: character,
                                    currentHour: webSocketService.player.hourOfDay
                                )
                            }

                            // Stats & Health Section
                            AccordionSection(
                                title: ProfileSection.stats.rawValue,
                                icon: ProfileSection.stats.icon,
                                isExpanded: sectionBinding(for: .stats)
                            ) {
                                StatsHealthSection(person: character)
                            }

                            // Items Section
                            AccordionSection(
                                title: ProfileSection.items.rawValue,
                                icon: ProfileSection.items.icon,
                                isExpanded: sectionBinding(for: .items)
                            ) {
                                ItemsSection(person: character)
                            }
                        }
                        .padding(.horizontal, AppSpacing.md)

                        // Bottom spacer
                        Spacer()
                            .frame(height: AppSpacing.xxl)
                    }
                }
            } else {
                // Loading state
                VStack(spacing: AppSpacing.md) {
                    ProgressView()
                        .progressViewStyle(CircularProgressViewStyle(tint: AppColors.primary))
                        .scaleEffect(1.5)

                    Text("Loading profile...")
                        .font(.appBody)
                        .foregroundColor(AppColors.secondaryText)
                }
            }
        }
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Menu {
                    Button(action: {
                        showInteractionsSheet = true
                    }) {
                        Label("Start Interaction", systemImage: "bubble.left.and.bubble.right")
                    }

                    Button(action: {
                        showChatFullScreen = true
                    }) {
                        Label("View Chat History", systemImage: "message")
                    }
                } label: {
                    Image(systemName: "ellipsis.circle")
                        .font(.system(size: 18, weight: .semibold))
                        .foregroundColor(AppColors.primary)
                }
            }
        }
        .onAppear {
            loadCharacter()
        }
        .onChange(of: webSocketService.personReceived) { newValue in
            if newValue {
                loadCharacter()
            }
        }
        .sheet(isPresented: $showInteractionsSheet) {
            InteractionsSheet(
                character: character,
                webSocketService: webSocketService,
                onStartChat: { conversation in
                    if let char = character, conversation.fname != "chat" {
                        let convEvent: [String: Any] = [
                            "conversationEvent": "init",
                            "characterID": char.id,
                            "cType": conversation.fname
                        ]
                        let message: [String: Any] = [
                            "type": "conversation",
                            "message": convEvent
                        ]
                        webSocketService.sendMessage(message: message)
                    }
                    showInteractionsSheet = false
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                        showChatFullScreen = true
                    }
                },
                onDismiss: {
                    showInteractionsSheet = false
                }
            )
            .presentationDetents([.medium])
            .presentationDragIndicator(.visible)
        }
        .fullScreenCover(isPresented: $showChatFullScreen) {
            ChatView(characterID: personID)
                .environmentObject(webSocketService)
        }
    }

    // MARK: - Helper Methods

    private func loadCharacter() {
        if let index = webSocketService.player.r.firstIndex(where: { $0.id == personID }) {
            character = webSocketService.player.r[index]
        } else {
            // Request character data from server
            playerViewModel.retrievePerson(personID: personID)
        }
    }

    private func sectionBinding(for section: ProfileSection) -> Binding<Bool> {
        Binding(
            get: { expandedSection == section },
            set: { isExpanded in
                withAnimation(.spring(response: 0.35, dampingFraction: 0.75)) {
                    expandedSection = isExpanded ? section : nil
                }
            }
        )
    }

    private func handleAction(_ action: ActionItem, for character: Person) {
        switch action.id {
        // Chat action - just open chat view
        case "chat":
            showChatFullScreen = true

        // Conversation actions - use correct backend cTypes
        case "flatter", "checkIn", "askAboutDay", "activity", "studySession":
            let convEvent: [String: Any] = [
                "conversationEvent": "init",
                "characterID": character.id,
                "cType": action.id
            ]
            let message: [String: Any] = [
                "type": "conversation",
                "message": convEvent
            ]
            webSocketService.sendMessage(message: message)
            showChatFullScreen = true

        // Gift action - backend expects just the partner ID as message
        case "partnerGift":
            webSocketService.sendMessage(message: WebSocketCommands.partnerGift(partnerId: character.id))

        case "romance":
            webSocketService.sendMessage(message: WebSocketCommands.romance(partnerId: character.id))

        case "Movie Night at Home", "Picnic in the Park", "Fine Dining Experience",
             "Hiking Adventure", "Beach Day", "Visit a Museum or Art Gallery",
             "Cooking Class Together", "Amusement Park Day", "Attend a Concert or Show",
             "Spa Day for Relaxation":
            webSocketService.sendMessage(message: WebSocketCommands.dateNight(activityName: action.id))

        default:
            print("Unknown action: \(action.id)")
        }
    }
}

// MARK: - Interactions Sheet

private struct InteractionsSheet: View {
    let character: Person?
    let webSocketService: WebSocketService
    let onStartChat: (ConversationClass) -> Void
    let onDismiss: () -> Void

    var body: some View {
        NavigationView {
            VStack(spacing: AppSpacing.lg) {
                if let char = character {
                    let conversations = char.availableConversations.isEmpty
                        ? [ConversationClass(fname: "chat", button: "💬 Chat")]
                        : char.availableConversations

                    Text("Choose an interaction with \(char.firstname)")
                        .font(.appBody)
                        .foregroundColor(AppColors.secondaryText)
                        .padding(.top, AppSpacing.md)

                    ForEach(conversations, id: \.button) { conversation in
                        Button(action: {
                            onStartChat(conversation)
                        }) {
                            HStack {
                                Text(conversation.button)
                                    .font(.appBodyBold)
                                    .foregroundColor(AppColors.primaryText)
                                Spacer()
                                Image(systemName: "chevron.right")
                                    .font(.system(size: 14, weight: .semibold))
                                    .foregroundColor(AppColors.secondaryText)
                            }
                            .padding(AppSpacing.md)
                            .background(AppColors.surfaceElevated)
                            .cornerRadius(12)
                        }
                    }

                    Spacer()
                }
            }
            .padding(.horizontal, AppSpacing.lg)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(AppColors.background)
            .navigationTitle("Interactions")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Close") {
                        onDismiss()
                    }
                }
            }
        }
    }
}

// MARK: - Preview
// Preview removed - requires backend connection for WebSocketService initialization
