import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:slrpg_app/l10n/app_localizations.dart';

import '../../../../core/theme/app_theme.dart';
import '../../../../shared/data/local/app_database.dart';
import '../../../../shared/data/repositories/user_repository.dart';
import '../../../../shared/data/repositories/workout_repository.dart';
import '../../../../shared/domain/entities/exercise.dart';

class HistoryScreen extends ConsumerStatefulWidget {
  const HistoryScreen({super.key});

  @override
  ConsumerState<HistoryScreen> createState() => _HistoryScreenState();
}

class _HistoryScreenState extends ConsumerState<HistoryScreen> {
  Future<List<WorkoutCollection>> _loadHistory() async {
    final userRepo = ref.read(userRepositoryProvider);
    final workoutRepo = ref.read(workoutRepositoryProvider);

    final user = await userRepo.getLocalUser();
    if (user == null) return [];

    final userId = user.serverId ?? user.id.toString();
    return workoutRepo.getCompletedWorkouts(userId);
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.historyTitle),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.go('/hub'),
        ),
      ),
      body: FutureBuilder<List<WorkoutCollection>>(
        future: _loadHistory(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }

          if (!snapshot.hasData || snapshot.data!.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.history_edu,
                    size: 80,
                    color: AppTheme.primaryColor.withValues(alpha: 0.5),
                  ),
                  const SizedBox(height: 16),
                  Text(
                    l10n.historyEmptyTitle,
                    style: Theme.of(context).textTheme.headlineMedium,
                  ),
                  const SizedBox(height: 8),
                  Text(
                    l10n.historyEmptyBody,
                    style: Theme.of(context).textTheme.bodyMedium,
                  ),
                ],
              ),
            );
          }

          final workouts = List<WorkoutCollection>.from(snapshot.data!)
            ..sort((a, b) => b.completedAt!.compareTo(a.completedAt!));

          return ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: workouts.length,
            itemBuilder: (context, index) {
              final workout = workouts[index];
              return _WorkoutHistoryCard(workout: workout);
            },
          );
        },
      ),
    );
  }
}

class _WorkoutHistoryCard extends StatelessWidget {
  final WorkoutCollection workout;

  const _WorkoutHistoryCard({required this.workout});

  List<Exercise> _parseExercises() {
    try {
      final List<dynamic> list = workout.exercises;
      return list
          .map((json) => Exercise.fromJson(json as Map<String, dynamic>))
          .toList();
    } catch (e) {
      log('Error parsing workout history: $e');
      return [];
    }
  }

  @override
  Widget build(BuildContext context) {
    final dateStr = DateFormat.yMMMd().format(workout.completedAt!);
    final timeStr = DateFormat.jm().format(workout.completedAt!);
    final exercises = _parseExercises();
    final l10n = AppLocalizations.of(context)!;

    final summary = exercises
        .map((e) =>
            e.exerciseName.replaceAll('Weighted ', '').replaceAll('Back ', ''))
        .toSet()
        .join(' & ');

    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      child: ExpansionTile(
        tilePadding: const EdgeInsets.all(16),
        leading: _buildDateBadge(context, workout),
        title: Text(
          summary.isEmpty ? l10n.historyUnknownWorkout : summary,
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
                color: AppTheme.primaryColor,
              ),
        ),
        subtitle: Padding(
          padding: const EdgeInsets.only(top: 4),
          child: Row(
            children: [
              Icon(Icons.access_time, size: 14, color: AppTheme.textSecondary),
              const SizedBox(width: 4),
              Text('$dateStr • $timeStr',
                  style: Theme.of(context)
                      .textTheme
                      .bodySmall
                      ?.copyWith(color: AppTheme.textSecondary)),
              const Spacer(),
              Text('+${workout.xpEarned} XP',
                  style: TextStyle(
                      color: AppTheme.secondaryColor,
                      fontWeight: FontWeight.bold)),
            ],
          ),
        ),
        children: [
          if (workout.notes.isNotEmpty)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.white10),
                ),
                child: Text(
                  '📝 "${workout.notes}"',
                  style: const TextStyle(
                      fontStyle: FontStyle.italic, color: AppTheme.textPrimary),
                ),
              ),
            ),
          ...exercises
              .map((exercise) => _ExerciseDetailRow(exercise: exercise))
              .toList(),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  Widget _buildDateBadge(BuildContext context, WorkoutCollection workout) {
    return Container(
      width: 50,
      height: 50,
      decoration: BoxDecoration(
        color: AppTheme.primaryColor.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppTheme.primaryColor.withValues(alpha: 0.3)),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            'W${workout.week}',
            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
          ),
          Text(
            'D${workout.day}',
            style: TextStyle(
                color: AppTheme.primaryColor,
                fontWeight: FontWeight.bold,
                fontSize: 16),
          ),
        ],
      ),
    );
  }
}

class _ExerciseDetailRow extends StatelessWidget {
  final Exercise exercise;

  const _ExerciseDetailRow({required this.exercise});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 4,
                height: 16,
                color: AppTheme.primaryColor,
                margin: const EdgeInsets.only(right: 8),
              ),
              Text(
                exercise.exerciseName,
                style: Theme.of(context).textTheme.titleSmall?.copyWith(
                    fontWeight: FontWeight.bold, color: AppTheme.textSecondary),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Table(
            defaultVerticalAlignment: TableCellVerticalAlignment.middle,
            columnWidths: const {
              0: FlexColumnWidth(1),
              1: FlexColumnWidth(2),
              2: FlexColumnWidth(2),
              3: FlexColumnWidth(1),
            },
            children: exercise.sets.where((s) => s.completed).map((set) {
              return TableRow(
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 4),
                    child: Text(
                      '#${set.setNumber}',
                      style: const TextStyle(color: Colors.grey, fontSize: 12),
                    ),
                  ),
                  Text(
                    '${set.targetWeightTotal} kg',
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  Row(
                    children: [
                      Text(
                        '${set.repsActual}',
                        style: TextStyle(
                          color: set.isAmrap
                              ? AppTheme.secondaryColor
                              : (set.repsActual >= set.repsTarget
                                  ? AppTheme.successColor
                                  : AppTheme.errorColor),
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        ' / ${set.repsTarget}',
                        style:
                            const TextStyle(color: Colors.grey, fontSize: 12),
                      ),
                    ],
                  ),
                  if (set.isAmrap)
                    const Icon(Icons.local_fire_department,
                        size: 16, color: AppTheme.secondaryColor)
                  else
                    const SizedBox(),
                ],
              );
            }).toList(),
          ),
          const Divider(),
        ],
      ),
    );
  }
}
