import SwiftUI
import PhotosUI

@Observable
final class HomeViewModel {
    private let repo = FitnessRepository.shared

    var totalCalories: Double = 0
    var calorieGoal: Double = 2000
    var isLoading = false

    // Background image
    var backgroundImage: UIImage?
    var selectedPhoto: PhotosPickerItem?

    private let backgroundKey = "homeBackgroundImage"

    init() {
        loadSavedBackground()
    }

    var hasBackground: Bool {
        backgroundImage != nil
    }

    func loadTodayData() async {
        isLoading = true
        let today = Date().apiDateString
        async let entriesTask: () = repo.loadEntries(date: today)
        async let goalTask: () = repo.loadGoal(date: today)
        _ = await (entriesTask, goalTask)
        totalCalories = repo.entries.reduce(0) { $0 + $1.snapshotCalories }
        calorieGoal = repo.goal?.calories ?? 2000
        isLoading = false
    }

    // MARK: - Background Image

    func handlePhotoSelection() async {
        guard let item = selectedPhoto else { return }
        guard let data = try? await item.loadTransferable(type: Data.self) else { return }
        guard let original = UIImage(data: data) else { return }

        let resized = resizeImage(original, maxWidth: 1200)
        backgroundImage = resized

        if let jpegData = resized.jpegData(compressionQuality: 0.8) {
            UserDefaults.standard.set(jpegData, forKey: backgroundKey)
        }
        selectedPhoto = nil
    }

    func removeBackground() {
        backgroundImage = nil
        UserDefaults.standard.removeObject(forKey: backgroundKey)
    }

    private func loadSavedBackground() {
        if let data = UserDefaults.standard.data(forKey: backgroundKey),
           let image = UIImage(data: data) {
            backgroundImage = image
        }
    }

    private func resizeImage(_ image: UIImage, maxWidth: CGFloat) -> UIImage {
        let scale = maxWidth / image.size.width
        guard scale < 1 else { return image }
        let newSize = CGSize(width: maxWidth, height: image.size.height * scale)
        let renderer = UIGraphicsImageRenderer(size: newSize)
        return renderer.image { _ in
            image.draw(in: CGRect(origin: .zero, size: newSize))
        }
    }
}
