import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../core/api/api_client.dart';
import '../../core/api/api_service.dart';
import '../../core/l10n/app_localizations.dart';
import '../../core/theme/app_theme.dart';

class RegistrationScreen extends ConsumerStatefulWidget {
  const RegistrationScreen({super.key});

  @override
  ConsumerState<RegistrationScreen> createState() => _RegistrationScreenState();
}

class _RegistrationScreenState extends ConsumerState<RegistrationScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameArController = TextEditingController();
  final _nameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _emailController = TextEditingController();
  final _childNameController = TextEditingController();
  final _childAgeController = TextEditingController();
  String _gender = 'male';
  bool _isLoading = false;
  String? _error;
  int _step = 0;

  @override
  void dispose() {
    _nameArController.dispose();
    _nameController.dispose();
    _phoneController.dispose();
    _emailController.dispose();
    _childNameController.dispose();
    _childAgeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final l = AppLocalizations.of(context);

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        surfaceTintColor: Colors.transparent,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new, size: 18),
          onPressed: () {
            if (_step > 0) {
              setState(() => _step--);
            } else {
              context.pop();
            }
          },
        ),
        title: Text(l.t('pre_register')),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Column(
          children: [
            // Progress indicator
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 16),
              child: Row(
                children: List.generate(3, (i) {
                  return Expanded(
                    child: Container(
                      height: 4,
                      margin: const EdgeInsets.symmetric(horizontal: 3),
                      decoration: BoxDecoration(
                        color: i <= _step ? AppTheme.primaryColor : Colors.grey.shade200,
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                  );
                }),
              ).animate().fadeIn(duration: 300.ms),
            ),
            // Form
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.symmetric(horizontal: 28),
                child: Form(
                  key: _formKey,
                  child: AnimatedSwitcher(
                    duration: 300.ms,
                    transitionBuilder: (child, anim) {
                      return FadeTransition(
                        opacity: anim,
                        child: SlideTransition(
                          position: Tween(
                            begin: const Offset(0.05, 0),
                            end: Offset.zero,
                          ).animate(anim),
                          child: child,
                        ),
                      );
                    },
                    child: _buildStep(l),
                  ),
                ),
              ),
            ),
            // Bottom button
            Padding(
              padding: EdgeInsets.only(
                left: 28,
                right: 28,
                bottom: MediaQuery.paddingOf(context).bottom + 16,
              ),
              child: Column(
                children: [
                  if (_error != null)
                    Padding(
                      padding: const EdgeInsets.only(bottom: 12),
                      child: Text(
                        _error!,
                        style: const TextStyle(color: Colors.red, fontSize: 13),
                      ).animate().shake(duration: 400.ms),
                    ),
                  SizedBox(
                    width: double.infinity,
                    height: 52,
                    child: ElevatedButton(
                      onPressed: _isLoading ? null : _next,
                      child: _isLoading
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2.5),
                            )
                          : Text(
                              _step == 2 ? l.t('submit') : l.t('next'),
                              style: const TextStyle(fontSize: 16),
                            ),
                    ),
                  ),
                ],
              ),
            ).animate(delay: 200.ms).fadeIn(duration: 400.ms),
          ],
        ),
      ),
    );
  }

  Widget _buildStep(AppLocalizations l) {
    switch (_step) {
      case 0:
        return Column(
          key: const ValueKey(0),
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 20),
            Text(l.t('guardian_info'), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Text(
              'بيانات ولي الأمر',
              style: TextStyle(fontSize: 14, color: Colors.grey.shade500),
            ),
            const SizedBox(height: 28),
            _buildField(
              controller: _nameArController,
              label: 'الاسم بالعربي',
              icon: Icons.person,
              required: true,
            ),
            const SizedBox(height: 14),
            _buildField(
              controller: _nameController,
              label: 'Name in English',
              icon: Icons.person_outline,
            ),
            const SizedBox(height: 14),
            Directionality(
              textDirection: TextDirection.ltr,
              child: _buildField(
                controller: _phoneController,
                label: 'رقم الهاتف',
                icon: Icons.phone,
                required: true,
                keyboardType: TextInputType.phone,
                formatters: [FilteringTextInputFormatter.allow(RegExp(r'[0-9+]'))],
              ),
            ),
            const SizedBox(height: 14),
            _buildField(
              controller: _emailController,
              label: 'البريد الإلكتروني (اختياري)',
              icon: Icons.email,
              keyboardType: TextInputType.emailAddress,
            ),
          ],
        );
      case 1:
        return Column(
          key: const ValueKey(1),
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 20),
            Text(l.t('child_info'), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Text(
              'بيانات المشترك',
              style: TextStyle(fontSize: 14, color: Colors.grey.shade500),
            ),
            const SizedBox(height: 28),
            _buildField(
              controller: _childNameController,
              label: 'اسم المشترك',
              icon: Icons.child_care,
              required: true,
            ),
            const SizedBox(height: 14),
            Directionality(
              textDirection: TextDirection.ltr,
              child: _buildField(
                controller: _childAgeController,
                label: 'العمر',
                icon: Icons.cake,
                required: true,
                keyboardType: TextInputType.number,
                formatters: [FilteringTextInputFormatter.digitsOnly],
              ),
            ),
            const SizedBox(height: 14),
            // Gender selector
            Text('الجنس', style: TextStyle(fontSize: 14, color: Colors.grey.shade600)),
            const SizedBox(height: 10),
            Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () => setState(() => _gender = 'male'),
                    child: AnimatedContainer(
                      duration: 200.ms,
                      padding: const EdgeInsets.symmetric(vertical: 14),
                      decoration: BoxDecoration(
                        color: _gender == 'male'
                            ? AppTheme.primaryColor.withValues(alpha: 0.1)
                            : const Color(0xFFF1F5F9),
                        borderRadius: BorderRadius.circular(12),
                        border: _gender == 'male'
                            ? Border.all(color: AppTheme.primaryColor)
                            : Border.all(color: Colors.transparent),
                      ),
                      child: Center(
                        child: Text(
                          'ذكر',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: _gender == 'male' ? AppTheme.primaryColor : Colors.grey.shade600,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: GestureDetector(
                    onTap: () => setState(() => _gender = 'female'),
                    child: AnimatedContainer(
                      duration: 200.ms,
                      padding: const EdgeInsets.symmetric(vertical: 14),
                      decoration: BoxDecoration(
                        color: _gender == 'female'
                            ? Colors.pink.withValues(alpha: 0.1)
                            : const Color(0xFFF1F5F9),
                        borderRadius: BorderRadius.circular(12),
                        border: _gender == 'female'
                            ? Border.all(color: Colors.pink)
                            : Border.all(color: Colors.transparent),
                      ),
                      child: Center(
                        child: Text(
                          'أنثى',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: _gender == 'female' ? Colors.pink : Colors.grey.shade600,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        );
      case 2:
        return Column(
          key: const ValueKey(2),
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 20),
            Text(l.t('review'), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Text(
              'تأكيد البيانات',
              style: TextStyle(fontSize: 14, color: Colors.grey.shade500),
            ),
            const SizedBox(height: 28),
            _ReviewRow(label: 'ولي الأمر', value: _nameArController.text),
            _ReviewRow(label: 'الهاتف', value: _phoneController.text),
            if (_emailController.text.isNotEmpty)
              _ReviewRow(label: 'البريد', value: _emailController.text),
            const Divider(height: 24),
            _ReviewRow(label: 'المشترك', value: _childNameController.text),
            _ReviewRow(label: 'العمر', value: _childAgeController.text),
            _ReviewRow(label: 'الجنس', value: _gender == 'male' ? 'ذكر' : 'أنثى'),
            const SizedBox(height: 20),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(
                color: Colors.amber.shade50,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.amber.shade200),
              ),
              child: Row(
                children: [
                  Icon(Icons.info_outline, color: Colors.amber.shade700, size: 20),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Text(
                      'يرجى الحضور للمقر لإتمام التسجيل والدفع',
                      style: TextStyle(fontSize: 13, color: Colors.amber.shade800),
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      default:
        return const SizedBox.shrink();
    }
  }

  Widget _buildField({
    required TextEditingController controller,
    required String label,
    required IconData icon,
    bool required = false,
    TextInputType? keyboardType,
    List<TextInputFormatter>? formatters,
  }) {
    return TextFormField(
      controller: controller,
      keyboardType: keyboardType,
      inputFormatters: formatters,
      decoration: InputDecoration(
        labelText: label,
        prefixIcon: Icon(icon, size: 20),
        filled: true,
        fillColor: const Color(0xFFF1F5F9),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: AppTheme.primaryColor, width: 1.5),
        ),
      ),
      validator: required ? (v) => (v == null || v.isEmpty) ? '' : null : null,
    );
  }

  void _next() {
    setState(() => _error = null);

    if (_step == 0) {
      if (_nameArController.text.isEmpty || _phoneController.text.isEmpty) {
        setState(() => _error = 'يرجى ملء الحقول المطلوبة');
        return;
      }
      setState(() => _step = 1);
    } else if (_step == 1) {
      if (_childNameController.text.isEmpty || _childAgeController.text.isEmpty) {
        setState(() => _error = 'يرجى ملء الحقول المطلوبة');
        return;
      }
      setState(() => _step = 2);
    } else {
      _submit();
    }
  }

  Future<void> _submit() async {
    setState(() => _isLoading = true);
    try {
      await ref.read(apiServiceProvider).preRegister(
        guardianNameAr: _nameArController.text,
        guardianName: _nameController.text,
        phone: _phoneController.text,
        email: _emailController.text,
        participantName: _childNameController.text,
        participantAge: int.tryParse(_childAgeController.text) ?? 0,
        gender: _gender,
      );
      if (mounted) {
        _showSuccess();
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _error = e is ApiException ? e.message : 'حدث خطأ';
      });
    }
  }

  void _showSuccess() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (ctx) => Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        child: Padding(
          padding: const EdgeInsets.all(28),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 70,
                height: 70,
                decoration: BoxDecoration(
                  color: Colors.green.shade50,
                  shape: BoxShape.circle,
                ),
                child: Icon(Icons.check_circle, size: 40, color: Colors.green.shade600),
              ).animate().scale(
                    begin: const Offset(0.5, 0.5),
                    end: const Offset(1, 1),
                    duration: 500.ms,
                    curve: Curves.easeOutBack,
                  ),
              const SizedBox(height: 20),
              const Text(
                'تم التسجيل بنجاح!',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 8),
              Text(
                'يرجى الحضور للمقر لإتمام التسجيل',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 14, color: Colors.grey.shade600),
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () {
                    Navigator.pop(ctx);
                    context.go('/auth/login');
                  },
                  child: const Text('حسناً'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _ReviewRow extends StatelessWidget {
  final String label;
  final String value;

  const _ReviewRow({required this.label, required this.value});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: Row(
        children: [
          SizedBox(
            width: 80,
            child: Text(label, style: TextStyle(fontSize: 13, color: Colors.grey.shade500)),
          ),
          Expanded(
            child: Text(value, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
          ),
        ],
      ),
    );
  }
}
