import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'dart:async';
import 'dart:convert';

import '../../../../core/constants/asset_paths.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../shared/domain/entities/exercise.dart';
import '../../../../shared/domain/entities/workout_set.dart';
import '../../../../shared/domain/logic/wendler_calculator.dart';
import '../../../../shared/domain/logic/plate_calculator.dart';
import '../../../../shared/domain/logic/xp_calculator.dart';
import '../../../../shared/data/repositories/user_repository.dart';
import '../../../../shared/data/repositories/cycle_repository.dart';
import '../../../../shared/data/repositories/workout_repository.dart';
import '../../../../shared/data/remote/sync_service.dart';
import '../widgets/plate_visualizer.dart';
import '../widgets/timer_widget.dart';
import '../widgets/enemy_hp_bar.dart';

class BattleScreen extends ConsumerStatefulWidget {
  final int week;
  final int day;
  final int? workoutId;

  const BattleScreen({
    super.key,
    required this.week,
    required this.day,
    this.workoutId,
  });

  @override
  ConsumerState<BattleScreen> createState() => _BattleScreenState();
}

class _BattleScreenState extends ConsumerState<BattleScreen> {
  List<Exercise> _exercises = [];
  int _currentExerciseIndex = 0;
  int _currentSetIndex = 0;
  int _repsCompleted = 0;
  bool _isLoading = true;
  Timer? _restTimer;
  int _restSeconds = 0;
  bool _isResting = false;

  @override
  void initState() {
    super.initState();
    _loadWorkout();
  }

  @override
  void dispose() {
    _restTimer?.cancel();
    super.dispose();
  }

  String _getEnemyAsset(String exerciseId) {
    // Mapping basierend auf Übungs-ID
    switch (exerciseId) {
      case 'squat':
        return AssetPaths.enemyIronGolem;
      case 'pullup':
        return AssetPaths.enemyGravityDemon;
      case 'dip':
        return AssetPaths.enemyPressurePhantom;
      default:
        return AssetPaths.enemyIronGolem; // Fallback
    }
  }

  List<Map<String, dynamic>> _getExerciseConfig(int day) {
    switch (day) {
      case 1:
        return [
          {
            'id': 'squat',
            'name': 'Back Squat',
            'type': ExerciseType.squat,
            'isMain': true
          },
          {
            'id': 'pullup',
            'name': 'Weighted Pull-up',
            'type': ExerciseType.pullup,
            'isMain': false
          },
        ];
      case 2:
        return [
          {
            'id': 'dip',
            'name': 'Weighted Dip',
            'type': ExerciseType.dip,
            'isMain': true
          },
          {
            'id': 'squat',
            'name': 'Back Squat',
            'type': ExerciseType.squat,
            'isMain': false
          },
        ];
      case 3:
        return [
          {
            'id': 'pullup',
            'name': 'Weighted Pull-up',
            'type': ExerciseType.pullup,
            'isMain': true
          },
          {
            'id': 'dip',
            'name': 'Weighted Dip',
            'type': ExerciseType.dip,
            'isMain': false
          },
        ];
      default:
        return [];
    }
  }

  Future<void> _loadWorkout() async {
    final userRepo = ref.read(userRepositoryProvider);
    final cycleRepo = ref.read(cycleRepositoryProvider);

    final user = await userRepo.getLocalUser();
    final cycle = await cycleRepo.getCurrentCycle();

    if (user == null || cycle == null) {
      if (mounted) context.go('/hub');
      return;
    }

    final trainingMaxes = cycleRepo.getCurrentTrainingMaxes();
    final exercises = <Exercise>[];

    final exerciseConfigs = _getExerciseConfig(widget.day);

    for (final config in exerciseConfigs) {
      final id = config['id'] as String;
      final name = config['name'] as String;
      final type = config['type'] as ExerciseType;
      final isMain = config['isMain'] as bool;

      final tm = trainingMaxes[id] ?? 0.0;
      List<WorkoutSet> sets = [];

      if (isMain) {
        sets = WendlerCalculator.generateSets(
          week: widget.week,
          trainingMax: tm,
          exerciseType: type,
          currentBodyweight: user.currentBodyweight,
        );
      } else {
        if (widget.week != 4) {
          sets = WendlerCalculator.generateFSLSets(
            trainingMax: tm,
            exerciseType: type,
            currentBodyweight: user.currentBodyweight,
          );
        }
      }

      if (sets.isNotEmpty) {
        exercises.add(Exercise(
          exerciseId: id,
          exerciseName: isMain ? name : '$name (FSL)',
          bodyweightAtSession: user.currentBodyweight,
          sets: sets,
        ));
      }
    }

    setState(() {
      _exercises = exercises;
      _isLoading = false;

      if (exercises.isNotEmpty && exercises.first.sets.isNotEmpty) {
        _repsCompleted = exercises.first.sets.first.repsTarget;
      }
    });
  }

  void _completeSet() {
    final currentExercise = _exercises[_currentExerciseIndex];
    final currentSet = currentExercise.sets[_currentSetIndex];

    final updatedSet = currentSet.copyWith(
      repsActual: _repsCompleted,
      completed: true,
    );

    final updatedSets = List<WorkoutSet>.from(currentExercise.sets);
    updatedSets[_currentSetIndex] = updatedSet;

    final updatedExercise = currentExercise.copyWith(sets: updatedSets);
    final updatedExercises = List<Exercise>.from(_exercises);
    updatedExercises[_currentExerciseIndex] = updatedExercise;

    int nextRepsTarget = 0;

    if (_currentSetIndex < currentExercise.sets.length - 1) {
      nextRepsTarget = currentExercise.sets[_currentSetIndex + 1].repsTarget;

      setState(() {
        _exercises = updatedExercises;
        _currentSetIndex++;
        _repsCompleted = nextRepsTarget;
      });
      _startRestTimer(90);
    } else if (_currentExerciseIndex < _exercises.length - 1) {
      final nextExercise = _exercises[_currentExerciseIndex + 1];
      if (nextExercise.sets.isNotEmpty) {
        nextRepsTarget = nextExercise.sets.first.repsTarget;
      }

      setState(() {
        _exercises = updatedExercises;
        _currentExerciseIndex++;
        _currentSetIndex = 0;
        _repsCompleted = nextRepsTarget;
      });
      _startRestTimer(180);
    } else {
      setState(() {
        _exercises = updatedExercises;
      });
      _completeWorkout();
    }
  }

  void _startRestTimer(int seconds) {
    setState(() {
      _isResting = true;
      _restSeconds = seconds;
    });

    _restTimer?.cancel();
    _restTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_restSeconds > 0) {
        setState(() => _restSeconds--);
      } else {
        timer.cancel();
        setState(() => _isResting = false);
      }
    });
  }

  void _skipRest() {
    _restTimer?.cancel();
    setState(() {
      _isResting = false;
      _restSeconds = 0;
    });
  }

  Future<void> _completeWorkout() async {
    final xpEarned = XPCalculator.calculateWorkoutXP(_exercises);

    final userRepo = ref.read(userRepositoryProvider);
    await userRepo.updateXP(xpEarned);

    final user = await userRepo.getLocalUser();
    if (user != null) {
      final newLevel = XPCalculator.calculateLevelFromXP(user.xp);
      if (newLevel > user.level) {
        await userRepo.updateLevel(newLevel);
        if (mounted) {
          _showLevelUpDialog(user.level, newLevel);
        }
      }
    }

    if (widget.workoutId != null) {
      final workoutRepo = ref.read(workoutRepositoryProvider);
      final cycleRepo = ref.read(cycleRepositoryProvider);
      final cycle = await cycleRepo.getCurrentCycle();

      final cycleIdRef = cycle?.serverId ?? cycle?.id.toString() ?? '';

      var workout = await workoutRepo.getWorkoutByWeekDay(
          cycleId: cycleIdRef, week: widget.week, day: widget.day);

      if (workout != null) {
        workout.exercisesJson =
            jsonEncode(_exercises.map((e) => e.toJson()).toList());
        await workoutRepo.completeWorkout(workout, xpEarned: xpEarned);

        ref.read(syncServiceProvider).sync();
      }
    }

    if (mounted) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => AlertDialog(
          title: const Text('RAID COMPLETE!'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(
                Icons.emoji_events,
                size: 64,
                color: AppTheme.primaryColor,
              ),
              const SizedBox(height: 16),
              Text(
                '+$xpEarned XP',
                style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                      color: AppTheme.primaryColor,
                    ),
              ),
            ],
          ),
          actions: [
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                context.go('/hub');
              },
              child: const Text('BACK TO HUB'),
            ),
          ],
        ),
      );
    }
  }

  void _showLevelUpDialog(int oldLevel, int newLevel) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppTheme.primaryColor,
        title: const Text(
          'LEVEL UP!',
          style: TextStyle(color: Colors.black),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.military_tech, size: 80, color: Colors.black),
            const SizedBox(height: 16),
            Text(
              '$oldLevel → $newLevel',
              style: const TextStyle(
                fontSize: 32,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child:
                const Text('CONTINUE', style: TextStyle(color: Colors.black)),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    if (_exercises.isEmpty) {
      return Scaffold(
        appBar: AppBar(title: const Text('Battle')),
        body: const Center(child: Text('No exercises configured')),
      );
    }

    final currentExercise = _exercises[_currentExerciseIndex];
    final currentSet = currentExercise.sets[_currentSetIndex];
    final userRepo = ref.watch(userRepositoryProvider);

    final totalHP = _exercises.fold<int>(
      0,
      (sum, ex) => sum + ex.sets.fold<int>(0, (s, set) => s + set.repsTarget),
    );

    final completedHP = _exercises.take(_currentExerciseIndex).fold<int>(
              0,
              (sum, ex) =>
                  sum + ex.sets.fold<int>(0, (s, set) => s + set.repsActual),
            ) +
        currentExercise.sets
            .take(_currentSetIndex)
            .fold<int>(0, (sum, set) => sum + set.repsActual);

    final isBodyweight = currentExercise.exerciseId != 'squat';
    final barWeight = isBodyweight
        ? currentExercise.bodyweightAtSession
        : userRepo.getBarWeight();
    final availablePlates = userRepo.getAvailablePlates();
    final inventory = userRepo.getInventorySettings();
    final bandsList =
        (inventory['bands'] as List?)?.cast<Map<String, dynamic>>() ?? [];

    final Map<String, double> availableBands = {};
    for (var band in bandsList) {
      final color = band['color'] as String;
      final resistance = (band['resistance_kg'] as num).toDouble();
      if (band['count'] as int > 0) {
        availableBands[color] = resistance;
      }
    }

    final plateResult = PlateCalculator.calculate(
      targetWeight: currentSet.targetWeightTotal,
      barWeight: barWeight,
      availablePlates: availablePlates,
      availableBands: availableBands,
      isTwoSided: !isBodyweight,
    );

    return Scaffold(
      appBar: AppBar(
        title: Text('Week ${widget.week} - Day ${widget.day}'),
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () {
            showDialog(
              context: context,
              builder: (context) => AlertDialog(
                title: const Text('Abandon Raid?'),
                content: const Text('Your progress will not be saved.'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('CANCEL'),
                  ),
                  TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                      context.go('/hub');
                    },
                    style: TextButton.styleFrom(
                        foregroundColor: AppTheme.errorColor),
                    child: const Text('ABANDON'),
                  ),
                ],
              ),
            );
          },
        ),
      ),
      body: Stack(
        children: [
          // 1. HINTERGRUND (Underground Gym)
          Positioned.fill(
            child: Image.asset(
              AssetPaths.bgUndergroundGym,
              fit: BoxFit.cover,
            ),
          ),

          // 2. Overlay (Atmosphäre & Lesbarkeit)
          Positioned.fill(
            child: Container(
              color: Colors.black.withOpacity(0.7), // Dunkler Schleier
            ),
          ),

          // 3. INHALT
          SafeArea(
            child: _isResting
                ? _buildRestScreen() // Rest Screen überdeckt das Gym (oder man macht ihn auch transparent)
                : _buildWorkoutScreen(currentExercise, currentSet, plateResult,
                    completedHP, totalHP),
          ),
        ],
      ),
      // body: _isResting
      //     ? _buildRestScreen()
      //     : _buildWorkoutScreen(
      //         currentExercise, currentSet, plateResult, completedHP, totalHP),
    );
  }

  Widget _buildRestScreen() {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            AppTheme.backgroundColor,
            AppTheme.surfaceColor,
          ],
        ),
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'REST',
              style: Theme.of(context).textTheme.displayLarge,
            ),
            const SizedBox(height: 32),
            SizedBox(
              width: 200,
              height: 200,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  SizedBox(
                    width: 200,
                    height: 200,
                    child: CircularProgressIndicator(
                      value: _restSeconds / 180,
                      strokeWidth: 12,
                      backgroundColor: AppTheme.xpBarBackground,
                      color: AppTheme.primaryColor,
                    ),
                  ),
                  Text(
                    _formatTime(_restSeconds),
                    style: Theme.of(context).textTheme.displayLarge?.copyWith(
                          fontSize: 48,
                          color: AppTheme.primaryColor,
                        ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 48),
            ElevatedButton(
              onPressed: _skipRest,
              child: const Text('SKIP REST'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildWorkoutScreen(
    Exercise currentExercise,
    WorkoutSet currentSet,
    PlateLoadResult plateResult,
    int completedHP,
    int totalHP,
  ) {
    // Gemeinsamer Text-Style für bessere Lesbarkeit auf Hintergründen
    final readableStyle = Theme.of(context).textTheme.bodyLarge?.copyWith(
      color: Colors.white,
      shadows: [
        const Shadow(color: Colors.black, blurRadius: 4, offset: Offset(0, 1))
      ],
    );

    final titleStyle = Theme.of(context).textTheme.titleLarge?.copyWith(
      color: Colors.white,
      fontWeight: FontWeight.bold,
      shadows: [
        const Shadow(color: Colors.black, blurRadius: 8, offset: Offset(0, 2))
      ],
    );

    return Column(
      children: [
        // Info Header (HP & Wave)
        Container(
          padding: const EdgeInsets.all(16),
          margin: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: AppTheme.surfaceColor.withOpacity(0.9),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.white10),
          ),
          child: Column(
            children: [
              // --- NEU: Enemy Image ---
              SizedBox(
                height: 120, // Gute Größe für den Header
                child: Image.asset(
                  _getEnemyAsset(
                      currentExercise.exerciseId), // Wählt das richtige Bild
                  fit: BoxFit.contain,
                  // Ein leichter Schatten, damit der Gegner nicht "schwebt"
                  color: Colors.black.withOpacity(0.2),
                  colorBlendMode: BlendMode.dstOver,
                  // Fallback Icon, falls Asset fehlt
                  errorBuilder: (c, o, s) => const Icon(
                      Icons.warning_amber_rounded,
                      size: 48,
                      color: Colors.white24),
                ),
              ),
              const SizedBox(height: 16), // Abstand zum Text
              // ------------------------
              Text(
                'Wave ${_currentExerciseIndex + 1}/${_exercises.length}',
                style: Theme.of(context).textTheme.titleMedium,
              ),
              const SizedBox(height: 8),
              EnemyHPBar(
                current: totalHP - completedHP,
                max: totalHP,
              ),
            ],
          ),
        ),

        // Scrollbarer Inhalt (nimmt den verfügbaren Platz ein)
        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 24),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Text(
                  currentExercise.exerciseName,
                  style: Theme.of(context).textTheme.displayMedium?.copyWith(
                    shadows: [
                      const Shadow(color: Colors.black, blurRadius: 10)
                    ],
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),
                Text(
                  'Set ${_currentSetIndex + 1}/${currentExercise.sets.length}',
                  style: titleStyle, // Neuer Style
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 24),

                // Target Card (etwas transparenter für Look)
                Card(
                  color: AppTheme.surfaceColor.withOpacity(0.95),
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      children: [
                        Text('TARGET',
                            style: Theme.of(context)
                                .textTheme
                                .labelLarge
                                ?.copyWith(color: AppTheme.textSecondary)),
                        const SizedBox(height: 8),
                        Text(
                          '${currentSet.targetWeightTotal.toStringAsFixed(1)} kg',
                          style: Theme.of(context)
                              .textTheme
                              .displayMedium
                              ?.copyWith(color: AppTheme.primaryColor),
                        ),
                        Text(
                          '${currentSet.targetPercentage}% TM × ${currentSet.repsTarget} reps${currentSet.isAmrap ? '+' : ''}',
                          style: readableStyle, // Neuer Style
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 24),

                // Visualizer oder Band Info
                // Wir geben dem Container eine feste Mindesthöhe, damit das Layout weniger springt,
                // aber da der Button jetzt fixiert ist, ist das Springen weniger kritisch.
                if (plateResult.bandAssistance != null)
                  Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: AppTheme.primaryColor
                          .withOpacity(0.2), // Heller für Kontrast
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(color: AppTheme.primaryColor),
                    ),
                    child: Column(
                      children: [
                        const Icon(Icons.help_outline,
                            size: 48, color: AppTheme.primaryColor),
                        const SizedBox(height: 8),
                        Text(
                          'ASSISTANCE NEEDED',
                          style: titleStyle?.copyWith(
                              color: AppTheme.primaryColor),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          'Use ${plateResult.bandAssistance} Band',
                          style: Theme.of(context)
                              .textTheme
                              .headlineSmall
                              ?.copyWith(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                          textAlign: TextAlign.center,
                        ),
                        Text(
                          '(approx. -${(plateResult.totalAchieved - currentSet.targetWeightTotal).abs().toStringAsFixed(1)} kg)',
                          style: readableStyle, // Neuer Style
                        ),
                      ],
                    ),
                  )
                else
                  PlateVisualizer(
                    plateConfiguration: plateResult.plateConfiguration,
                    isTwoSided: currentExercise.exerciseId == 'squat',
                    exerciseName: currentExercise.exerciseName,
                  ),

                const SizedBox(height: 32),

                Text(
                  'REPS COMPLETED',
                  style: titleStyle,
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 16),

                // Counter (Hintergrund hinzufügen für Lesbarkeit)
                Container(
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(30),
                  ),
                  padding:
                      const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.remove_circle),
                        iconSize: 48,
                        color: AppTheme.primaryColor,
                        onPressed: _repsCompleted > 0
                            ? () => setState(() => _repsCompleted--)
                            : null,
                      ),
                      const SizedBox(width: 24),
                      SizedBox(
                        width: 80,
                        child: Text(
                          _repsCompleted.toString(),
                          style: Theme.of(context)
                              .textTheme
                              .displayLarge
                              ?.copyWith(fontSize: 56, color: Colors.white),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      const SizedBox(width: 24),
                      IconButton(
                        icon: const Icon(Icons.add_circle),
                        iconSize: 48,
                        color: AppTheme.primaryColor,
                        onPressed: () => setState(() => _repsCompleted++),
                      ),
                    ],
                  ),
                ),

                if (currentSet.isAmrap)
                  Padding(
                    padding: const EdgeInsets.only(top: 12),
                    child: Text(
                      '🔥 AMRAP - Go for max reps! 🔥',
                      style: readableStyle?.copyWith(
                          color: AppTheme.secondaryColor,
                          fontWeight: FontWeight.bold,
                          fontSize: 18),
                      textAlign: TextAlign.center,
                    ),
                  ),

                // Platzhalter am Ende, damit man nicht "hinter" den fixierten Button scrollen muss
                const SizedBox(height: 100),
              ],
            ),
          ),
        ),

        // --- FIXIERTER BUTTON BEREICH ---
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: AppTheme.surfaceColor, // Solider Hintergrund
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.5),
                blurRadius: 10,
                offset: const Offset(0, -5),
              ),
            ],
          ),
          child: SafeArea(
            top: false,
            child: SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _repsCompleted >= currentSet.repsTarget
                    ? _completeSet
                    : null,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  backgroundColor: AppTheme.primaryColor,
                  foregroundColor: Colors.black,
                ),
                child: const Text(
                  'COMPLETE SET',
                  style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      letterSpacing: 1.5),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
  // Widget _buildWorkoutScreen(
  //   Exercise currentExercise,
  //   WorkoutSet currentSet,
  //   PlateLoadResult plateResult,
  //   int completedHP,
  //   int totalHP,
  // ) {
  //   return Column(
  //     children: [
  //       Container(
  //         padding: const EdgeInsets.all(16),
  //         color: AppTheme.surfaceColor,
  //         child: Column(
  //           children: [
  //             Text(
  //               'Wave ${_currentExerciseIndex + 1}/${_exercises.length}',
  //               style: Theme.of(context).textTheme.titleMedium,
  //             ),
  //             const SizedBox(height: 8),
  //             EnemyHPBar(
  //               current: totalHP - completedHP,
  //               max: totalHP,
  //             ),
  //           ],
  //         ),
  //       ),
  //       Expanded(
  //         child: SingleChildScrollView(
  //           padding: const EdgeInsets.all(24),
  //           child: Column(
  //             crossAxisAlignment: CrossAxisAlignment.stretch,
  //             children: [
  //               Text(
  //                 currentExercise.exerciseName,
  //                 style: Theme.of(context).textTheme.displayMedium,
  //                 textAlign: TextAlign.center,
  //               ),
  //               const SizedBox(height: 8),
  //               Text(
  //                 'Set ${_currentSetIndex + 1}/${currentExercise.sets.length}',
  //                 style: Theme.of(context).textTheme.titleLarge,
  //                 textAlign: TextAlign.center,
  //               ),
  //               const SizedBox(height: 24),
  //               Card(
  //                 child: Padding(
  //                   padding: const EdgeInsets.all(16),
  //                   child: Column(
  //                     children: [
  //                       Text('Target',
  //                           style: Theme.of(context).textTheme.bodyMedium),
  //                       const SizedBox(height: 8),
  //                       Text(
  //                         '${currentSet.targetWeightTotal.toStringAsFixed(1)} kg',
  //                         style: Theme.of(context)
  //                             .textTheme
  //                             .displayMedium
  //                             ?.copyWith(color: AppTheme.primaryColor),
  //                       ),
  //                       Text(
  //                         '${currentSet.targetPercentage}% TM × ${currentSet.repsTarget} reps${currentSet.isAmrap ? '+' : ''}',
  //                         style: Theme.of(context).textTheme.bodyMedium,
  //                       ),
  //                     ],
  //                   ),
  //                 ),
  //               ),
  //               const SizedBox(height: 24),
  //               if (plateResult.bandAssistance != null)
  //                 Container(
  //                   padding: const EdgeInsets.all(16),
  //                   decoration: BoxDecoration(
  //                     color: AppTheme.primaryColor.withOpacity(0.1),
  //                     borderRadius: BorderRadius.circular(16),
  //                     border: Border.all(color: AppTheme.primaryColor),
  //                   ),
  //                   child: Column(
  //                     children: [
  //                       const Icon(Icons.help_outline,
  //                           size: 48, color: AppTheme.primaryColor),
  //                       const SizedBox(height: 8),
  //                       Text(
  //                         'ASSISTANCE NEEDED',
  //                         style:
  //                             Theme.of(context).textTheme.titleMedium?.copyWith(
  //                                   color: AppTheme.primaryColor,
  //                                   fontWeight: FontWeight.bold,
  //                                 ),
  //                       ),
  //                       const SizedBox(height: 8),
  //                       Text(
  //                         'Use ${plateResult.bandAssistance} Band',
  //                         style: Theme.of(context).textTheme.headlineSmall,
  //                       ),
  //                       Text(
  //                         '(approx. -${(plateResult.totalAchieved - currentSet.targetWeightTotal).abs().toStringAsFixed(1)} kg)',
  //                         style: Theme.of(context).textTheme.bodySmall,
  //                       ),
  //                     ],
  //                   ),
  //                 )
  //               else
  //                 PlateVisualizer(
  //                   plateConfiguration: plateResult.plateConfiguration,
  //                   isTwoSided: currentExercise.exerciseId == 'squat',
  //                   exerciseName: currentExercise.exerciseName,
  //                 ),
  //               const SizedBox(height: 32),
  //               Text(
  //                 'Reps Completed',
  //                 style: Theme.of(context).textTheme.titleLarge,
  //                 textAlign: TextAlign.center,
  //               ),
  //               const SizedBox(height: 16),
  //               Row(
  //                 mainAxisAlignment: MainAxisAlignment.center,
  //                 children: [
  //                   IconButton(
  //                     icon: const Icon(Icons.remove_circle),
  //                     iconSize: 48,
  //                     color: AppTheme.primaryColor,
  //                     onPressed: _repsCompleted > 0
  //                         ? () => setState(() => _repsCompleted--)
  //                         : null,
  //                   ),
  //                   const SizedBox(width: 24),
  //                   SizedBox(
  //                     width: 100,
  //                     child: Text(
  //                       _repsCompleted.toString(),
  //                       style: Theme.of(context)
  //                           .textTheme
  //                           .displayLarge
  //                           ?.copyWith(
  //                               fontSize: 64, color: AppTheme.primaryColor),
  //                       textAlign: TextAlign.center,
  //                     ),
  //                   ),
  //                   const SizedBox(width: 24),
  //                   IconButton(
  //                     icon: const Icon(Icons.add_circle),
  //                     iconSize: 48,
  //                     color: AppTheme.primaryColor,
  //                     onPressed: () => setState(() => _repsCompleted++),
  //                   ),
  //                 ],
  //               ),
  //               if (currentSet.isAmrap)
  //                 Padding(
  //                   padding: const EdgeInsets.only(top: 8),
  //                   child: Text(
  //                     'AMRAP - Go for max reps!',
  //                     style: Theme.of(context).textTheme.bodyMedium?.copyWith(
  //                         color: AppTheme.secondaryColor,
  //                         fontWeight: FontWeight.bold),
  //                     textAlign: TextAlign.center,
  //                   ),
  //                 ),
  //               const SizedBox(height: 32),
  //               ElevatedButton(
  //                 onPressed: _repsCompleted >= currentSet.repsTarget
  //                     ? _completeSet
  //                     : null,
  //                 style: ElevatedButton.styleFrom(
  //                     padding: const EdgeInsets.symmetric(vertical: 20)),
  //                 child: const Text('COMPLETE SET'),
  //               ),
  //             ],
  //           ),
  //         ),
  //       ),
  //     ],
  //   );
  // }

  String _formatTime(int seconds) {
    final minutes = seconds ~/ 60;
    final secs = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }
}
