import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../core/api/api_service.dart';
import '../../core/l10n/app_localizations.dart';
import '../../core/widgets/loading_overlay.dart';

final evaluationsProvider =
    FutureProvider.autoDispose.family<List<dynamic>, String>((ref, uuid) async {
  return ref.watch(apiServiceProvider).getEvaluations(uuid);
});

class EvaluationsScreen extends ConsumerWidget {
  final String participantUuid;

  const EvaluationsScreen({super.key, required this.participantUuid});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final l = AppLocalizations.of(context);
    final evaluations = ref.watch(evaluationsProvider(participantUuid));

    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      appBar: AppBar(
        title: Text(l.t('evaluations')),
        centerTitle: true,
        backgroundColor: Colors.white,
        surfaceTintColor: Colors.transparent,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new, size: 18),
          onPressed: () => context.pop(),
        ),
      ),
      body: evaluations.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(child: Text(l.t('error_occurred'))),
        data: (items) {
          if (items.isEmpty) {
            return EmptyState(icon: Icons.assessment, message: l.t('no_evaluations'));
          }
          return ListView.builder(
            physics: const BouncingScrollPhysics(),
            padding: const EdgeInsets.all(16),
            itemCount: items.length,
            itemBuilder: (ctx, i) {
              final eval = items[i] as Map<String, dynamic>;
              return _EvaluationCard(evaluation: eval, index: i);
            },
          );
        },
      ),
    );
  }
}

class _EvaluationCard extends StatelessWidget {
  final Map<String, dynamic> evaluation;
  final int index;

  const _EvaluationCard({required this.evaluation, required this.index});

  @override
  Widget build(BuildContext context) {
    final criteria = (evaluation['criteria'] as List?) ?? [];
    final overallScore = evaluation['overall_score'] ?? 0;
    final date = evaluation['evaluation_date'] ?? '';
    final trainerName = evaluation['trainer_name'] ?? '';

    return Container(
      margin: const EdgeInsets.only(bottom: 14),
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        boxShadow: [
          BoxShadow(color: Colors.black.withValues(alpha: 0.04), blurRadius: 12, offset: const Offset(0, 3)),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 44,
                height: 44,
                decoration: BoxDecoration(
                  color: _scoreColor(overallScore).withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Center(
                  child: Text(
                    '$overallScore',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: _scoreColor(overallScore),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      evaluation['period_name'] ?? 'تقييم',
                      style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      '$trainerName • $date',
                      style: TextStyle(fontSize: 12, color: Colors.grey.shade500),
                    ),
                  ],
                ),
              ),
            ],
          ),
          if (criteria.isNotEmpty) ...[
            const SizedBox(height: 16),
            ...criteria.map((c) {
              final crit = c as Map<String, dynamic>;
              final score = (crit['score'] ?? 0) as num;
              final maxScore = (crit['max_score'] ?? 10) as num;
              return Padding(
                padding: const EdgeInsets.only(bottom: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            crit['name'] ?? '',
                            style: const TextStyle(fontSize: 13),
                          ),
                        ),
                        Text(
                          '$score/$maxScore',
                          style: TextStyle(fontSize: 12, color: Colors.grey.shade600, fontWeight: FontWeight.w600),
                        ),
                      ],
                    ),
                    const SizedBox(height: 6),
                    ClipRRect(
                      borderRadius: BorderRadius.circular(4),
                      child: LinearProgressIndicator(
                        value: maxScore > 0 ? score / maxScore : 0,
                        backgroundColor: Colors.grey.shade100,
                        color: _scoreColor((score / maxScore * 10).round()),
                        minHeight: 6,
                      ),
                    ),
                  ],
                ),
              );
            }),
          ],
          if (evaluation['notes'] != null && (evaluation['notes'] as String).isNotEmpty) ...[
            const SizedBox(height: 12),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: const Color(0xFFF8FAFC),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Text(
                evaluation['notes'],
                style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
              ),
            ),
          ],
        ],
      ),
    )
        .animate(delay: Duration(milliseconds: 80 * index))
        .fadeIn(duration: 450.ms)
        .slideY(begin: 0.04, end: 0);
  }

  Color _scoreColor(dynamic score) {
    final s = (score as num).toDouble();
    if (s >= 8) return Colors.green;
    if (s >= 6) return Colors.orange;
    if (s >= 4) return Colors.amber;
    return Colors.red;
  }
}
