import SwiftUI

struct FoodSearchView: View {
    var isSheet: Bool = false
    var onFoodAdded: (() -> Void)?
    @State private var vm = FoodSearchViewModel()
    @State private var selectedFood: Food?

    var body: some View {
        VStack(spacing: 0) {
            // Search bar
            HStack {
                Image(systemName: "magnifyingglass")
                    .foregroundStyle(Color.textTertiary)
                TextField("Search foods...", text: $vm.searchText)
                    .textFieldStyle(.plain)
                    .autocorrectionDisabled()
                if !vm.searchText.isEmpty {
                    Button {
                        vm.searchText = ""
                        vm.searchResults = []
                    } label: {
                        Image(systemName: "xmark.circle.fill")
                            .foregroundStyle(Color.textTertiary)
                    }
                }
            }
            .padding(12)
            .background(Color.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: 10))
            .padding(.horizontal)
            .padding(.top, 8)

            if vm.isLoadingInitial {
                LoadingView()
            } else if !vm.searchText.isEmpty {
                // Search results
                searchResultsList
            } else {
                // Recent + All
                defaultList
            }
        }
        .background(Color.canvas)
        .task {
            await vm.loadInitial()
        }
        .onChange(of: vm.searchText) {
            vm.search()
        }
        .sheet(item: $selectedFood) { food in
            AddFoodSheet(food: food, onFoodAdded: onFoodAdded)
        }
    }

    private var searchResultsList: some View {
        ScrollView {
            LazyVStack(spacing: 0) {
                if vm.isSearching {
                    ProgressView()
                        .padding()
                } else if vm.searchResults.isEmpty {
                    EmptyStateView(
                        icon: "magnifyingglass",
                        title: "No results",
                        subtitle: "Try a different search term"
                    )
                } else {
                    ForEach(vm.searchResults) { food in
                        foodRow(food)
                    }
                }
            }
        }
    }

    private var defaultList: some View {
        ScrollView {
            LazyVStack(alignment: .leading, spacing: 0) {
                if !vm.recentFoods.isEmpty {
                    sectionHeader("Recent")
                    ForEach(vm.recentFoods) { recent in
                        recentFoodRow(recent)
                    }
                }

                if !vm.allFoods.isEmpty {
                    sectionHeader("All Foods")
                    ForEach(vm.allFoods) { food in
                        foodRow(food)
                    }
                }
            }
        }
    }

    private func sectionHeader(_ title: String) -> some View {
        Text(title)
            .font(.caption.weight(.semibold))
            .foregroundStyle(Color.textTertiary)
            .textCase(.uppercase)
            .padding(.horizontal, 20)
            .padding(.top, 16)
            .padding(.bottom, 4)
    }

    private func foodRow(_ food: Food) -> some View {
        Button {
            selectedFood = food
        } label: {
            HStack {
                VStack(alignment: .leading, spacing: 2) {
                    Text(food.name)
                        .font(.subheadline.weight(.medium))
                        .foregroundStyle(Color.textPrimary)
                        .lineLimit(1)
                    if let brand = food.brand, !brand.isEmpty {
                        Text(brand)
                            .font(.caption)
                            .foregroundStyle(Color.textTertiary)
                    }
                }
                Spacer()
                Text("\(Int(food.caloriesPerBase)) kcal/\(food.baseUnit)")
                    .font(.caption.weight(.medium))
                    .foregroundStyle(Color.textSecondary)
            }
            .padding(.horizontal, 20)
            .padding(.vertical, 10)
        }
    }

    private func recentFoodRow(_ recent: RecentFood) -> some View {
        Button {
            // Navigate to add sheet by loading the full food
            Task {
                do {
                    let food = try await FitnessAPI().getFood(id: recent.foodId)
                    selectedFood = food
                } catch {
                    // Silently fail
                }
            }
        } label: {
            HStack {
                VStack(alignment: .leading, spacing: 2) {
                    Text(recent.name)
                        .font(.subheadline.weight(.medium))
                        .foregroundStyle(Color.textPrimary)
                        .lineLimit(1)
                }
                Spacer()
                Text("\(Int(recent.caloriesPerBase)) kcal")
                    .font(.caption.weight(.medium))
                    .foregroundStyle(Color.textSecondary)
            }
            .padding(.horizontal, 20)
            .padding(.vertical, 10)
        }
    }
}
