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/theme/app_theme.dart';
import '../../core/utils/money.dart';

final participantDetailProvider = FutureProvider.autoDispose
    .family<Map<String, dynamic>, String>((ref, uuid) async {
      return ref.watch(apiServiceProvider).getParticipant(uuid);
    });

final participantSummaryProvider = FutureProvider.autoDispose
    .family<Map<String, dynamic>, String>((ref, uuid) async {
      return ref.watch(apiServiceProvider).getParticipantSummary(uuid);
    });

class ParticipantDetailScreen extends ConsumerWidget {
  final String uuid;

  const ParticipantDetailScreen({super.key, required this.uuid});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final l = AppLocalizations.of(context);
    final detail = ref.watch(participantDetailProvider(uuid));
    final summary = ref.watch(participantSummaryProvider(uuid));

    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      body: detail.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(child: Text(l.t('error_occurred'))),
        data: (participant) => CustomScrollView(
          physics: const BouncingScrollPhysics(),
          slivers: [
            // Header
            SliverToBoxAdapter(
              child: Container(
                padding: EdgeInsets.only(
                  top: MediaQuery.paddingOf(context).top + 10,
                  left: 20,
                  right: 20,
                  bottom: 24,
                ),
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(
                    bottom: Radius.circular(24),
                  ),
                ),
                child: Column(
                  children: [
                    // Back button
                    Row(
                      children: [
                        GestureDetector(
                          onTap: () => context.pop(),
                          child: Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              color: Colors.grey.shade100,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Icon(
                              Icons.arrow_back_ios_new,
                              size: 18,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    // Avatar
                    Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                        color: AppTheme.primaryColor.withValues(alpha: 0.1),
                        shape: BoxShape.circle,
                      ),
                      child: participant['photo_url'] != null
                          ? ClipOval(
                              child: Image.network(
                                participant['photo_url'],
                                fit: BoxFit.cover,
                              ),
                            )
                          : Icon(
                              Icons.person,
                              size: 40,
                              color: AppTheme.primaryColor,
                            ),
                    ).animate().scale(
                      begin: const Offset(0.7, 0.7),
                      end: const Offset(1, 1),
                      duration: 500.ms,
                      curve: Curves.easeOutBack,
                    ),
                    const SizedBox(height: 12),
                    Text(
                      participant['name_ar'] ?? participant['name'] ?? '',
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ).animate(delay: 100.ms).fadeIn(duration: 400.ms),
                    const SizedBox(height: 4),
                    _StatusBadge(status: participant['status'] ?? 'active'),
                  ],
                ),
              ),
            ),
            // Summary stats
            SliverToBoxAdapter(
              child: summary.when(
                loading: () => const SizedBox(
                  height: 80,
                  child: Center(child: CircularProgressIndicator()),
                ),
                error: (_, _) => const SizedBox.shrink(),
                data: (s) => Padding(
                  padding: const EdgeInsets.all(20),
                  child:
                      Row(
                            children: [
                              _MiniStat(
                                label: l.t('attendance_rate'),
                                value: '${s['attendance_rate'] ?? 0}%',
                                icon: Icons.check_circle,
                                color: Colors.green,
                              ),
                              const SizedBox(width: 12),
                              _MiniStat(
                                label: l.t('total_balance'),
                                value: formatMoney(
                                  s['outstanding_balance'] ?? 0,
                                ),
                                icon: Icons.account_balance_wallet,
                                color: Colors.orange,
                              ),
                              const SizedBox(width: 12),
                              _MiniStat(
                                label: l.t('enrollments'),
                                value: '${s['active_enrollments'] ?? 0}',
                                icon: Icons.school,
                                color: Colors.blue,
                              ),
                            ],
                          )
                          .animate(delay: 200.ms)
                          .fadeIn(duration: 500.ms)
                          .slideY(begin: 0.05, end: 0),
                ),
              ),
            ),
            // Action Grid
            SliverPadding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              sliver: SliverGrid.count(
                crossAxisCount: 3,
                crossAxisSpacing: 12,
                mainAxisSpacing: 12,
                childAspectRatio: 1.0,
                children: [
                  _ActionTile(
                    icon: Icons.event_note,
                    label: l.t('schedule'),
                    color: Colors.purple,
                    onTap: () => context.push('/participants/$uuid/schedule'),
                    index: 0,
                  ),
                  _ActionTile(
                    icon: Icons.fact_check,
                    label: l.t('attendance'),
                    color: Colors.green,
                    onTap: () => context.push('/participants/$uuid/attendance'),
                    index: 1,
                  ),
                  _ActionTile(
                    icon: Icons.receipt_long,
                    label: l.t('invoices'),
                    color: Colors.orange,
                    onTap: () => context.push('/participants/$uuid/invoices'),
                    index: 2,
                  ),
                  _ActionTile(
                    icon: Icons.assessment,
                    label: l.t('evaluations'),
                    color: Colors.teal,
                    onTap: () =>
                        context.push('/participants/$uuid/evaluations'),
                    index: 3,
                  ),
                  _ActionTile(
                    icon: Icons.account_balance_wallet,
                    label: l.t('wallet'),
                    color: Colors.indigo,
                    onTap: () {},
                    index: 4,
                  ),
                  _ActionTile(
                    icon: Icons.folder,
                    label: l.t('documents'),
                    color: Colors.brown,
                    onTap: () {},
                    index: 5,
                  ),
                ],
              ),
            ),
            const SliverToBoxAdapter(child: SizedBox(height: 40)),
          ],
        ),
      ),
    );
  }
}

class _StatusBadge extends StatelessWidget {
  final String status;

  const _StatusBadge({required this.status});

  @override
  Widget build(BuildContext context) {
    final (color, label) = switch (status) {
      'active' => (Colors.green, 'نشط'),
      'frozen' => (Colors.blue, 'مجمد'),
      'suspended' => (Colors.red, 'موقوف'),
      'registered' => (Colors.orange, 'مسجل'),
      _ => (Colors.grey, status),
    };

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 12,
          color: color,
          fontWeight: FontWeight.w600,
        ),
      ),
    ).animate(delay: 150.ms).fadeIn(duration: 300.ms);
  }
}

class _MiniStat extends StatelessWidget {
  final String label;
  final String value;
  final IconData icon;
  final Color color;

  const _MiniStat({
    required this.label,
    required this.value,
    required this.icon,
    required this.color,
  });

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: color.withValues(alpha: 0.05),
          borderRadius: BorderRadius.circular(14),
          border: Border.all(color: color.withValues(alpha: 0.1)),
        ),
        child: Column(
          children: [
            Icon(icon, size: 18, color: color),
            const SizedBox(height: 6),
            Text(
              value,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: color,
              ),
            ),
            const SizedBox(height: 2),
            Text(
              label,
              style: TextStyle(fontSize: 10, color: Colors.grey.shade500),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
}

class _ActionTile extends StatelessWidget {
  final IconData icon;
  final String label;
  final Color color;
  final VoidCallback onTap;
  final int index;

  const _ActionTile({
    required this.icon,
    required this.label,
    required this.color,
    required this.onTap,
    required this.index,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
          onTap: onTap,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: Colors.grey.shade100),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 44,
                  height: 44,
                  decoration: BoxDecoration(
                    color: color.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(icon, color: color, size: 22),
                ),
                const SizedBox(height: 8),
                Text(
                  label,
                  style: const TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
        )
        .animate(delay: Duration(milliseconds: 250 + (index * 60)))
        .fadeIn(duration: 400.ms)
        .scale(
          begin: const Offset(0.85, 0.85),
          end: const Offset(1, 1),
          curve: Curves.easeOutBack,
        );
  }
}
