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

import '../../core/theme/app_theme.dart';
import '../auth/auth_cubit.dart';
import 'wallet.dart';
import 'wallet_cubit.dart';

/// لابی اصلی: کیف‌پول، دکمه بازی، سکه روزانه.
class LobbyScreen extends StatefulWidget {
  const LobbyScreen({super.key});

  @override
  State<LobbyScreen> createState() => _LobbyScreenState();
}

class _LobbyScreenState extends State<LobbyScreen> {
  @override
  void initState() {
    super.initState();
    context.read<WalletCubit>().load();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: BlocBuilder<WalletCubit, WalletState>(
          builder: (context, state) {
            return Column(
              children: [
                _TopBar(wallet: state.wallet),
                Expanded(
                  child: Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Text('سلطان حکم',
                            style: TextStyle(
                                fontSize: 40,
                                fontWeight: FontWeight.bold,
                                color: AppColors.gold)),
                        const SizedBox(height: 48),
                        _MenuButton(
                          label: 'بازی',
                          icon: Icons.style,
                          color: const Color(0xFF8E1B5B),
                          onTap: () async {
                            await context.push('/game/tiers');
                            if (context.mounted) {
                              context.read<WalletCubit>().load();
                            }
                          },
                        ),
                        const SizedBox(height: 16),
                        _MenuButton(
                          label: 'فروشگاه',
                          icon: Icons.storefront,
                          color: const Color(0xFF4A148C),
                          onTap: () async {
                            await context.push('/shop');
                            if (context.mounted) {
                              context.read<WalletCubit>().load();
                            }
                          },
                        ),
                        const SizedBox(height: 16),
                        _MenuButton(
                          label: 'سکه روزانه',
                          icon: Icons.monetization_on,
                          color: AppColors.green,
                          onTap: () => _claimDaily(context),
                        ),
                      ],
                    ),
                  ),
                ),
                TextButton.icon(
                  onPressed: () async {
                    await context.read<AuthCubit>().logout();
                    if (context.mounted) context.go('/login');
                  },
                  icon: const Icon(Icons.logout, color: Colors.white54),
                  label: const Text('خروج',
                      style: TextStyle(color: Colors.white54)),
                ),
                const SizedBox(height: 8),
              ],
            );
          },
        ),
      ),
    );
  }

  Future<void> _claimDaily(BuildContext context) async {
    final amount = await context.read<WalletCubit>().claimDaily();
    if (!context.mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(amount != null
            ? 'سکه روزانه دریافت شد: +$amount'
            : 'سکه روزانه را قبلاً امروز گرفته‌اید'),
      ),
    );
  }
}

class _TopBar extends StatelessWidget {
  final Wallet? wallet;
  const _TopBar({this.wallet});

  @override
  Widget build(BuildContext context) {
    final w = wallet;
    return Container(
      margin: const EdgeInsets.all(8),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      decoration: BoxDecoration(
        color: AppColors.bgDark,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: AppColors.goldDark),
      ),
      child: Row(
        children: [
          const CircleAvatar(
            backgroundColor: AppColors.panel,
            child: Icon(Icons.person, color: AppColors.gold),
          ),
          const SizedBox(width: 10),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('سطح ${w?.level ?? '-'}',
                  style: const TextStyle(color: AppColors.gold)),
              if (w != null)
                SizedBox(
                  width: 90,
                  child: LinearProgressIndicator(
                    value: w.xpForNext == 0 ? 0 : w.xpIntoLevel / w.xpForNext,
                    backgroundColor: Colors.white12,
                    color: AppColors.gold,
                    minHeight: 5,
                  ),
                ),
            ],
          ),
          const Spacer(),
          _Chip(icon: Icons.confirmation_number, value: w?.tickets ?? 0),
          const SizedBox(width: 8),
          _Chip(icon: Icons.monetization_on, value: w?.coins ?? 0),
        ],
      ),
    );
  }
}

class _Chip extends StatelessWidget {
  final IconData icon;
  final int value;
  const _Chip({required this.icon, required this.value});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      decoration: BoxDecoration(
        color: AppColors.panel,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: AppColors.goldDark),
      ),
      child: Row(
        children: [
          Icon(icon, color: AppColors.gold, size: 18),
          const SizedBox(width: 6),
          Text('$value', style: const TextStyle(color: AppColors.text)),
        ],
      ),
    );
  }
}

class _MenuButton extends StatelessWidget {
  final String label;
  final IconData icon;
  final Color color;
  final VoidCallback onTap;
  const _MenuButton({
    required this.label,
    required this.icon,
    required this.color,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    // رنگِ تیره‌ترِ پایه برای بِوِل (لبه‌ی پایینیِ برجسته).
    final dark = Color.lerp(color, Colors.black, 0.45)!;
    final light = Color.lerp(color, Colors.white, 0.12)!;
    return SizedBox(
      width: 280,
      child: Material(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(16),
        child: InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: onTap,
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 15),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [light, color, dark],
                stops: const [0, 0.5, 1],
              ),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: AppColors.gold, width: 1.6),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.55),
                  blurRadius: 10,
                  offset: const Offset(0, 5),
                ),
                // هایلایتِ بالا برای حسِ شیشه‌ای/برجسته.
                BoxShadow(
                  color: Colors.white.withValues(alpha: 0.12),
                  blurRadius: 1,
                  offset: const Offset(0, 1),
                  spreadRadius: -1,
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(icon, color: AppColors.gold),
                const SizedBox(width: 10),
                Text(label,
                    style: const TextStyle(
                      color: AppColors.text,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      shadows: [Shadow(color: Colors.black54, blurRadius: 3)],
                    )),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
