import SwiftUI
import PhotosUI

struct FeedbackButton: View {
    @State private var showSheet = false

    var body: some View {
        Button { showSheet = true } label: {
            Image(systemName: "exclamationmark.bubble.fill")
                .font(.system(size: 14))
                .foregroundStyle(Color.textTertiary)
                .frame(width: 32, height: 32)
                .background(Color.surfaceCard.opacity(0.8))
                .clipShape(Circle())
                .shadow(color: .black.opacity(0.08), radius: 4, y: 2)
        }
        .sheet(isPresented: $showSheet) {
            FeedbackSheet()
                .presentationDetents([.large, .medium])
        }
    }
}

struct FeedbackSheet: View {
    @Environment(\.dismiss) private var dismiss
    @State private var text = ""
    @State private var isSending = false
    @State private var sent = false
    @State private var error: String?
    @State private var selectedPhotos: [PhotosPickerItem] = []
    @State private var photoPreviews: [(Data, UIImage)] = []

    var body: some View {
        VStack(spacing: 16) {
            Capsule()
                .fill(Color.textTertiary.opacity(0.3))
                .frame(width: 36, height: 5)
                .padding(.top, 8)

            Text("Feedback")
                .font(.headline)
                .foregroundStyle(Color.textPrimary)

            Text("Bug report, feature request, or anything else")
                .font(.caption)
                .foregroundStyle(Color.textTertiary)

            if sent {
                VStack(spacing: 12) {
                    Image(systemName: "checkmark.circle.fill")
                        .font(.system(size: 44))
                        .foregroundStyle(Color.emerald)
                    Text("Sent! We'll look into it.")
                        .font(.subheadline.weight(.medium))
                        .foregroundStyle(Color.textPrimary)
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            } else {
                TextEditor(text: $text)
                    .font(.body)
                    .scrollContentBackground(.hidden)
                    .padding(12)
                    .background(Color.canvas)
                    .clipShape(RoundedRectangle(cornerRadius: 12))
                    .overlay(
                        RoundedRectangle(cornerRadius: 12)
                            .stroke(Color.textTertiary.opacity(0.2), lineWidth: 1)
                    )

                // Photo attachments
                VStack(alignment: .leading, spacing: 8) {
                    PhotosPicker(
                        selection: $selectedPhotos,
                        maxSelectionCount: 5,
                        matching: .images
                    ) {
                        HStack(spacing: 6) {
                            Image(systemName: "camera.fill")
                                .font(.caption)
                            Text(photoPreviews.isEmpty ? "Add screenshots" : "Add more")
                                .font(.caption.weight(.medium))
                        }
                        .foregroundStyle(Color.accentWarm)
                        .padding(.horizontal, 12)
                        .padding(.vertical, 8)
                        .background(Color.accentWarm.opacity(0.1))
                        .clipShape(Capsule())
                    }

                    if !photoPreviews.isEmpty {
                        ScrollView(.horizontal, showsIndicators: false) {
                            HStack(spacing: 8) {
                                ForEach(Array(photoPreviews.enumerated()), id: \.offset) { index, item in
                                    ZStack(alignment: .topTrailing) {
                                        Image(uiImage: item.1)
                                            .resizable()
                                            .scaledToFill()
                                            .frame(width: 60, height: 60)
                                            .clipShape(RoundedRectangle(cornerRadius: 8))

                                        Button {
                                            photoPreviews.remove(at: index)
                                            if index < selectedPhotos.count {
                                                selectedPhotos.remove(at: index)
                                            }
                                        } label: {
                                            Image(systemName: "xmark.circle.fill")
                                                .font(.system(size: 16))
                                                .foregroundStyle(.white)
                                                .background(Circle().fill(.black.opacity(0.5)))
                                        }
                                        .offset(x: 4, y: -4)
                                    }
                                }
                            }
                        }
                    }
                }

                if let error {
                    Text(error)
                        .font(.caption)
                        .foregroundStyle(.red)
                }

                Button {
                    sendFeedback()
                } label: {
                    if isSending {
                        ProgressView().tint(.white)
                    } else {
                        Text("Send")
                            .font(.headline)
                    }
                }
                .frame(maxWidth: .infinity)
                .frame(height: 48)
                .background(text.trimmingCharacters(in: .whitespaces).isEmpty ? Color.textTertiary : Color.accentWarm)
                .foregroundStyle(.white)
                .clipShape(RoundedRectangle(cornerRadius: 12))
                .disabled(text.trimmingCharacters(in: .whitespaces).isEmpty || isSending)
            }
        }
        .padding()
        .background(Color.surfaceCard)
        .onChange(of: selectedPhotos) {
            Task {
                var newPreviews: [(Data, UIImage)] = []
                for item in selectedPhotos {
                    if let data = try? await item.loadTransferable(type: Data.self),
                       let image = UIImage(data: data) {
                        newPreviews.append((data, image))
                    }
                }
                photoPreviews = newPreviews
            }
        }
    }

    private func sendFeedback() {
        guard !isSending else { return }
        isSending = true
        error = nil

        Task { @MainActor in
            do {
                var body: [String: Any] = [
                    "text": text.trimmingCharacters(in: .whitespaces),
                    "source": "ios"
                ]
                if !photoPreviews.isEmpty {
                    let images = photoPreviews.map { $0.0.base64EncodedString() }
                    body["images"] = images
                }
                let jsonData = try JSONSerialization.data(withJSONObject: body)
                let data = try await APIClient.shared.rawPost(path: "/api/feedback", data: jsonData)

                let respBody = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
                if respBody?["ok"] as? Bool == true {
                    withAnimation { sent = true }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        dismiss()
                    }
                } else {
                    error = (respBody?["error"] as? String) ?? "Failed to send"
                }
            } catch {
                self.error = error.localizedDescription
            }
            isSending = false
        }
    }
}
