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 attendanceProvider =
    FutureProvider.autoDispose.family<Map<String, dynamic>, String>((ref, uuid) async {
  return ref.watch(apiServiceProvider).getAttendance(uuid);
});

class AttendanceScreen extends ConsumerWidget {
  final String participantUuid;

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

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

    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      appBar: AppBar(
        title: Text(l.t('attendance')),
        centerTitle: true,
        backgroundColor: Colors.white,
        surfaceTintColor: Colors.transparent,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new, size: 18),
          onPressed: () => context.pop(),
        ),
      ),
      body: attendance.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(child: Text(l.t('error_occurred'))),
        data: (data) {
          final records = (data['data'] as List?) ?? [];
          final rate = data['rate'] ?? 0;

          return Column(
            children: [
              // Rate header
              Container(
                margin: const EdgeInsets.all(16),
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(18),
                  boxShadow: [
                    BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 10),
                  ],
                ),
                child: Row(
                  children: [
                    SizedBox(
                      width: 70,
                      height: 70,
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          CircularProgressIndicator(
                            value: (rate as num).toDouble() / 100,
                            strokeWidth: 6,
                            backgroundColor: Colors.grey.shade200,
                            color: _rateColor(rate),
                          ),
                          Text(
                            '$rate%',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: _rateColor(rate),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 20),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            l.t('attendance_rate'),
                            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            '${records.length} ${l.t('sessions')}',
                            style: TextStyle(fontSize: 13, color: Colors.grey.shade500),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ).animate().fadeIn(duration: 500.ms).slideY(begin: 0.05, end: 0),
              // Records
              Expanded(
                child: records.isEmpty
                    ? EmptyState(icon: Icons.event_busy, message: l.t('no_attendance'))
                    : ListView.builder(
                        physics: const BouncingScrollPhysics(),
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        itemCount: records.length,
                        itemBuilder: (ctx, i) {
                          final r = records[i] as Map<String, dynamic>;
                          return _AttendanceTile(record: r, index: i);
                        },
                      ),
              ),
            ],
          );
        },
      ),
    );
  }

  Color _rateColor(dynamic rate) {
    final r = (rate as num).toDouble();
    if (r >= 80) return Colors.green;
    if (r >= 60) return Colors.orange;
    return Colors.red;
  }
}

class _AttendanceTile extends StatelessWidget {
  final Map<String, dynamic> record;
  final int index;

  const _AttendanceTile({required this.record, required this.index});

  @override
  Widget build(BuildContext context) {
    final status = record['status'] ?? 'expected';
    final (color, icon, label) = _statusInfo(status);

    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade100),
      ),
      child: Row(
        children: [
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Icon(icon, color: color, size: 18),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  record['session_date'] ?? '',
                  style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                ),
                if (record['group_name'] != null) ...[
                  const SizedBox(height: 2),
                  Text(
                    record['group_name'],
                    style: TextStyle(fontSize: 12, color: Colors.grey.shade500),
                  ),
                ],
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Text(label, style: TextStyle(fontSize: 11, color: color, fontWeight: FontWeight.w600)),
          ),
        ],
      ),
    )
        .animate(delay: Duration(milliseconds: 40 * index))
        .fadeIn(duration: 350.ms)
        .slideX(begin: 0.03, end: 0);
  }

  (Color, IconData, String) _statusInfo(String status) => switch (status) {
        'present' => (Colors.green, Icons.check_circle, 'حاضر'),
        'late' => (Colors.orange, Icons.schedule, 'متأخر'),
        'absent' => (Colors.red, Icons.cancel, 'غائب'),
        'excused' => (Colors.blue, Icons.info, 'معذور'),
        'no_show' => (Colors.red.shade800, Icons.close, 'لم يحضر'),
        _ => (Colors.grey, Icons.circle_outlined, status),
      };
}
