import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';

import '../../../../core/network/dio_client.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../../core/theme/app_text_styles.dart';
import '../../../../core/theme/app_spacing.dart';
import '../../../../core/theme/app_radius.dart';
import '../../../../core/widgets/stat_card.dart';
import '../../../../core/widgets/fs_shimmer.dart';
import '../../../../core/widgets/fs_error_state.dart';
import '../../../auth/presentation/bloc/auth_cubit.dart';
import '../../data/datasources/dashboard_remote_datasource.dart';
import '../../data/repositories/dashboard_repository_impl.dart';
import '../bloc/dashboard_cubit.dart';
import '../bloc/dashboard_state.dart';
import '../widgets/quick_action_card.dart';
import '../widgets/recent_attempts_list.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) {
        final remote = DashboardRemoteDatasource(DioClient.instance);
        final repo = DashboardRepositoryImpl(remote: remote);
        return DashboardCubit(repo)..loadStats();
      },
      child: const _DashboardView(),
    );
  }
}

class _DashboardView extends StatelessWidget {
  const _DashboardView();

  @override
  Widget build(BuildContext context) {
    final user = context.read<AuthCubit>().currentUser;
    final username = user?.username ?? 'User';
    final initial = username.isNotEmpty ? username[0].toUpperCase() : '?';

    return Scaffold(
      body: SafeArea(
        child: BlocBuilder<DashboardCubit, DashboardState>(
          builder: (context, state) {
            return RefreshIndicator(
              color: AppColors.accent,
              backgroundColor: AppColors.panel,
              onRefresh: () => context.read<DashboardCubit>().refresh(),
              child: ListView(
                padding: AppSpacing.screenAll,
                children: [
                  // ── Greeting ──
                  Row(
                    children: [
                      Container(
                        width: 44,
                        height: 44,
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            colors: [AppColors.accent, Color(0xFFA855F7)],
                          ),
                          borderRadius: BorderRadius.circular(22),
                        ),
                        alignment: Alignment.center,
                        child: Text(
                          initial,
                          style: AppTextStyles.titleMedium
                              .copyWith(color: Colors.white),
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('Welcome back,',
                                style: AppTextStyles.bodySmall),
                            Text(username, style: AppTextStyles.titleMedium),
                          ],
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.person_outline,
                            color: AppColors.textSecondary),
                        onPressed: () => context.go('/app/dashboard/profile'),
                      ),
                    ],
                  ),
                  AppSpacing.vLg,

                  // ── Stats ──
                  if (state is DashboardLoading)
                    _buildStatsShimmer()
                  else if (state is DashboardLoaded) ...[
                    GridView.count(
                      crossAxisCount: 2,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisSpacing: 12,
                      mainAxisSpacing: 12,
                      childAspectRatio: 1.35,
                      children: [
                        StatCard(
                          icon: '🎯',
                          value: '${state.stats.totalScore}',
                          label: 'Total Score',
                        ),
                        StatCard(
                          icon: '📝',
                          value: '${state.stats.quizzesTaken}',
                          label: 'Quizzes',
                        ),
                        StatCard(
                          icon: '✅',
                          value: '${state.stats.accuracy.toStringAsFixed(1)}%',
                          label: 'Accuracy',
                        ),
                        StatCard(
                          icon: '📊',
                          value: '${state.stats.avgScore}',
                          label: 'Avg Score',
                        ),
                      ],
                    ),
                  ] else if (state is DashboardError)
                    FSErrorState(
                      message: state.message,
                      onRetry: () =>
                          context.read<DashboardCubit>().loadStats(),
                    ),

                  AppSpacing.vLg,

                  // ── Quick Actions ──
                  Text('Quick Actions', style: AppTextStyles.titleMedium),
                  AppSpacing.vSm,
                  Row(
                    children: [
                      QuickActionCard(
                        icon: '⚡',
                        label: 'Generate',
                        accentColor: AppColors.warning,
                        onTap: () => context.go('/app/more/generator'),
                      ),
                      const SizedBox(width: 10),
                      QuickActionCard(
                        icon: '📝',
                        label: 'Quiz',
                        accentColor: AppColors.success,
                        onTap: () => context.go('/app/quiz'),
                      ),
                      const SizedBox(width: 10),
                      QuickActionCard(
                        icon: '🔮',
                        label: 'Akinator',
                        accentColor: AppColors.purple,
                        onTap: () => context.go('/app/akinator'),
                      ),
                    ],
                  ),
                  AppSpacing.vLg,

                  // ── Recent Attempts ──
                  Container(
                    decoration: BoxDecoration(
                      color: AppColors.panel,
                      border: Border.all(color: AppColors.border),
                      borderRadius: AppRadius.mdAll,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
                          child: Text('Recent Quiz Attempts',
                              style: AppTextStyles.titleSmall),
                        ),
                        if (state is DashboardLoading)
                          const Padding(
                            padding: EdgeInsets.all(16),
                            child: FSShimmerList(itemCount: 3),
                          )
                        else if (state is DashboardLoaded)
                          RecentAttemptsList(
                              attempts: state.stats.recentAttempts),
                        const SizedBox(height: 8),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildStatsShimmer() {
    return GridView.count(
      crossAxisCount: 2,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      crossAxisSpacing: 12,
      mainAxisSpacing: 12,
      childAspectRatio: 1.35,
      children: List.generate(
        4,
        (_) => FSShimmer.card(height: 100),
      ),
    );
  }
}