//
// ActiveWorkoutGateView.swift
// Workouts Watch App
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//

import SwiftUI
import SwiftData

/// Root of the watch app. The watch only runs the workouts that are currently
/// active on the phone — there's no history browsing here. An "active" workout is a
/// cached one that isn't finished (`notStarted` or `inProgress`); a workout is
/// created on the phone as `notStarted` the moment a split is picked, and flips to
/// `completed` once every exercise is done, at which point it drops off this list.
///
/// The root shows every active workout (most-recent first); picking one opens its
/// exercise list.
struct ActiveWorkoutGateView: View {
    @Environment(WatchConnectivityBridge.self) private var bridge
    @Environment(WorkoutSessionManager.self) private var sessionManager

    @Query(sort: \Workout.start, order: .reverse) private var workouts: [Workout]
    @Query private var splits: [Split]

    private var activeWorkouts: [Workout] {
        workouts.filter { $0.status == .inProgress || $0.status == .notStarted }
    }

    private func split(for workout: Workout) -> Split? {
        guard let id = workout.splitID else { return nil }
        return splits.first { $0.id == id }
    }

    var body: some View {
        NavigationStack {
            Group {
                if activeWorkouts.isEmpty {
                    emptyState
                } else {
                    List {
                        ForEach(activeWorkouts) { workout in
                            NavigationLink {
                                WorkoutLogListView(workout: workout)
                            } label: {
                                ActiveWorkoutRow(workout: workout, split: split(for: workout))
                            }
                        }
                    }
                    .navigationTitle("In Progress")
                }
            }
        }
        .task {
            // Nothing to run yet — pull fresh state in case the phone just started one.
            if activeWorkouts.isEmpty { bridge.requestSync() }
        }
        .onChange(of: activeWorkouts.isEmpty) { _, noActiveWorkouts in
            // Everything finished (or was cleared) — release the HealthKit session that
            // was keeping the launched app alive.
            if noActiveWorkouts { sessionManager.end() }
        }
    }

    private var emptyState: some View {
        ContentUnavailableView {
            Label("Start a Workout", systemImage: "iphone")
        } description: {
            Text("Begin a workout on your iPhone to run it here.")
        } actions: {
            Button {
                bridge.requestSync()
            } label: {
                Label("Refresh", systemImage: "arrow.triangle.2.circlepath")
            }
        }
    }
}

// MARK: - Active Workout Row

private struct ActiveWorkoutRow: View {
    let workout: Workout
    let split: Split?

    private var logs: [WorkoutLog] { workout.logsArray }
    private var doneCount: Int { logs.filter { $0.status == .completed }.count }

    var body: some View {
        HStack(spacing: 10) {
            Image(systemName: split?.systemImage ?? "figure.strengthtraining.traditional")
                .font(.title3)
                .foregroundStyle(split.map { Color.color(from: $0.color) } ?? .workTint)
                .frame(width: 26)

            VStack(alignment: .leading, spacing: 2) {
                Text(workout.splitName ?? Split.unnamed)
                    .font(.headline)
                    .lineLimit(1)

                Text(subtitle)
                    .font(.caption2)
                    .foregroundStyle(.secondary)
            }
        }
    }

    private var subtitle: String {
        guard !logs.isEmpty else { return workout.start.formattedDate() }
        if doneCount == 0 { return "Not started · \(logs.count) exercises" }
        return "\(doneCount) of \(logs.count) done"
    }
}
