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/auth/auth_store.dart';
import '../../core/l10n/app_localizations.dart';
import '../../core/theme/app_theme.dart';
import '../../core/utils/money.dart';
import '../../core/widgets/animated_card.dart';

final dashboardProvider = FutureProvider.autoDispose<Map<String, dynamic>>((
  ref,
) async {
  return ref.watch(apiServiceProvider).getDashboard();
});

class DashboardScreen extends ConsumerWidget {
  const DashboardScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final l = AppLocalizations.of(context);
    final auth = ref.watch(authStoreProvider);
    final dashboard = ref.watch(dashboardProvider);

    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      body: RefreshIndicator(
        onRefresh: () async => ref.invalidate(dashboardProvider),
        child: CustomScrollView(
          physics: const AlwaysScrollableScrollPhysics(
            parent: BouncingScrollPhysics(),
          ),
          slivers: [
            // Header
            SliverToBoxAdapter(
              child: Container(
                padding: EdgeInsets.only(
                  top: MediaQuery.paddingOf(context).top + 16,
                  left: 20,
                  right: 20,
                  bottom: 20,
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: const BorderRadius.vertical(
                    bottom: Radius.circular(24),
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withValues(alpha: 0.03),
                      blurRadius: 10,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    _greeting(l),
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Colors.grey.shade500,
                                    ),
                                  ),
                                  const SizedBox(height: 4),
                                  Text(
                                    auth.userName ?? '',
                                    style: const TextStyle(
                                      fontSize: 22,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              width: 48,
                              height: 48,
                              decoration: BoxDecoration(
                                color: AppTheme.primaryColor.withValues(
                                  alpha: 0.1,
                                ),
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: Icon(
                                Icons.person,
                                color: AppTheme.primaryColor,
                              ),
                            ),
                          ],
                        )
                        .animate()
                        .fadeIn(duration: 500.ms)
                        .slideY(begin: -0.1, end: 0),
                  ],
                ),
              ),
            ),
            // Body
            dashboard.when(
              loading: () => const SliverFillRemaining(
                child: Center(child: CircularProgressIndicator()),
              ),
              error: (e, _) => SliverFillRemaining(
                child: Center(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        Icons.error_outline,
                        size: 48,
                        color: Colors.grey.shade300,
                      ),
                      const SizedBox(height: 12),
                      Text(
                        l.t('error_occurred'),
                        style: TextStyle(color: Colors.grey.shade500),
                      ),
                      const SizedBox(height: 12),
                      TextButton(
                        onPressed: () => ref.invalidate(dashboardProvider),
                        child: Text(l.t('retry')),
                      ),
                    ],
                  ),
                ),
              ),
              data: (data) => SliverPadding(
                padding: const EdgeInsets.all(20),
                sliver: SliverList(
                  delegate: SliverChildListDelegate([
                    // Quick Stats
                    _QuickStats(data: data['totals'] ?? {}, l: l),
                    const SizedBox(height: 20),
                    // Children cards
                    if ((data['children'] as List?)?.isNotEmpty ?? false) ...[
                      _SectionHeader(title: l.t('my_children')),
                      const SizedBox(height: 12),
                      ..._buildChildrenCards(
                        context,
                        data['children'] as List,
                        l,
                      ),
                      const SizedBox(height: 20),
                    ],
                    // Today sessions
                    if ((data['today_sessions'] as List?)?.isNotEmpty ??
                        false) ...[
                      _SectionHeader(title: l.t('today_sessions')),
                      const SizedBox(height: 12),
                      ..._buildSessionCards(data['today_sessions'] as List),
                      const SizedBox(height: 20),
                    ],
                    // Quick Actions
                    _QuickActions(l: l),
                    const SizedBox(height: 40),
                  ]),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _greeting(AppLocalizations l) {
    final hour = DateTime.now().hour;
    return hour < 12 ? l.t('good_morning') : l.t('good_evening');
  }

  List<Widget> _buildChildrenCards(
    BuildContext context,
    List children,
    AppLocalizations l,
  ) {
    return children.asMap().entries.map((entry) {
      final i = entry.key;
      final child = entry.value as Map<String, dynamic>;
      return Padding(
            padding: const EdgeInsets.only(bottom: 12),
            child: AnimatedCard(
              onTap: () => context.push('/participants/${child['uuid']}'),
              child: Row(
                children: [
                  Container(
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                      color: AppTheme.primaryColor.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(14),
                    ),
                    child: child['photo_url'] != null
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(14),
                            child: Image.network(
                              child['photo_url'],
                              fit: BoxFit.cover,
                            ),
                          )
                        : Icon(Icons.person, color: AppTheme.primaryColor),
                  ),
                  const SizedBox(width: 14),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          child['name_ar'] ?? '',
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        const SizedBox(height: 4),
                        if (child['next_session'] != null)
                          Text(
                            '${l.t('next_session')}: ${child['next_session']['group_name']}',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey.shade500,
                            ),
                          ),
                      ],
                    ),
                  ),
                  if ((int.tryParse(child['outstanding_balance']?.toString() ?? '0') ?? 0) > 0)
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 6,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.red.shade50,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        child['outstanding_display'] ?? '',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.red.shade700,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  const SizedBox(width: 8),
                  Icon(Icons.chevron_right, color: Colors.grey.shade300),
                ],
              ),
            ),
          )
          .animate(delay: Duration(milliseconds: 100 + (i * 80)))
          .fadeIn(duration: 450.ms)
          .slideX(begin: 0.05, end: 0, curve: Curves.easeOutCubic);
    }).toList();
  }

  List<Widget> _buildSessionCards(List sessions) {
    return sessions.asMap().entries.map((entry) {
      final i = entry.key;
      final s = entry.value as Map<String, dynamic>;
      return Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: Container(
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(14),
                border: Border.all(color: Colors.grey.shade100),
              ),
              child: Row(
                children: [
                  Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(
                      color: AppTheme.accentColor.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Icon(
                      Icons.sports,
                      color: AppTheme.accentColor,
                      size: 22,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          s['group_name'] ?? '',
                          style: const TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 14,
                          ),
                        ),
                        Text(
                          '${s['start_time']} - ${s['end_time']}',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey.shade500,
                          ),
                        ),
                      ],
                    ),
                  ),
                  _StatusChip(status: s['status'] ?? 'scheduled'),
                ],
              ),
            ),
          )
          .animate(delay: Duration(milliseconds: 200 + (i * 60)))
          .fadeIn(duration: 400.ms)
          .slideY(begin: 0.05, end: 0);
    }).toList();
  }
}

class _QuickStats extends StatelessWidget {
  final Map<String, dynamic> data;
  final AppLocalizations l;

  const _QuickStats({required this.data, required this.l});

  @override
  Widget build(BuildContext context) {
    return Row(
          children: [
            Expanded(
              child: _StatCard(
                icon: Icons.account_balance_wallet,
                label: l.t('total_balance'),
                value: formatMoney(data['outstanding_balance'] ?? 0),
                color: Colors.orange,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _StatCard(
                icon: Icons.today,
                label: l.t('today_sessions'),
                value: '${data['today_sessions'] ?? 0}',
                color: AppTheme.primaryColor,
              ),
            ),
          ],
        )
        .animate(delay: 200.ms)
        .fadeIn(duration: 500.ms)
        .slideY(begin: 0.08, end: 0);
  }
}

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

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

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

class _SectionHeader extends StatelessWidget {
  final String title;
  final VoidCallback? onViewAll;

  const _SectionHeader({required this.title}) : onViewAll = null;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text(
          title,
          style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
        ),
        const Spacer(),
        if (onViewAll != null)
          TextButton(
            onPressed: onViewAll,
            child: const Text('عرض الكل', style: TextStyle(fontSize: 13)),
          ),
      ],
    );
  }
}

class _StatusChip extends StatelessWidget {
  final String status;

  const _StatusChip({required this.status});

  @override
  Widget build(BuildContext context) {
    final (color, label) = switch (status) {
      'scheduled' => (Colors.blue, 'مجدولة'),
      'in_progress' => (Colors.green, 'جارية'),
      'completed' => (Colors.grey, 'مكتملة'),
      'cancelled' => (Colors.red, 'ملغاة'),
      _ => (Colors.grey, status),
    };

    return 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,
        ),
      ),
    );
  }
}

class _QuickActions extends StatelessWidget {
  final AppLocalizations l;

  const _QuickActions({required this.l});

  @override
  Widget build(BuildContext context) {
    final actions = [
      (Icons.event, l.t('events'), '/events', AppTheme.primaryColor),
      (Icons.shopping_bag_rounded, l.t('shop'), '/shop', AppTheme.accentColor),
      (Icons.mail_rounded, l.t('messages'), '/messages', Colors.teal),
      (
        Icons.description_rounded,
        l.t('service_requests'),
        '/service-requests',
        Colors.purple,
      ),
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _SectionHeader(title: l.t('more')),
        const SizedBox(height: 12),
        GridView.count(
          crossAxisCount: 4,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
          childAspectRatio: 0.85,
          children: actions.asMap().entries.map((entry) {
            final i = entry.key;
            final (icon, label, route, color) = entry.value;
            return GestureDetector(
                  onTap: () => context.push(route),
                  child: Column(
                    children: [
                      Container(
                        width: 52,
                        height: 52,
                        decoration: BoxDecoration(
                          color: color.withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(16),
                        ),
                        child: Icon(icon, color: color, size: 24),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        label,
                        style: const TextStyle(
                          fontSize: 11,
                          fontWeight: FontWeight.w500,
                        ),
                        textAlign: TextAlign.center,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                )
                .animate(delay: Duration(milliseconds: 400 + (i * 80)))
                .fadeIn(duration: 400.ms)
                .scale(
                  begin: const Offset(0.8, 0.8),
                  end: const Offset(1, 1),
                  curve: Curves.easeOutBack,
                );
          }).toList(),
        ),
      ],
    );
  }
}
