import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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_empty_state.dart';
import '../../../../core/widgets/fs_error_state.dart';
import '../../data/datasources/leaderboard_remote_datasource.dart';
import '../bloc/leaderboard_cubit.dart';
import '../bloc/leaderboard_state.dart';

class LeaderboardScreen extends StatefulWidget {
  const LeaderboardScreen({super.key});

  @override
  State<LeaderboardScreen> createState() => _LeaderboardScreenState();
}

class _LeaderboardScreenState extends State<LeaderboardScreen> {
  late final LeaderboardCubit _cubit;

  @override
  void initState() {
    super.initState();
    _cubit = LeaderboardCubit()..loadLeaderboard();
  }

  @override
  void dispose() {
    _cubit.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _cubit,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Leaderboard'),
          actions: [
            IconButton(
              icon: const Icon(Icons.refresh, size: 20),
              onPressed: () => _cubit.loadLeaderboard(),
            ),
          ],
        ),
        body: BlocBuilder<LeaderboardCubit, LeaderboardState>(
          builder: (context, state) {
            if (state is LeaderboardLoading) {
              return Padding(
                padding: AppSpacing.screenAll,
                child: FSShimmerList(itemCount: 8),
              );
            }

            if (state is LeaderboardError) {
              return FSErrorState(
                message: state.message,
                onRetry: () => _cubit.loadLeaderboard(),
              );
            }

            if (state is LeaderboardLoaded) {
              if (state.entries.isEmpty) {
                return const FSEmptyState(
                  icon: '🏆',
                  title: 'No Rankings Yet',
                  subtitle: 'Be the first to take a quiz and claim the top spot!',
                );
              }

              return RefreshIndicator(
                color: AppColors.accent,
                backgroundColor: AppColors.panel,
                onRefresh: () => _cubit.loadLeaderboard(),
                child: ListView.builder(
                  padding: AppSpacing.screenAll,
                  itemCount: state.entries.length + 1, // +1 for podium
                  itemBuilder: (context, index) {
                    if (index == 0) {
                      return _buildPodium(state.entries);
                    }
                    final entry = state.entries[index - 1];
                    final rank = index;
                    return _buildRow(entry, rank);
                  },
                ),
              );
            }

            return const SizedBox.shrink();
          },
        ),
      ),
    );
  }

  Widget _buildPodium(List<LeaderboardEntryModel> entries) {
    if (entries.length < 3) return const SizedBox.shrink();

    return Container(
      margin: const EdgeInsets.only(bottom: 20),
      padding: const EdgeInsets.symmetric(vertical: 24),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          // 2nd place
          _podiumItem(entries[1], 2, 80, AppColors.textSecondary),
          const SizedBox(width: 12),
          // 1st place
          _podiumItem(entries[0], 1, 110, AppColors.warning),
          const SizedBox(width: 12),
          // 3rd place
          _podiumItem(entries[2], 3, 60, AppColors.cyan),
        ],
      ),
    );
  }

  Widget _podiumItem(
      LeaderboardEntryModel entry, int rank, double height, Color accent) {
    final medals = ['', '🥇', '🥈', '🥉'];

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // Avatar
        Container(
          width: rank == 1 ? 56 : 44,
          height: rank == 1 ? 56 : 44,
          decoration: BoxDecoration(
            gradient: rank == 1
                ? AppGradients.primaryButton
                : LinearGradient(colors: [accent, accent.withOpacity(0.6)]),
            shape: BoxShape.circle,
            border: Border.all(
              color: accent.withOpacity(0.5),
              width: rank == 1 ? 3 : 2,
            ),
          ),
          alignment: Alignment.center,
          child: Text(
            entry.username.isNotEmpty
                ? entry.username[0].toUpperCase()
                : '?',
            style: AppTextStyles.titleMedium.copyWith(
              color: Colors.white,
              fontSize: rank == 1 ? 20 : 16,
            ),
          ),
        ),
        const SizedBox(height: 6),
        Text(medals[rank], style: const TextStyle(fontSize: 18)),
        const SizedBox(height: 4),
        Text(
          entry.username,
          style: AppTextStyles.labelMedium,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        Text(
          '${entry.totalScore} pts',
          style: AppTextStyles.caption.copyWith(color: accent),
        ),
        const SizedBox(height: 8),
        // Podium block
        Container(
          width: 80,
          height: height,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [accent.withOpacity(0.3), accent.withOpacity(0.08)],
            ),
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(8),
              topRight: Radius.circular(8),
            ),
            border: Border.all(color: accent.withOpacity(0.2)),
          ),
          alignment: Alignment.center,
          child: Text(
            '#$rank',
            style: AppTextStyles.headlineMedium.copyWith(
              color: accent.withOpacity(0.6),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildRow(LeaderboardEntryModel entry, int rank) {
    final isTop3 = rank <= 3;

    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
      decoration: BoxDecoration(
        color: isTop3
            ? AppColors.accentGlow
            : AppColors.panel,
        border: Border.all(
          color: isTop3 ? AppColors.accent.withOpacity(0.2) : AppColors.border,
        ),
        borderRadius: AppRadius.smAll,
      ),
      child: Row(
        children: [
          // Rank
          SizedBox(
            width: 32,
            child: Text(
              '#$rank',
              style: AppTextStyles.titleSmall.copyWith(
                color: isTop3 ? AppColors.warningLight : AppColors.textTertiary,
                fontWeight: FontWeight.w800,
              ),
            ),
          ),
          const SizedBox(width: 10),

          // Avatar
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(
              color: AppColors.panelLight,
              shape: BoxShape.circle,
            ),
            alignment: Alignment.center,
            child: Text(
              entry.username.isNotEmpty
                  ? entry.username[0].toUpperCase()
                  : '?',
              style: AppTextStyles.labelLarge.copyWith(
                color: AppColors.accentLight,
              ),
            ),
          ),
          const SizedBox(width: 12),

          // Name + stats
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(entry.username, style: AppTextStyles.titleSmall),
                Text(
                  '${entry.quizzesTaken} quizzes · avg ${entry.avgScore}%',
                  style: AppTextStyles.caption,
                ),
              ],
            ),
          ),

          // Score
          Text(
            '${entry.totalScore}',
            style: AppTextStyles.titleMedium.copyWith(
              color: AppColors.accentLight,
              fontWeight: FontWeight.w800,
            ),
          ),
          const SizedBox(width: 4),
          Text('pts', style: AppTextStyles.caption),
        ],
      ),
    );
  }
}