import SwiftUI
import HealthKit
import HealthDB
import HealthKitExtensions
import SFSafeSymbols

struct WorkoutListRow: View {

    let workout: Workout

    var indoor: Bool {
        guard let isIndoor: Bool = workout.metadata?.indoorWorkout else {
            return false
        }
        return isIndoor
    }

    var type: HKWorkoutActivityType {
        if #available(iOS 17.0, *) {
            if let type: HKWorkoutActivityType = workout.metadata?.activityType {
                return type
            }
        }
        return workout.workoutActivityType
    }

    var titleText: String {
        if let distance = workout.totalDistance, distance > 0 {
            return (distance * 1000).lengthAsMeter
        }
        return workout.duration.durationString
    }

    @State var existsInHealth: Bool = false

    var body: some View {
        HStack {
            ZStack(alignment: .center) {
                Image(systemSymbol: type.icon(indoor: indoor))
                    .foregroundStyle(Color.accentColor)
                    .padding(12)
                LinearGradient(colors: [Color.accentColor.opacity(0.0), Color.accentColor.opacity(0.4)], startPoint: .bottomLeading, endPoint: .topTrailing)
                .clipShape(Circle())
                    .frame(width: 50, height: 50)
            }.frame(width: 50, height: 50)
            VStack(alignment: .leading) {
                HStack(alignment: .top) {
                    Text(workout.typeString)
                        .font(.subheadline)
                        .fontWeight(.medium)
                        .foregroundStyle(.primary)
                    Spacer()
                    if existsInHealth {
                        Image(systemSymbol: .heartCircleFill)
                            .foregroundStyle(.red)
                    }
                }
                HStack(alignment: .lastTextBaseline) {
                    Text(titleText)
                        .font(.title)
                        .foregroundStyle(Color.accentColor)

                    Spacer()
                    Text(workout.endDate.timeOrDateText)
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }

            }
        }
        .padding(16)
        .background(Color.secondary.opacity(0.2))
        .clipShape(RoundedRectangle(cornerRadius: 10.0))
        .onAppear(perform: findMatchingHealthWorkout)
    }

    private func findMatchingHealthWorkout() {
        Task {
            await searchHealth()
        }
    }

    private func searchHealth() async {
        guard HKHealthStore.isHealthDataAvailable() else {
            return
        }
        let found = await hasWorkoutInHealth()
        DispatchQueue.main.async {
            self.existsInHealth = found
        }
    }

    private func hasWorkoutInHealth() async -> Bool {
        guard let activityType = workout.workoutActivities.first?.workoutConfiguration.activityType else {
            return false
        }
        let store = HealthStore()
        switch store.authorizationStatus(for: HKWorkout.self) {
        case .notDetermined:
            return false
        case .sharingAuthorized, .sharingDenied:
            break
        @unknown default:
            print("Unknown permission for workouts")
            return false
        }

        let start = workout.startDate.addingTimeInterval(-60)
        let end = workout.endDate.addingTimeInterval(60)
        do {
            guard let _ = try await store.workouts(activityType: activityType, from: start, to: end)
                .first else {
                return false
            }
            return true
        } catch {
            print("Failed to search for matching workout: \(error)")
            return false
        }
    }
}

#Preview {
    WorkoutListRow(workout: .mock1)
        .preferredColorScheme(.dark)
}
