import SwiftUI
import PhotosUI

struct AssistantChatView: View {
    @State private var vm = AssistantViewModel()
    var onFoodAdded: (() -> Void)?

    var body: some View {
        VStack(spacing: 0) {
            // Messages
            ScrollViewReader { proxy in
                ScrollView {
                    LazyVStack(spacing: 8) {
                        // Welcome state when no messages
                        if vm.messages.isEmpty {
                            VStack(spacing: 16) {
                                Spacer(minLength: 60)
                                Image(systemName: "sparkles")
                                    .font(.system(size: 40))
                                    .foregroundStyle(Color.accentWarm.opacity(0.4))
                                Text("What did you eat?")
                                    .font(.title3.weight(.semibold))
                                    .foregroundStyle(Color.textPrimary)
                                Text("Describe your food naturally.\n\"2 eggs and toast for breakfast\"\nor snap a photo of your meal.")
                                    .font(.subheadline)
                                    .foregroundStyle(Color.textSecondary)
                                    .multilineTextAlignment(.center)
                                    .lineSpacing(4)
                                Spacer(minLength: 60)
                            }
                            .frame(maxWidth: .infinity)
                            .padding(.horizontal, 32)
                        }

                        ForEach(vm.messages) { message in
                            chatBubble(message)
                                .id(message.id)
                        }

                        // Draft card
                        if let draft = vm.currentDraft, !vm.applied {
                            draftCard(draft)
                        }

                        // Multiple drafts
                        if vm.currentDrafts.count > 1 && !vm.applied {
                            multipleDraftsCard
                        }

                        if vm.isLoading {
                            HStack {
                                ProgressView()
                                    .controlSize(.small)
                                Text("Thinking...")
                                    .font(.caption)
                                    .foregroundStyle(Color.textTertiary)
                                Spacer()
                            }
                            .padding(.horizontal)
                        }

                        if let error = vm.error {
                            Text(error)
                                .font(.caption)
                                .foregroundStyle(.red)
                                .padding(.horizontal)
                        }
                    }
                    .padding(.vertical, 8)
                }
                .onTapGesture {
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                }
                .onChange(of: vm.messages.count) {
                    if let last = vm.messages.last {
                        withAnimation {
                            proxy.scrollTo(last.id, anchor: .bottom)
                        }
                    }
                }
            }

            Divider()

            // Input bar
            HStack(spacing: 10) {
                PhotosPicker(selection: $vm.selectedPhoto, matching: .images) {
                    Image(systemName: "camera.fill")
                        .font(.title3)
                        .foregroundStyle(Color.accentWarm)
                }

                TextField("Describe your food...", text: $vm.inputText)
                    .textFieldStyle(.plain)
                    .onSubmit {
                        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                        Task { await vm.send() }
                    }

                Button {
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                    Task { await vm.send() }
                } label: {
                    Image(systemName: "arrow.up.circle.fill")
                        .font(.title2)
                        .foregroundStyle(
                            vm.inputText.trimmingCharacters(in: .whitespaces).isEmpty
                                ? Color.textTertiary
                                : Color.accentWarm
                        )
                }
                .disabled(vm.inputText.trimmingCharacters(in: .whitespaces).isEmpty || vm.isLoading)
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 10)
            .background(Color.surfaceCard)
        }
        .background(Color.canvas)
        .onChange(of: vm.selectedPhoto) {
            Task { await vm.handlePhotoSelection() }
        }
        .onChange(of: vm.applied) {
            if vm.applied {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    onFoodAdded?()
                }
            }
        }
    }

    // MARK: - Chat Bubble

    private func chatBubble(_ message: ChatMessage) -> some View {
        HStack {
            if message.role == "user" { Spacer(minLength: 60) }

            Text(message.content)
                .font(.subheadline)
                .foregroundStyle(message.role == "user" ? .white : Color.textPrimary)
                .padding(.horizontal, 14)
                .padding(.vertical, 10)
                .background(
                    message.role == "user"
                        ? Color.accentWarm
                        : Color.surfaceSheet
                )
                .clipShape(RoundedRectangle(cornerRadius: 16))

            if message.role == "assistant" { Spacer(minLength: 60) }
        }
        .padding(.horizontal, 12)
    }

    // MARK: - Draft Card (Editable)

    private func draftCard(_ draft: FitnessDraft) -> some View {
        EditableDraftCard(vm: vm)
    }

    private var multipleDraftsCard: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Image(systemName: "doc.on.doc.fill")
                    .foregroundStyle(Color.accentWarm)
                Text("\(vm.currentDrafts.count) Items")
                    .font(.subheadline.weight(.semibold))
                    .foregroundStyle(Color.textPrimary)
            }

            ForEach(vm.currentDrafts) { draft in
                HStack {
                    Text(draft.foodName)
                        .font(.caption.weight(.medium))
                        .foregroundStyle(Color.textPrimary)
                    Spacer()
                    Text("\(Int(draft.calories)) kcal")
                        .font(.caption)
                        .foregroundStyle(Color.textSecondary)
                }
            }

            let totalCals = vm.currentDrafts.reduce(0.0) { $0 + $1.calories }
            Text("Total: \(Int(totalCals)) kcal")
                .font(.caption.weight(.semibold))
                .foregroundStyle(Color.textSecondary)

            Button {
                Task { await vm.applyAllDrafts() }
            } label: {
                Text("Add all")
                    .font(.subheadline.weight(.semibold))
                    .foregroundStyle(.white)
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 10)
                    .background(Color.emerald)
                    .clipShape(RoundedRectangle(cornerRadius: 10))
            }
        }
        .padding()
        .background(Color.surfaceCard)
        .clipShape(RoundedRectangle(cornerRadius: 14))
        .shadow(color: .black.opacity(0.06), radius: 6, y: 2)
        .padding(.horizontal, 12)
    }

    private func miniStat(_ label: String, value: Int) -> some View {
        VStack(spacing: 2) {
            Text("\(value)")
                .font(.caption.weight(.bold).monospacedDigit())
                .foregroundStyle(Color.textPrimary)
            Text(label)
                .font(.system(size: 9).weight(.medium))
                .foregroundStyle(Color.textTertiary)
        }
    }
}
