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

import '../../../../core/theme/app_theme.dart';
import '../../../../core/widgets/game_ui.dart';
import '../bloc/private_info_bloc.dart';

/// صفحه‌ی دورهمی: پیوستن با شماره میز یا ساختِ میز جدید.
class PrivateEntryScreen extends StatefulWidget {
  const PrivateEntryScreen({super.key});

  @override
  State<PrivateEntryScreen> createState() => _PrivateEntryScreenState();
}

class _PrivateEntryScreenState extends State<PrivateEntryScreen> {
  final _code = TextEditingController();

  @override
  void initState() {
    super.initState();
    context.read<PrivateInfoBloc>().add(LoadTablesInfoEvent());
  }

  @override
  void dispose() {
    _code.dispose();
    super.dispose();
  }

  void _join() {
    final code = _code.text.trim();
    if (code.length < 4) return;
    context.push('/private/room?join=$code');
  }

  void _create(bool canCreate) {
    if (!canCreate) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content:
              Text('سهمیه‌ی میزهای رایگان تمام شده؛ با VIP نامحدود بسازید')));
      return;
    }
    context.push('/private/room?create=1').then((_) {
      if (mounted) {
        context.read<PrivateInfoBloc>().add(LoadTablesInfoEvent());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GameBackground(
        child: SafeArea(
          child: BlocBuilder<PrivateInfoBloc, PrivateInfoState>(
            builder: (context, state) {
              final loading = state is! PrivateInfoLoaded;
              final unlimited =
                  state is PrivateInfoLoaded && state.info.unlimited;
              final remaining =
                  state is PrivateInfoLoaded ? state.info.remaining : 0;
              final canCreate = unlimited || remaining > 0;
              return Column(
                children: [
                  const Align(
                    alignment: Alignment.centerRight,
                    child: Padding(
                      padding: EdgeInsets.all(10),
                      child: AppBackButton(),
                    ),
                  ),
                  Expanded(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.symmetric(horizontal: 24),
                      child: Column(
                        children: [
                          const SizedBox(height: 8),
                          const Icon(Icons.person,
                              color: AppColors.gold, size: 56),
                          const SizedBox(height: 12),
                          TextField(
                            controller: _code,
                            textAlign: TextAlign.center,
                            keyboardType: TextInputType.number,
                            style: const TextStyle(
                                fontSize: 22, letterSpacing: 6),
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                              LengthLimitingTextInputFormatter(5),
                            ],
                            decoration:
                                const InputDecoration(hintText: 'شماره میز'),
                            onChanged: (_) => setState(() {}),
                          ),
                          const SizedBox(height: 16),
                          GameButton(
                            label: 'پیوستن',
                            width: double.infinity,
                            colors: const [Color(0xFFC2185B), Color(0xFF6A0D38)],
                            onTap: _code.text.trim().length >= 4 ? _join : null,
                          ),
                          const SizedBox(height: 8),
                          const Text('برای ورود، شماره میز را وارد کنید.',
                              style: TextStyle(
                                  color: Colors.white60, fontSize: 13)),
                          const SizedBox(height: 24),
                          Divider(
                              color: AppColors.goldDark.withValues(alpha: 0.5)),
                          const SizedBox(height: 16),
                          Text(
                            loading
                                ? '...'
                                : unlimited
                                    ? 'میزهای نامحدود (VIP)'
                                    : 'میزهای رایگان باقیمانده: $remaining',
                            style: const TextStyle(
                                color: AppColors.gold,
                                fontSize: 14,
                                fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(height: 12),
                          const Icon(Icons.groups,
                              color: AppColors.gold, size: 56),
                          const SizedBox(height: 12),
                          GameButton(
                            label: 'ساخت میز',
                            width: double.infinity,
                            colors: canCreate
                                ? const [Color(0xFFC2185B), Color(0xFF6A0D38)]
                                : const [Color(0xFF555555), Color(0xFF333333)],
                            onTap: loading ? null : () => _create(canCreate),
                          ),
                          const SizedBox(height: 8),
                          const Text('میز جدید بساز و دوستانت را دعوت کن',
                              style: TextStyle(
                                  color: Colors.white60, fontSize: 13)),
                          const SizedBox(height: 24),
                        ],
                      ),
                    ),
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }
}
