import Foundation

@MainActor @Observable
final class FoodSearchViewModel {
    var searchText = ""
    var searchResults: [FoodItem] = []
    var recentFoods: [FoodItem] = []
    var isSearching = false
    var isLoadingRecent = false
    var errorMessage: String?

    // Add food sheet state
    var selectedFood: FoodItem?
    var showAddSheet = false
    var addQuantity: Double = 1
    var addMealType: MealType = .guess()
    var isAddingFood = false

    private let repo = FitnessRepository.shared
    private var searchTask: Task<Void, Never>?

    var displayedFoods: [FoodItem] {
        if searchText.trimmingCharacters(in: .whitespaces).isEmpty {
            return recentFoods
        }
        return searchResults
    }

    var isShowingRecent: Bool {
        searchText.trimmingCharacters(in: .whitespaces).isEmpty
    }

    func loadRecent() async {
        isLoadingRecent = true
        do {
            recentFoods = try await repo.recentFoods(forceRefresh: true)
        } catch {
            // Silent failure for recent foods
        }
        isLoadingRecent = false
    }

    func search() {
        let query = searchText.trimmingCharacters(in: .whitespaces)

        // Cancel previous search
        searchTask?.cancel()

        guard !query.isEmpty else {
            searchResults = []
            isSearching = false
            return
        }

        guard query.count >= 2 else {
            return
        }

        isSearching = true
        searchTask = Task {
            // Debounce
            try? await Task.sleep(for: .milliseconds(300))
            guard !Task.isCancelled else { return }

            do {
                let results = try await repo.searchFoods(query: query)
                guard !Task.isCancelled else { return }
                searchResults = results
            } catch {
                guard !Task.isCancelled else { return }
                errorMessage = error.localizedDescription
            }
            isSearching = false
        }
    }

    func selectFood(_ food: FoodItem) {
        selectedFood = food
        addQuantity = 1
        addMealType = .guess()
        showAddSheet = true
    }

    func addFood(date: String, onComplete: @escaping () -> Void) async {
        guard let food = selectedFood else { return }
        isAddingFood = true

        let request = CreateEntryRequest(
            foodId: food.id,
            quantity: addQuantity,
            unit: food.baseUnit ?? "serving",
            mealType: addMealType.rawValue,
            entryDate: date,
            entryMethod: "manual",
            source: "ios_app"
        )

        do {
            _ = try await repo.createEntry(request)
            showAddSheet = false
            selectedFood = nil
            onComplete()
        } catch {
            errorMessage = "Failed to add food: \(error.localizedDescription)"
        }
        isAddingFood = false
    }
}
