import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fl_chart/fl_chart.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/theme/app_gradients.dart';
import '../../../../core/widgets/fs_shimmer.dart';
import '../../../../core/widgets/fs_error_state.dart';
import '../../../../core/widgets/fs_button.dart';
import '../../../auth/presentation/bloc/auth_cubit.dart';
import '../../data/datasources/dashboard_remote_datasource.dart';
import '../../data/repositories/dashboard_repository_impl.dart';
import '../../data/models/user_stats_model.dart';
import '../bloc/dashboard_cubit.dart';
import '../bloc/dashboard_state.dart';

class ProfileScreen extends StatelessWidget {
  const ProfileScreen({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 _ProfileView(),
    );
  }
}

class _ProfileView extends StatelessWidget {
  const _ProfileView();

  @override
  Widget build(BuildContext context) {
    final authCubit = context.read<AuthCubit>();
    final user = authCubit.currentUser;

    return Scaffold(
      appBar: AppBar(title: const Text('Profile')),
      body: BlocBuilder<DashboardCubit, DashboardState>(
        builder: (context, state) {
          if (state is DashboardLoading) {
            return const Center(child: CircularProgressIndicator());
          }
          if (state is DashboardError) {
            return FSErrorState(
              message: state.message,
              onRetry: () => context.read<DashboardCubit>().loadStats(),
            );
          }
          if (state is! DashboardLoaded) {
            return const SizedBox.shrink();
          }

          final stats = state.stats;
          return ListView(
            padding: AppSpacing.screenAll,
            children: [
              // ── User Header ──
              Center(
                child: Column(
                  children: [
                    Container(
                      width: 72,
                      height: 72,
                      decoration: BoxDecoration(
                        gradient: AppGradients.primaryButton,
                        shape: BoxShape.circle,
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        (user?.username ?? '?')[0].toUpperCase(),
                        style: AppTextStyles.headlineLarge
                            .copyWith(color: Colors.white),
                      ),
                    ),
                    AppSpacing.vSm,
                    Text(user?.username ?? 'User',
                        style: AppTextStyles.titleLarge),
                    Text(user?.email ?? '',
                        style: AppTextStyles.bodySmall
                            .copyWith(color: AppColors.textTertiary)),
                    AppSpacing.vXs,
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 4),
                      decoration: BoxDecoration(
                        color: AppColors.accentGlow,
                        borderRadius: AppRadius.pill,
                      ),
                      child: Text(
                        user?.role.toUpperCase() ?? 'USER',
                        style: AppTextStyles.labelSmall
                            .copyWith(color: AppColors.accentLight),
                      ),
                    ),
                  ],
                ),
              ),
              AppSpacing.vXl,

              // ── Accuracy Donut ──
              _buildAccuracyChart(stats),
              AppSpacing.vLg,

              // ── Category Breakdown ──
              if (stats.categories.isNotEmpty) ...[
                Text('Category Breakdown', style: AppTextStyles.titleMedium),
                AppSpacing.vSm,
                ...stats.categories.map((c) => _buildCategoryBar(c)),
                AppSpacing.vLg,
              ],

              // ── Logout ──
              FSButton(
                label: 'Sign Out',
                variant: FSButtonVariant.danger,
                icon: Icons.logout,
                onPressed: () => authCubit.logout(),
              ),
              AppSpacing.vXl,
            ],
          );
        },
      ),
    );
  }

  Widget _buildAccuracyChart(UserStatsModel stats) {
    final correct = stats.totalCorrect.toDouble();
    final wrong = (stats.totalQuestionsAnswered - stats.totalCorrect).toDouble();
    final hasData = stats.totalQuestionsAnswered > 0;

    return Container(
      padding: AppSpacing.cardInnerLarge,
      decoration: BoxDecoration(
        color: AppColors.panel,
        border: Border.all(color: AppColors.border),
        borderRadius: AppRadius.mdAll,
      ),
      child: Column(
        children: [
          Text('Overall Accuracy', style: AppTextStyles.titleSmall),
          AppSpacing.vMd,
          SizedBox(
            height: 160,
            child: hasData
                ? PieChart(
                    PieChartData(
                      sectionsSpace: 3,
                      centerSpaceRadius: 40,
                      sections: [
                        PieChartSectionData(
                          value: correct,
                          color: AppColors.success,
                          title: '${stats.accuracy.toStringAsFixed(0)}%',
                          titleStyle: AppTextStyles.titleSmall
                              .copyWith(color: Colors.white, fontSize: 13),
                          radius: 35,
                        ),
                        PieChartSectionData(
                          value: wrong > 0 ? wrong : 0.01,
                          color: AppColors.error.withOpacity(0.4),
                          title: '',
                          radius: 28,
                        ),
                      ],
                    ),
                  )
                : Center(
                    child: Text(
                      'No data yet',
                      style: AppTextStyles.bodySmall
                          .copyWith(color: AppColors.textTertiary),
                    ),
                  ),
          ),
          AppSpacing.vSm,
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _legendDot(AppColors.success, 'Correct (${stats.totalCorrect})'),
              const SizedBox(width: 20),
              _legendDot(
                AppColors.error.withOpacity(0.4),
                'Wrong (${stats.totalQuestionsAnswered - stats.totalCorrect})',
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _legendDot(Color color, String label) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 10,
          height: 10,
          decoration: BoxDecoration(color: color, shape: BoxShape.circle),
        ),
        const SizedBox(width: 6),
        Text(label, style: AppTextStyles.caption),
      ],
    );
  }

  Widget _buildCategoryBar(CategoryBreakdownModel cat) {
    final pct =
        cat.attempts > 0 ? (cat.correct / cat.attempts * 100).round() : 0;
    final fill = cat.attempts > 0 ? cat.correct / cat.attempts : 0.0;

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(cat.category, style: AppTextStyles.bodySmall),
              Text(
                '$pct%  (${cat.correct}/${cat.attempts})',
                style: AppTextStyles.caption,
              ),
            ],
          ),
          const SizedBox(height: 4),
          ClipRRect(
            borderRadius: BorderRadius.circular(3),
            child: LinearProgressIndicator(
              value: fill,
              minHeight: 6,
              backgroundColor: AppColors.border,
              valueColor: AlwaysStoppedAnimation(
                pct >= 70
                    ? AppColors.success
                    : pct >= 40
                        ? AppColors.warning
                        : AppColors.error,
              ),
            ),
          ),
        ],
      ),
    );
  }
}