import SwiftUI

struct FoodSearchView: View {
    let date: String
    let onFoodAdded: () -> Void

    @Environment(\.dismiss) private var dismiss
    @State private var viewModel = FoodSearchViewModel()
    @FocusState private var searchFocused: Bool

    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                // Search bar
                searchBar

                // Content
                if viewModel.isSearching || viewModel.isLoadingRecent {
                    LoadingView(message: viewModel.isSearching ? "Searching..." : "Loading recent...")
                } else if viewModel.displayedFoods.isEmpty && !viewModel.isShowingRecent {
                    EmptyStateView(
                        icon: "magnifyingglass",
                        title: "No results",
                        subtitle: "Try a different search term"
                    )
                } else {
                    foodList
                }
            }
            .background(Color.canvas)
            .navigationTitle("Add Food")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button("Cancel") {
                        dismiss()
                    }
                    .foregroundStyle(Color.text3)
                }
            }
            .sheet(isPresented: $viewModel.showAddSheet) {
                if let food = viewModel.selectedFood {
                    AddFoodSheet(
                        food: food,
                        quantity: $viewModel.addQuantity,
                        mealType: $viewModel.addMealType,
                        isAdding: viewModel.isAddingFood
                    ) {
                        Task {
                            await viewModel.addFood(date: date) {
                                onFoodAdded()
                                dismiss()
                            }
                        }
                    }
                    .presentationDetents([.medium])
                }
            }
            .task {
                await viewModel.loadRecent()
                searchFocused = true
            }
        }
    }

    private var searchBar: some View {
        HStack(spacing: 10) {
            Image(systemName: "magnifyingglass")
                .foregroundStyle(Color.text4)

            TextField("Search foods...", text: $viewModel.searchText)
                .textFieldStyle(.plain)
                .autocorrectionDisabled()
                .textInputAutocapitalization(.never)
                .focused($searchFocused)
                .onSubmit {
                    viewModel.search()
                }
                .onChange(of: viewModel.searchText) {
                    viewModel.search()
                }

            if !viewModel.searchText.isEmpty {
                Button {
                    viewModel.searchText = ""
                    viewModel.searchResults = []
                } label: {
                    Image(systemName: "xmark.circle.fill")
                        .foregroundStyle(Color.text4)
                }
            }
        }
        .padding(12)
        .background(Color.surface)
        .clipShape(RoundedRectangle(cornerRadius: 12))
        .padding(.horizontal, 16)
        .padding(.vertical, 8)
    }

    private var foodList: some View {
        ScrollView {
            LazyVStack(spacing: 0) {
                if viewModel.isShowingRecent && !viewModel.recentFoods.isEmpty {
                    sectionHeader("Recent Foods")
                }

                ForEach(viewModel.displayedFoods) { food in
                    FoodItemRow(food: food) {
                        viewModel.selectFood(food)
                    }
                    Divider()
                        .padding(.leading, 60)
                }
            }
        }
    }

    private func sectionHeader(_ title: String) -> some View {
        Text(title)
            .font(.caption.weight(.semibold))
            .foregroundStyle(Color.text4)
            .textCase(.uppercase)
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.horizontal, 16)
            .padding(.top, 16)
            .padding(.bottom, 8)
    }
}

struct FoodItemRow: View {
    let food: FoodItem
    let onTap: () -> Void

    var body: some View {
        Button(action: onTap) {
            HStack(spacing: 12) {
                // Icon
                ZStack {
                    RoundedRectangle(cornerRadius: 10)
                        .fill(Color.accentWarmBg)
                        .frame(width: 40, height: 40)

                    if let imageUrl = food.imageUrl, !imageUrl.isEmpty {
                        AsyncImage(url: URL(string: imageUrl)) { image in
                            image
                                .resizable()
                                .scaledToFill()
                                .frame(width: 40, height: 40)
                                .clipShape(RoundedRectangle(cornerRadius: 10))
                        } placeholder: {
                            Image(systemName: "fork.knife")
                                .font(.caption)
                                .foregroundStyle(Color.accentWarm)
                        }
                    } else {
                        Image(systemName: "fork.knife")
                            .font(.caption)
                            .foregroundStyle(Color.accentWarm)
                    }
                }

                // Info
                VStack(alignment: .leading, spacing: 2) {
                    Text(food.name)
                        .font(.subheadline.weight(.medium))
                        .foregroundStyle(Color.text1)
                        .lineLimit(1)

                    Text(food.displayInfo)
                        .font(.caption)
                        .foregroundStyle(Color.text3)
                        .lineLimit(1)
                }

                Spacer()

                // Calories
                VStack(alignment: .trailing, spacing: 2) {
                    Text("\(Int(food.caloriesPerBase))")
                        .font(.subheadline.weight(.bold))
                        .foregroundStyle(Color.text1)

                    Text("kcal")
                        .font(.caption2)
                        .foregroundStyle(Color.text4)
                }

                Image(systemName: "chevron.right")
                    .font(.caption2.weight(.semibold))
                    .foregroundStyle(Color.text4)
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 10)
            .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
    }
}
