import SwiftUI
import CoreSpotlight

struct SpotlightDebugView: View {
    @EnvironmentObject var linkViewModel: LinkViewModel
    @State private var indexedItemsCount: Int = 0
    @State private var isSpotlightAvailable: Bool = false
    @State private var showingAlert = false
    @State private var alertMessage = ""

    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                Section {
                    Text("Spotlight Search Status")
                        .font(.title2)
                        .fontWeight(.bold)

                    VStack(alignment: .leading, spacing: 10) {
                        HStack {
                            Text("Spotlight Available:")
                            Spacer()
                            Text(isSpotlightAvailable ? "✅ Yes" : "❌ No")
                                .foregroundColor(isSpotlightAvailable ? .green : .red)
                        }

                        HStack {
                            Text("Indexed Items:")
                            Spacer()
                            Text("\(indexedItemsCount)")
                                .fontWeight(.semibold)
                        }

                        HStack {
                            Text("Total Links:")
                            Spacer()
                            Text("\(linkViewModel.links.count)")
                                .fontWeight(.semibold)
                        }
                    }
                    .padding()
                    .background(Color(.systemGray6))
                    .cornerRadius(10)
                }

                Section {
                    VStack(spacing: 15) {
                        Button("Refresh Spotlight Index") {
                            refreshSpotlightIndex()
                        }
                        .foregroundColor(.blue)

                        Button("Check Index Status") {
                            checkIndexStatus()
                        }
                        .foregroundColor(.blue)

                        Button("Clear All Indexed Items") {
                            clearSpotlightIndex()
                        }
                        .foregroundColor(.red)
                    }
                }

                Section {
                    VStack(alignment: .leading, spacing: 10) {
                        Text("Instructions:")
                            .font(.headline)

                        Text("1. Tap 'Refresh Spotlight Index' to index your links")
                        Text("2. Go to iOS home screen")
                        Text("3. Pull down to open Spotlight search")
                        Text("4. Type 'heygo g' to test search")
                        Text("5. Your links should appear in results")
                    }
                    .padding()
                    .background(Color(.systemBlue).opacity(0.1))
                    .cornerRadius(10)
                }

                Spacer()
            }
            .padding()
            .navigationTitle("Spotlight Debug")
            .onAppear {
                checkSpotlightAvailability()
                checkIndexStatus()
            }
            .alert("Spotlight Debug", isPresented: $showingAlert) {
                Button("OK") { }
            } message: {
                Text(alertMessage)
            }
        }
    }

    private func checkSpotlightAvailability() {
        isSpotlightAvailable = SpotlightSearchManager.shared.isSpotlightAvailable()
    }

    private func checkIndexStatus() {
        linkViewModel.checkSpotlightStatus { count in
            DispatchQueue.main.async {
                self.indexedItemsCount = count
            }
        }
    }

    private func refreshSpotlightIndex() {
        linkViewModel.refreshSpotlightIndex()
        alertMessage = "Spotlight index refresh initiated. Check status in a few seconds."
        showingAlert = true

        // Check status after a delay
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            checkIndexStatus()
        }
    }

    private func clearSpotlightIndex() {
        SpotlightSearchManager.shared.clearAllIndexedLinks()
        alertMessage = "All indexed items cleared. You can refresh the index to re-add them."
        showingAlert = true

        // Update count after clearing
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            indexedItemsCount = 0
        }
    }
}

#Preview {
    SpotlightDebugView()
        .environmentObject(LinkViewModel())
}
