import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:slrpg_app/l10n/app_localizations.dart';
import 'package:slrpg_app/src/features/multiplayer/presentation/screens/lobby_screen.dart';
import 'package:slrpg_app/src/features/workout_runner/application/battle_controller.dart';
import 'package:slrpg_app/src/features/workout_runner/application/workout_completion_service.dart';
import 'package:slrpg_app/src/features/workout_runner/application/workout_loader_service.dart';
import 'package:slrpg_app/src/features/workout_runner/presentation/widgets/timer_widget.dart';
import 'package:slrpg_app/src/shared/domain/entities/exercise.dart';
import 'package:slrpg_app/src/shared/domain/entities/workout_set.dart';

import '../../../../core/constants/asset_paths.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../core/utils/notification_service.dart';
import '../../../../shared/data/repositories/user_repository.dart';
import '../../../../shared/domain/logic/plate_calculator.dart';
import '../../../multiplayer/data/repositories/party_repository.dart';
import '../../../wiki/presentation/widgets/exercise_guide_sheet.dart';
import '../widgets/enemy_hp_bar.dart';
import '../widgets/plate_visualizer.dart';
import '../widgets/emom_timer_widget.dart';

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

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

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

class _BattleScreenState extends ConsumerState<BattleScreen> {
  @override
  void initState() {
    super.initState();
    if (widget.partyId != null) {
      log("⚔️ MULTIPLAYER BATTLE STARTED! Party ID: ${widget.partyId}");
    } else {
      log("👤 SINGLEPLAYER BATTLE");
    }
    _loadWorkout();
  }

  Future<void> _loadWorkout() async {
    try {
      final controller = ref.read(battleControllerProvider.notifier);
      final loaderService = ref.read(workoutLoaderServiceProvider);

      final exercises = await loaderService.loadWorkout(
        week: widget.week,
        day: widget.day,
        workoutId: widget.workoutId,
      );

      controller.setExercises(exercises);
    } catch (e) {
      ref.read(battleControllerProvider.notifier).setError(e.toString());
    }
  }

  bool _isTimeBasedExercise(String exerciseId) {
    final id = exerciseId.toLowerCase();
    return id.contains('plank') || id.contains('hold') || id.contains('static');
  }

  String _getEnemyAsset(String exerciseId) {
    switch (exerciseId) {
      case 'squat':
        return AssetPaths.enemyIronGolem;
      case 'pullup':
      case 'row':
        return AssetPaths.enemyGravityDemon;
      case 'dip':
      case 'bench':
        return AssetPaths.enemyPressurePhantom;
      default:
        return AssetPaths.enemyIronGolem;
    }
  }

  void _showExerciseGuide(String exerciseId) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => ExerciseGuideSheet(exerciseId: exerciseId),
    );
  }

  void _handleCompletePress() {
    final controller = ref.read(battleControllerProvider.notifier);
    final currentSet = controller.currentSet;

    if (currentSet.isAmrap) {
      _showAmrapDialog(currentSet.repsTarget);
    } else {
      _completeSetAndProgress(currentSet.repsTarget);
    }
  }

  void _completeSetAndProgress(int reps) {
    final controller = ref.read(battleControllerProvider.notifier);

    if (widget.partyId != null) {
      ref.read(partyRepositoryProvider).dealDamage(widget.partyId!, reps);
    }

    controller.completeSet(repsActual: reps);

    if (!controller.isLastSet) {
      controller.moveToNextSet();
      _startRest(90);
    } else if (!controller.isLastExercise) {
      controller.moveToNextExercise();
      _startRest(180);
    } else {
      _completeWorkout();
    }
  }

  void _startRest(int seconds) {
    ref.read(battleControllerProvider.notifier).startRest(seconds);
    _runRestTimer();
  }

  void _runRestTimer() {
    Future.delayed(const Duration(seconds: 1), () {
      if (!mounted) return;

      final controller = ref.read(battleControllerProvider.notifier);
      final battleState = ref.read(battleControllerProvider);
      
      if (battleState.isResting) {
        controller.tickRest();
        final newState = ref.read(battleControllerProvider);
        
        if (newState.isResting) {
          _runRestTimer();
        } else {
          _handleRestFinished();
        }
      }
    });
  }

  void _handleRestFinished() async {
    final user = await ref.read(userRepositoryProvider).getLocalUser();
    final settings = user?.notificationSettings ?? {};
    final restEnabled = settings['rest_finished_enabled'] ?? true;

    if (restEnabled) {
      ref.read(notificationServiceProvider).showRestFinishedNotification();
    }
  }

  void _skipRest() {
    ref.read(battleControllerProvider.notifier).skipRest();
  }

  Future<void> _completeWorkout() async {
    final state = ref.read(battleControllerProvider);
    final completionService = ref.read(workoutCompletionServiceProvider);

    final result = await completionService.completeWorkout(
      exercises: state.exercises,
      week: widget.week,
      day: widget.day,
      workoutId: widget.workoutId,
    );

    if (widget.partyId != null) {
      final userId =
          (await ref.read(userRepositoryProvider).getLocalUser())?.serverId;
      if (userId != null) {
        await ref
            .read(partyRepositoryProvider)
            .leaveParty(widget.partyId!, userId);
      }
    }

    if (!mounted) return;

    _showCompletionDialog(result.xpEarned);
    if (result.hasLevelUp) {
      _showLevelUpDialog(result.oldLevel!, result.newLevel!);
    }
  }

  void _showLevelUpDialog(int oldLevel, int newLevel) {
    final l10n = AppLocalizations.of(context)!;
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppTheme.primaryColor,
        title: Text(
          l10n.levelUpTitle,
          style: const 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(
              l10n.levelUpBody,
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium
                  ?.copyWith(color: Colors.black),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 8),
            Text(
              l10n.levelUpSubtitle,
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                  color: Colors.black54, fontStyle: FontStyle.italic),
              textAlign: TextAlign.center,
            ),
            Text(
              '$oldLevel → $newLevel',
              style: const TextStyle(
                fontSize: 32,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(l10n.continueButton,
                style: const TextStyle(color: Colors.black)),
          ),
        ],
      ),
    );
  }

  void _showCompletionDialog(int xpEarned) {
    final l10n = AppLocalizations.of(context)!;
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text(l10n.battleRaidComplete),
        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: Text(l10n.battleBackToHub),
          ),
        ],
      ),
    );
  }

  void _showAmrapDialog(int minReps) {
    int tempReps = minReps;
    final l10n = AppLocalizations.of(context)!;

    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.surfaceColor,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return Padding(
              padding: const EdgeInsets.all(24),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    l10n.amrapResultTitle,
                    style: const TextStyle(
                      color: AppTheme.secondaryColor,
                      fontWeight: FontWeight.bold,
                      fontSize: 20,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    l10n.amrapResultBody,
                    style: const TextStyle(color: Colors.grey),
                  ),
                  const SizedBox(height: 32),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _CounterButton(
                        icon: Icons.remove,
                        onTap: tempReps > 0
                            ? () => setModalState(() => tempReps--)
                            : null,
                      ),
                      Container(
                        width: 120,
                        alignment: Alignment.center,
                        child: Text(
                          '$tempReps',
                          style: const TextStyle(
                            fontSize: 72,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                      ),
                      _CounterButton(
                        icon: Icons.add,
                        onTap: () => setModalState(() => tempReps++),
                      ),
                    ],
                  ),
                  const SizedBox(height: 32),
                  SizedBox(
                    width: double.infinity,
                    height: 56,
                    child: ElevatedButton(
                      onPressed: () {
                        Navigator.pop(context);
                        _completeSetAndProgress(tempReps);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppTheme.secondaryColor,
                        foregroundColor: Colors.white,
                      ),
                      child: Text(
                        l10n.amrapConfirm,
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                ],
              ),
            );
          },
        );
      },
    );
  }

  void _handleEmomSetComplete() {
    final controller = ref.read(battleControllerProvider.notifier);
    final currentSet = controller.currentSet;

    if (widget.partyId != null) {
      ref
          .read(partyRepositoryProvider)
          .dealDamage(widget.partyId!, currentSet.repsTarget);
    }

    controller.completeSet(repsActual: currentSet.repsTarget);

    if (!controller.isLastSet) {
      controller.moveToNextSet();
    } else {
      _showEmomFinishDialog();
    }
  }

  void _showEmomFinishDialog() {
    final controller = ref.read(battleControllerProvider.notifier);
    final currentExercise = controller.currentExercise;
    int setsCount = currentExercise.sets.length;
    final l10n = AppLocalizations.of(context)!;

    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.surfaceColor,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return Padding(
              padding: const EdgeInsets.all(24),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.timer_off,
                      size: 48, color: AppTheme.primaryColor),
                  const SizedBox(height: 16),
                  Text(
                    l10n.emomFinishedTitle,
                    style: Theme.of(context).textTheme.titleLarge?.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 1.5,
                        ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    l10n.emomFinishedBody,
                    style: const TextStyle(color: Colors.grey),
                  ),
                  const SizedBox(height: 32),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _CounterButton(
                        icon: Icons.remove,
                        onTap: setsCount > 1
                            ? () => setModalState(() => setsCount--)
                            : null,
                      ),
                      Container(
                        width: 140,
                        alignment: Alignment.center,
                        child: Column(
                          children: [
                            Text(
                              '$setsCount',
                              style: const TextStyle(
                                fontSize: 64,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            ),
                            Text(
                              l10n.emomSetsCompleted,
                              style: const TextStyle(
                                color: AppTheme.primaryColor,
                                fontSize: 10,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                      _CounterButton(
                        icon: Icons.add,
                        onTap: () => setModalState(() => setsCount++),
                      ),
                    ],
                  ),
                  const SizedBox(height: 32),
                  SizedBox(
                    width: double.infinity,
                    height: 56,
                    child: ElevatedButton(
                      onPressed: () {
                        Navigator.pop(context);
                        controller.adjustEmomSets(setsCount);
                        _completeSetAndProgress(
                            controller.currentSet.repsTarget);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppTheme.successColor,
                        foregroundColor: Colors.white,
                      ),
                      child: Text(
                        l10n.emomConfirm,
                        style: const TextStyle(
                            fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                ],
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final state = ref.watch(battleControllerProvider);

    if (state.isLoading) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    if (state.error != null) {
      return Scaffold(
        appBar: AppBar(title: Text(l10n.battleTitle)),
        body: Center(child: Text(l10n.setupFailed(state.error.toString()))),
      );
    }

    if (state.exercises.isEmpty) {
      return Scaffold(
        appBar: AppBar(title: Text(l10n.battleTitle)),
        body: Center(child: Text(l10n.battleNoExercises)),
      );
    }

    final controller = ref.read(battleControllerProvider.notifier);
    final currentExercise = controller.currentExercise;
    final currentSet = controller.currentSet;

    return FutureBuilder<Map<String, dynamic>>(
      future: ref.read(userRepositoryProvider).getInventorySettingsAsync(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }

        final inventory = snapshot.data!;
        final plateResult =
            _calculatePlates(currentExercise, currentSet, inventory);

        return Scaffold(
          appBar: _buildAppBar(l10n),
          body: Stack(
            children: [
              Positioned.fill(
                child: Image.asset(
                  AssetPaths.bgUndergroundGym,
                  fit: BoxFit.cover,
                ),
              ),
              Positioned.fill(
                child: Container(
                  color: Colors.black.withValues(alpha: 0.7),
                ),
              ),
              Positioned.fill(
                child: SafeArea(
                  child: state.isResting
                      ? _buildRestScreen(l10n, inventory)
                      : _buildWorkoutScreen(
                          currentExercise,
                          currentSet,
                          plateResult,
                          controller.completedHP,
                          controller.totalHP,
                        ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildTimeBasedView(
    Exercise currentExercise,
    WorkoutSet currentSet,
    PlateLoadResult plateResult,
    int completedHP,
    int totalHP,
  ) {
    final l10n = AppLocalizations.of(context)!;
    final state = ref.watch(battleControllerProvider);
    final controller = ref.read(battleControllerProvider.notifier);

    return Column(
      children: [
        Flexible(
          flex: 3,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Image.asset(
                  _getEnemyAsset(currentExercise.exerciseId),
                  fit: BoxFit.contain,
                  color: Colors.white.withValues(alpha: 0.9),
                  colorBlendMode: BlendMode.modulate,
                ),
              ),
              Positioned(
                top: 16,
                right: 16,
                child: Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(20),
                    border: Border.all(color: Colors.white24),
                  ),
                  child: Text(
                    l10n.battleWave(
                      state.currentExerciseIndex + 1,
                      state.exercises.length,
                    ),
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
              Positioned(
                bottom: 10,
                left: 32,
                right: 32,
                child: Column(
                  children: [
                    const Icon(Icons.favorite,
                        color: AppTheme.errorColor, size: 24),
                    const SizedBox(height: 4),
                    widget.partyId != null
                        ? _buildMultiplayerHpBar()
                        : EnemyHPBar(
                            current: totalHP - completedHP,
                            max: totalHP,
                          ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 7,
          child: Container(
            decoration: BoxDecoration(
              color: AppTheme.surfaceColor.withValues(alpha: 0.95),
              borderRadius:
                  const BorderRadius.vertical(top: Radius.circular(24)),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.5),
                  blurRadius: 20,
                  offset: const Offset(0, -5),
                )
              ],
            ),
            child: Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.fromLTRB(24, 24, 24, 100),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              currentExercise.exerciseName,
                              style: Theme.of(context)
                                  .textTheme
                                  .headlineMedium
                                  ?.copyWith(
                                    color: AppTheme.primaryColor,
                                    fontWeight: FontWeight.bold,
                                  ),
                              textAlign: TextAlign.center,
                            ),
                            IconButton(
                              icon: const Icon(Icons.info_outline,
                                  color: Colors.white54),
                              onPressed: () => _showExerciseGuide(
                                  currentExercise.exerciseId),
                            ),
                          ],
                        ),

                        Text(
                          l10n.battleSet(
                            state.currentSetIndex + 1,
                            currentExercise.sets.length,
                          ),
                          style:
                              Theme.of(context).textTheme.titleMedium?.copyWith(
                                    color: Colors.white70,
                                  ),
                        ),

                        const SizedBox(height: 24),

                        Container(
                          padding: const EdgeInsets.all(24),
                          decoration: BoxDecoration(
                            color:
                                AppTheme.backgroundColor.withValues(alpha: 0.5),
                            borderRadius: BorderRadius.circular(16),
                            border: Border.all(
                              color:
                                  AppTheme.primaryColor.withValues(alpha: 0.3),
                              width: 2,
                            ),
                          ),
                          child: TimerWidget(
                            key: ValueKey(
                              '${currentExercise.exerciseId}_${state.currentExerciseIndex}_${state.currentSetIndex}',
                            ),
                            durationSeconds: currentSet.repsTarget,
                            onComplete: () {
                              controller.stopExerciseTimer();
                              _showTimeBasedCompleteDialog(currentSet);
                            },
                          ),
                        ),

                        const SizedBox(height: 24),

                        if (currentSet.targetWeightTotal > 0) ...[
                          Container(
                            padding: const EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              color: AppTheme.surfaceColor,
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(color: Colors.white10),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                const Icon(Icons.fitness_center,
                                    color: AppTheme.primaryColor),
                                const SizedBox(width: 12),
                                Text(
                                  '${currentSet.targetWeightTotal} ${l10n.unitKg}',
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 24,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 16),
                        ],

                        // // Reps Info (falls vorhanden)
                        // if (currentSet.repsTarget > 0)
                        //   Container(
                        //     padding: const EdgeInsets.symmetric(
                        //       horizontal: 16,
                        //       vertical: 12,
                        //     ),
                        //     decoration: BoxDecoration(
                        //       color: AppTheme.secondaryColor
                        //           .withValues(alpha: 0.1),
                        //       borderRadius: BorderRadius.circular(8),
                        //       border:
                        //           Border.all(color: AppTheme.secondaryColor),
                        //     ),
                        //     child: Text(
                        //       '${currentSet.repsTarget} ${currentSet.isAmrap ? "+" : ""} Reps',
                        //       style: const TextStyle(
                        //         color: AppTheme.secondaryColor,
                        //         fontSize: 18,
                        //         fontWeight: FontWeight.bold,
                        //       ),
                        //     ),
                        //   ),
                      ],
                    ),
                  ),
                ),
                Container(
                  color: AppTheme.surfaceColor,
                  padding: const EdgeInsets.all(16),
                  child: SafeArea(
                    top: false,
                    child: SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: () {
                          controller.stopExerciseTimer();
                          _showTimeBasedCompleteDialog(currentSet);
                        },
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          backgroundColor: AppTheme.successColor,
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                        child: Text(
                          l10n.battleCompleteSet,
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            letterSpacing: 1.2,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  void _showTimeBasedCompleteDialog(WorkoutSet currentSet) {
    final l10n = AppLocalizations.of(context)!;

    if (currentSet.repsTarget > 0) {
      int tempReps = currentSet.repsTarget;

      showModalBottomSheet(
        context: context,
        backgroundColor: AppTheme.surfaceColor,
        isScrollControlled: true,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
        ),
        builder: (context) {
          return StatefulBuilder(
            builder: (context, setModalState) {
              return Padding(
                padding: const EdgeInsets.all(24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(Icons.timer_off,
                        size: 48, color: AppTheme.successColor),
                    const SizedBox(height: 16),
                    Text(
                      l10n.timerComplete,
                      style: Theme.of(context).textTheme.titleLarge?.copyWith(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      l10n.amrapResultBody,
                      style: const TextStyle(color: Colors.grey),
                    ),
                    const SizedBox(height: 32),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        _CounterButton(
                          icon: Icons.remove,
                          onTap: tempReps > 0
                              ? () => setModalState(() => tempReps--)
                              : null,
                        ),
                        Container(
                          width: 120,
                          alignment: Alignment.center,
                          child: Text(
                            '$tempReps',
                            style: const TextStyle(
                              fontSize: 72,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                        ),
                        _CounterButton(
                          icon: Icons.add,
                          onTap: () => setModalState(() => tempReps++),
                        ),
                      ],
                    ),
                    const SizedBox(height: 32),
                    SizedBox(
                      width: double.infinity,
                      height: 56,
                      child: ElevatedButton(
                        onPressed: () {
                          Navigator.pop(context);
                          _completeSetAndProgress(tempReps);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppTheme.successColor,
                          foregroundColor: Colors.white,
                        ),
                        child: Text(
                          l10n.commonConfirm,
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                  ],
                ),
              );
            },
          );
        },
      );
    } else {
      _completeSetAndProgress(0);
    }
  }

  Widget _buildWorkoutScreen(
    Exercise currentExercise,
    WorkoutSet currentSet,
    PlateLoadResult plateResult,
    int completedHP,
    int totalHP,
  ) {
    if (currentExercise.intervalSeconds != null &&
        currentExercise.intervalSeconds! > 0) {
      return _buildEmomView(currentExercise, currentSet, completedHP, totalHP);
    }

    if (_isTimeBasedExercise(currentExercise.exerciseId)) {
      return _buildTimeBasedView(
        currentExercise,
        currentSet,
        plateResult,
        completedHP,
        totalHP,
      );
    }

    final l10n = AppLocalizations.of(context)!;
    final state = ref.watch(battleControllerProvider);

    return Column(
      children: [
        Flexible(
          flex: 4,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.only(bottom: 40),
                child: Image.asset(
                  _getEnemyAsset(currentExercise.exerciseId),
                  fit: BoxFit.contain,
                  color: Colors.white.withValues(alpha: 0.9),
                  colorBlendMode: BlendMode.modulate,
                ),
              ),
              Positioned(
                top: 16,
                right: 16,
                child: Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(20),
                    border: Border.all(color: Colors.white24),
                  ),
                  child: Text(
                    l10n.battleWave(
                      state.currentExerciseIndex + 1,
                      state.exercises.length,
                    ),
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
              Positioned(
                bottom: 10,
                left: 32,
                right: 32,
                child: Column(
                  children: [
                    const Icon(Icons.favorite,
                        color: AppTheme.errorColor, size: 24),
                    const SizedBox(height: 4),
                    widget.partyId != null
                        ? _buildMultiplayerHpBar()
                        : EnemyHPBar(
                            current: totalHP - completedHP,
                            max: totalHP,
                          ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 6,
          child: Container(
            decoration: BoxDecoration(
              color: AppTheme.surfaceColor.withValues(alpha: 0.95),
              borderRadius:
                  const BorderRadius.vertical(top: Radius.circular(24)),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.5),
                  blurRadius: 20,
                  offset: const Offset(0, -5),
                )
              ],
            ),
            child: Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.fromLTRB(24, 24, 24, 100),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              currentExercise.exerciseName,
                              style: Theme.of(context)
                                  .textTheme
                                  .headlineMedium
                                  ?.copyWith(
                                    color: AppTheme.primaryColor,
                                    fontWeight: FontWeight.bold,
                                  ),
                              textAlign: TextAlign.center,
                            ),
                            IconButton(
                              icon: const Icon(Icons.info_outline,
                                  color: Colors.white54),
                              onPressed: () => _showExerciseGuide(
                                  currentExercise.exerciseId),
                            ),
                          ],
                        ),
                        Text(
                          l10n.battleSet(
                            state.currentSetIndex + 1,
                            currentExercise.sets.length,
                          ),
                          style:
                              Theme.of(context).textTheme.titleMedium?.copyWith(
                                    color: Colors.white70,
                                  ),
                        ),
                        const SizedBox(height: 24),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            _InfoBox(
                              label: l10n.battleWeight,
                              value: '${currentSet.targetWeightTotal} kg',
                            ),
                            _InfoBox(
                              label: l10n.battleReps,
                              value:
                                  '${currentSet.repsTarget}${currentSet.isAmrap ? "+" : ""}',
                            ),
                          ],
                        ),
                        const SizedBox(height: 24),
                        if (plateResult.bandAssistance != null)
                          Container(
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color:
                                  AppTheme.primaryColor.withValues(alpha: 0.1),
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(color: AppTheme.primaryColor),
                            ),
                            child: Row(
                              children: [
                                const Icon(Icons.help,
                                    color: AppTheme.primaryColor, size: 32),
                                const SizedBox(width: 16),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        l10n.battleAssistance,
                                        style: const TextStyle(
                                          color: AppTheme.primaryColor,
                                          fontSize: 12,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      Text(
                                        plateResult.bandAssistance!,
                                        style: const TextStyle(
                                          color: Colors.white,
                                          fontSize: 18,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          )
                        else
                          PlateVisualizer(
                            plateConfiguration: plateResult.plateConfiguration,
                            isTwoSided: currentExercise.exerciseId == 'squat' ||
                                currentExercise.exerciseId == 'row' ||
                                currentExercise.exerciseId == 'bench',
                            exerciseName: currentExercise.exerciseName,
                          ),
                        const SizedBox(height: 32),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        Container(
          color: AppTheme.surfaceColor,
          padding: const EdgeInsets.all(16),
          child: SafeArea(
            top: false,
            child: SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _handleCompletePress,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  backgroundColor: AppTheme.primaryColor,
                  foregroundColor: Colors.black,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: Text(
                  l10n.battleCompleteSet,
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    letterSpacing: 1.2,
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  AppBar _buildAppBar(AppLocalizations l10n) {
    return AppBar(
      title: Text(l10n.battleWeekDay(widget.week, widget.day)),
      leading: IconButton(
        icon: const Icon(Icons.close),
        onPressed: () => _showAbandonDialog(l10n),
      ),
    );
  }

  void _showAbandonDialog(AppLocalizations l10n) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(l10n.battleAbandonTitle),
        content: Text(l10n.battleAbandonBody),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(l10n.cancelButton),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(context).pop();
              if (widget.partyId != null) {
                final userId =
                    (await ref.read(userRepositoryProvider).getLocalUser())
                        ?.serverId;
                if (userId != null) {
                  await ref
                      .read(partyRepositoryProvider)
                      .leaveParty(widget.partyId!, userId);
                }
              }
              if (mounted) context.go('/hub');
            },
            style: TextButton.styleFrom(foregroundColor: AppTheme.errorColor),
            child: Text(l10n.abandonButton),
          ),
        ],
      ),
    );
  }

  PlateLoadResult _calculatePlates(
    dynamic exercise,
    dynamic set,
    Map<String, dynamic> inventory,
  ) {
    final isTwoSided = ['squat', 'row', 'bench', 'rdl', 'ohp', 'curl']
        .contains(exercise.exerciseId);
    final isBodyweight = !isTwoSided;
    final barWeight = isBodyweight
        ? exercise.bodyweightAtSession
        : (inventory['bar_weight'] as num?)?.toDouble() ?? 20.0;

    final platesList = (inventory['plates'] as List?)
            ?.map((e) => (e as num).toDouble())
            .toList() ??
        [];

    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;
      }
    }

    return PlateCalculator.calculate(
      targetWeight: set.targetWeightTotal,
      barWeight: barWeight,
      availablePlates: platesList,
      availableBands: availableBands,
      isTwoSided: isTwoSided,
    );
  }

  Widget _buildRestScreen(
    AppLocalizations l10n,
    Map<String, dynamic> inventory,
  ) {
    final state = ref.watch(battleControllerProvider);
    final controller = ref.read(battleControllerProvider.notifier);
    final nextExercise = controller.currentExercise;
    final nextSet = controller.currentSet;

    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            AppTheme.backgroundColor,
            AppTheme.surfaceColor,
          ],
        ),
      ),
      child: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                l10n.battleRest,
                style: Theme.of(context).textTheme.displayLarge,
              ),
              const SizedBox(height: 20),
              SizedBox(
                width: 200,
                height: 200,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    SizedBox(
                      width: 200,
                      height: 200,
                      child: CircularProgressIndicator(
                        value: state.restSeconds / 180,
                        strokeWidth: 12,
                        backgroundColor: AppTheme.xpBarBackground,
                        color: AppTheme.primaryColor,
                      ),
                    ),
                    Text(
                      _formatTime(state.restSeconds),
                      style: Theme.of(context).textTheme.displayLarge?.copyWith(
                            fontSize: 32,
                            color: AppTheme.primaryColor,
                          ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: _skipRest,
                child: Text(l10n.battleSkipRest),
              ),
              if (nextSet != null && nextExercise != null) ...[
                const SizedBox(height: 24),
                const Divider(color: Colors.white10, endIndent: 32, indent: 32),
                const SizedBox(height: 12),
                Text(
                  l10n.battleUpNext(nextExercise.exerciseName.toUpperCase()),
                  style: const TextStyle(
                    color: Colors.grey,
                    fontSize: 11,
                    fontWeight: FontWeight.bold,
                    letterSpacing: 1.2,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '${nextSet.repsTarget} x ${nextSet.targetWeightTotal > 0 ? "${nextSet.targetWeightTotal} ${l10n.unitKg}" : l10n.bodyweight}',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                if (nextSet.targetWeightTotal > 0)
                  _buildNextSetPlates(nextExercise, nextSet, inventory),
              ],
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildNextSetPlates(
    Exercise exercise,
    WorkoutSet set,
    Map<String, dynamic> inventory,
  ) {
    final isTwoSided = exercise.exerciseId == 'squat' ||
        exercise.exerciseId == 'row' ||
        exercise.exerciseId == 'bench' ||
        exercise.exerciseId == 'rdl' ||
        exercise.exerciseId == 'ohp' ||
        exercise.exerciseId == 'curl';

    if (!isTwoSided) return const SizedBox.shrink();

    final barWeight = (inventory['bar_weight'] as num?)?.toDouble() ?? 20.0;
    final platesList = (inventory['plates'] as List?)
            ?.map((e) => (e as num).toDouble())
            .toList() ??
        [];

    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: set.targetWeightTotal,
      barWeight: barWeight,
      availablePlates: platesList,
      availableBands: availableBands,
      isTwoSided: true,
    );

    return Padding(
      padding: const EdgeInsets.only(top: 12.0),
      child: PlateVisualizer(
        plateConfiguration: plateResult.plateConfiguration,
        isTwoSided: true,
        exerciseName: '',
      ),
    );
  }

  Widget _buildEmomView(
    dynamic currentExercise,
    dynamic currentSet,
    int completedHP,
    int totalHP,
  ) {
    final l10n = AppLocalizations.of(context)!;
    final state = ref.watch(battleControllerProvider);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          padding: const EdgeInsets.all(16),
          margin: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: AppTheme.surfaceColor.withValues(alpha: 0.9),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.white10),
          ),
          child: Row(
            children: [
              SizedBox(
                height: 60,
                width: 60,
                child: Image.asset(
                  _getEnemyAsset(currentExercise.exerciseId),
                  fit: BoxFit.contain,
                  errorBuilder: (c, o, s) => const Icon(
                    Icons.fitness_center,
                    size: 40,
                    color: Colors.white,
                  ),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      currentExercise.exerciseName,
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                        color: Colors.white,
                      ),
                    ),
                    Text(
                      l10n.battleRepsPerRound(currentSet.repsTarget),
                      style: const TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              ),
              SizedBox(
                width: 80,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    widget.partyId != null
                        ? SizedBox(height: 40, child: _buildMultiplayerHpBar())
                        : Column(
                            children: [
                              Text(
                                '${totalHP - completedHP}/$totalHP HP',
                                style: const TextStyle(
                                  color: AppTheme.errorColor,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 10,
                                ),
                                textAlign: TextAlign.center,
                              ),
                              const SizedBox(height: 4),
                              ClipRRect(
                                borderRadius: BorderRadius.circular(4),
                                child: LinearProgressIndicator(
                                  value: totalHP > 0
                                      ? (totalHP - completedHP) / totalHP
                                      : 0.0,
                                  backgroundColor: Colors.red[900],
                                  color: AppTheme.errorColor,
                                  minHeight: 6,
                                ),
                              ),
                            ],
                          ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Expanded(
          child: Center(
            child: SingleChildScrollView(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  EmomTimerWidget(
                    key: ValueKey(
                        '${currentExercise.exerciseId}_${state.currentExerciseIndex}'),
                    intervalSeconds: currentExercise.intervalSeconds!,
                    totalSets: currentExercise.sets.length,
                    currentSet: state.currentSetIndex + 1,
                    onSetComplete: _handleEmomSetComplete,
                    onWorkoutComplete: _handleEmomSetComplete,
                  ),
                  const SizedBox(height: 32),
                  if (currentSet.targetWeightTotal > 0)
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 8),
                      decoration: BoxDecoration(
                        border: Border.all(color: AppTheme.primaryColor),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        l10n.battleWeightKg(currentSet.targetWeightTotal),
                        style: Theme.of(context).textTheme.titleLarge?.copyWith(
                              color: AppTheme.primaryColor,
                              fontWeight: FontWeight.bold,
                            ),
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildMultiplayerHpBar() {
    final partyAsync = ref.watch(partyStreamProvider(widget.partyId!));
    return partyAsync.when(
      data: (party) {
        if (party.status == 'finished') {
          return Container(
            height: 20,
            decoration: BoxDecoration(
              color: Colors.green,
              borderRadius: BorderRadius.circular(10),
            ),
            child: const Center(
              child: Text(
                'BOSS DEFEATED!',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
              ),
            ),
          );
        }
        return EnemyHPBar(
          current: party.currentHp,
          max: party.maxHp > 0 ? party.maxHp : 1000,
        );
      },
      loading: () =>
          const SizedBox(height: 20, child: LinearProgressIndicator()),
      error: (_, __) => const SizedBox(
        height: 20,
        child: Text(
          'Connection lost',
          style: TextStyle(color: Colors.red, fontSize: 10),
        ),
      ),
    );
  }

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

class _InfoBox extends StatelessWidget {
  final String label;
  final String value;
  const _InfoBox({required this.label, required this.value});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          label,
          style: const TextStyle(
            color: Colors.grey,
            fontSize: 12,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }
}

class _CounterButton extends StatelessWidget {
  final IconData icon;
  final VoidCallback? onTap;
  const _CounterButton({required this.icon, this.onTap});

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(30),
        child: Container(
          width: 56,
          height: 56,
          decoration: BoxDecoration(
            color: onTap != null
                ? AppTheme.primaryColor
                : Colors.grey.withValues(alpha: 0.1),
            shape: BoxShape.circle,
          ),
          child: Icon(
            icon,
            size: 32,
            color: onTap != null ? Colors.black : Colors.grey,
          ),
        ),
      ),
    );
  }
}
