import SwiftUI
import UIKit

struct AIChatPage: View {
    @StateObject private var vm: AIChatViewModel
    @State private var showSessions = false
    @State private var sessions: [ChatSession] = []

    init(context: ChatEntryContext? = nil) {
        let vm = AIChatViewModel()
        if let ctx = context {
            vm.setEntryContext(ctx)
        }
        _vm = StateObject(wrappedValue: vm)
    }

    var body: some View {
        ZStack {
            Color.zxBg0.ignoresSafeArea()
            VStack(spacing: 0) {
                if vm.isCreatingSession {
                    VStack(spacing: 12) {
                        ProgressView().tint(Color.zxPurple)
                        Text("正在准备 AI 助手...").font(.system(size: 14)).foregroundColor(Color.zxF04)
                    }.frame(maxWidth: .infinity, maxHeight: .infinity)
                } else if let error = vm.sessionError {
                    VStack(spacing: 16) {
                        Image(systemName: "exclamationmark.triangle").font(.system(size: 36)).foregroundColor(Color.zxF04)
                        Text(error).font(.system(size: 14)).foregroundColor(Color.zxF04)
                    }.frame(maxWidth: .infinity, maxHeight: .infinity)
                } else {
                    ScrollViewReader { proxy in
                        ScrollView {
                            VStack(spacing: 12) {
                                // Scope indicator
                                if let label = vm.scopeLabel {
                                    HStack(spacing: 6) {
                                        Image(systemName: vm.scopeIcon)
                                            .font(.system(size: 11))
                                        Text(label)
                                            .font(.system(size: 12, weight: .medium))
                                    }
                                    .foregroundColor(Color.zxF03)
                                    .padding(.horizontal, 12).padding(.vertical, 6)
                                    .background(Color.zxFill003)
                                    .clipShape(RoundedRectangle(cornerRadius: 8))
                                    .padding(.top, 4)
                                }

                                ForEach(vm.messages) { m in
                                    MessageCard(message: m, onRegenerate: { Task { vm.send() } })
                                        .id(m.id)
                                        .padding(.horizontal, 20)
                                }
                                if vm.isSending && vm.messages.last?.role == .user {
                                    HStack { ProgressView().tint(Color.zxPurple).padding(); Spacer() }
                                        .padding(.horizontal, 20)
                                }
                            }
                            .padding(.top, 8).padding(.bottom, 100)
                        }
                        .scrollIndicators(.hidden)
                        .onChange(of: vm.messages.count) { _ in scrollToBottom(proxy) }
                        .onChange(of: vm.messages.last?.content) { _ in scrollToBottom(proxy) }
                        .onChange(of: vm.messages.last?.thinkingContent) { _ in scrollToBottom(proxy) }
                    }
                    ZXAIInputBar(text: $vm.inputText, onSend: { vm.send() }).padding(.horizontal, 20).padding(.bottom, 34)
                }
            }
        }
        .navigationBarTitleDisplayMode(.inline).toolbar(.hidden, for: .tabBar)
        .toolbarBackground(.hidden, for: .navigationBar)
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                HStack(spacing: 12) {
                    Button { Task { await vm.createNewSession() } } label: {
                        Image(systemName: "plus.bubble").font(.system(size: 16)).foregroundColor(Color.zxF05)
                    }
                    Button { showSessions = true } label: {
                        Image("icon-list").font(.system(size: 16)).foregroundColor(Color.zxF05)
                    }
                }
            }
        }
        .sheet(isPresented: $showSessions) {
            VStack(spacing: 0) {
                HStack {
                    Text("对话列表").font(.system(size: 16, weight: .semibold)).foregroundColor(Color.zxF0)
                    Spacer()
                    Button {
                        showSessions = false
                        Task { await vm.createNewSession() }
                    } label: {
                        Image(systemName: "plus.bubble").font(.system(size: 18)).foregroundColor(Color.zxF05)
                    }
                }.padding(.horizontal, 20).padding(.top, 16).padding(.bottom, 12)
                if sessions.isEmpty {
                    Text("暂无历史对话").font(.system(size: 14)).foregroundColor(Color.zxF04).padding(.top, 40)
                } else {
                    List {
                        ForEach(sessions) { s in
                            Button {
                                showSessions = false
                                Task { await vm.loadSession(s.id) }
                            } label: {
                                HStack {
                                    VStack(alignment: .leading, spacing: 2) {
                                        Text(s.title ?? "对话").font(.system(size: 14)).foregroundColor(Color.zxF0)
                                        Text(s.updatedAt?.prefix(10).description ?? "").font(.system(size: 11)).foregroundColor(Color.zxF04)
                                    }
                                    Spacer()
                                }.padding(.vertical, 4)
                            }.foregroundColor(.primary)
                            .swipeActions(edge: .trailing, allowsFullSwipe: true) {
                                Button(role: .destructive) {
                                    Task {
                                        do {
                                            try await RagChatService.shared.deleteSession(id: s.id)
                                            sessions.removeAll { $0.id == s.id }
                                        } catch {
                                            // Keep session in list if delete failed
                                        }
                                    }
                                } label: { Label("删除", systemImage: "trash") }
                            }
                        }
                    }
                    .listStyle(.plain)
                    .scrollContentBackground(.hidden)
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity).background(Color.zxBg0)
            .presentationDetents([.medium, .large])
            .task {
                let s: [ChatSession]
                if let filter = vm.sessionListFilter {
                    s = (try? await RagChatService.shared.listSessions(scopeType: filter.scopeType, scopeId: filter.scopeId)) ?? []
                } else {
                    s = (try? await RagChatService.shared.listSessions()) ?? []
                }
                sessions = s
            }
        }
        .task { await vm.load() }
    }

    private func scrollToBottom(_ proxy: ScrollViewProxy) {
        withAnimation {
            proxy.scrollTo(vm.messages.last?.id, anchor: .bottom)
        }
    }
}

// MARK: - Message Card

struct MessageCard: View {
    let message: AIMessage
    let onRegenerate: () -> Void
    @State private var thinkingExpanded = true

    var body: some View {
        let isAI = message.role == .ai
        let hasContent = !message.content.isEmpty
        let hasThinking = !(message.thinkingContent?.isEmpty ?? true)
        let isStreaming = message.isStreaming

        // Don't render empty placeholder bubbles
        if !hasContent && !hasThinking { EmptyView() }
        else {
            VStack(alignment: isAI ? .leading : .trailing, spacing: 0) {
                // Thinking process (inside card, at top)
                if hasThinking {
                    ThinkingSection(text: message.thinkingContent ?? "", isExpanded: $thinkingExpanded, isStreaming: isStreaming)
                    if hasContent { Divider().background(Color.zxF03).padding(.horizontal, 8) }
                }

                // Content
                if hasContent {
                    Text(message.content).zxFontScaled(size: 14)
                        .foregroundColor(isAI ? Color.zxF007 : .white)
                        .padding(12)
                }

                // Actions (AI only, after streaming done)
                if isAI && !isStreaming && hasContent {
                    HStack(spacing: 16) {
                        Button { UIPasteboard.general.string = message.content } label: {
                            Label("复制", systemImage: "doc.on.doc").font(.system(size: 12)).foregroundColor(Color.zxF04)
                        }
                        Button { onRegenerate() } label: {
                            Label("重新生成", systemImage: "arrow.clockwise").font(.system(size: 12)).foregroundColor(Color.zxF04)
                        }
                        Spacer()
                    }.padding(.horizontal, 12).padding(.bottom, 8)
                }

                // Loading indicator
                if isAI && isStreaming && !hasContent && hasThinking {
                    HStack { ProgressView().tint(Color.zxPurple).scaleEffect(0.8); Spacer() }
                        .padding(.horizontal, 12).padding(.bottom, 8)
                }
            }
            .frame(maxWidth: .infinity, alignment: isAI ? .leading : .trailing)
            .background(isAI ? AnyView(Color.zxFill004) : AnyView(ZXGradient.brandPurple))
            .clipShape(RoundedRectangle(cornerRadius: 14))
        }
    }
}

// MARK: - Thinking Section

struct ThinkingSection: View {
    let text: String
    @Binding var isExpanded: Bool
    let isStreaming: Bool

    var body: some View {
        VStack(spacing: 0) {
            // Collapse toggle
            Button {
                withAnimation(.easeInOut(duration: 0.2)) { isExpanded.toggle() }
            } label: {
                HStack(spacing: 4) {
                    Text(isExpanded ? "思考中..." : "思考完成")
                        .font(.system(size: 11)).foregroundColor(Color.zxF03)
                    if isStreaming { ProgressView().scaleEffect(0.5).tint(Color.zxF03) }
                    Spacer()
                    Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
                        .font(.system(size: 8)).foregroundColor(Color.zxF03)
                }
                .padding(.horizontal, 12).padding(.vertical, 6)
            }

            // Thinking content
            if isExpanded {
                Text(text)
                    .font(.system(size: 12)).foregroundColor(Color.zxF03)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding(.horizontal, 12).padding(.bottom, 8)
            }
        }
        .background(Color.zxFill003)
    }

}
