import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../services/api_service.dart';
import '../../widgets/gradient_mesh.dart';
import '../../widgets/glass_card.dart';

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

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  final _nameCtrl = TextEditingController();
  final _emailCtrl = TextEditingController();
  final _passCtrl = TextEditingController();
  final _confirmPassCtrl = TextEditingController();
  final _nameFocus = FocusNode();
  final _emailFocus = FocusNode();
  final _passFocus = FocusNode();
  final _confirmPassFocus = FocusNode();
  String _country = 'US';
  bool _loading = false;
  String? _error;
  bool _obscure = true;
  bool _obscureConfirm = true;
  bool _acceptedTerms = false;

  // Live validation state
  bool _nameValid = false;
  bool _emailValid = false;
  int _passStrength = 0; // 0-4
  bool _passMatch = false;
  bool _showPassTips = false;

  static const _countries = [
    ('US', 'United States'), ('GB', 'United Kingdom'), ('CA', 'Canada'),
    ('AU', 'Australia'), ('DE', 'Germany'), ('FR', 'France'),
    ('IN', 'India'), ('BR', 'Brazil'), ('JP', 'Japan'), ('ZA', 'South Africa'),
    ('NG', 'Nigeria'), ('KE', 'Kenya'), ('AE', 'UAE'), ('SA', 'Saudi Arabia'),
    ('EG', 'Egypt'), ('MX', 'Mexico'), ('PH', 'Philippines'), ('PK', 'Pakistan'),
    ('BD', 'Bangladesh'), ('ID', 'Indonesia'),
  ];

  @override
  void initState() {
    super.initState();
    _nameCtrl.addListener(_validateName);
    _emailCtrl.addListener(_validateEmail);
    _passCtrl.addListener(_validatePassword);
    _confirmPassCtrl.addListener(_validateConfirm);
    _passFocus.addListener(() {
      setState(() => _showPassTips = _passFocus.hasFocus);
    });
  }

  void _validateName() {
    setState(() => _nameValid = _nameCtrl.text.trim().length >= 2);
  }

  void _validateEmail() {
    final e = _emailCtrl.text.trim();
    setState(() => _emailValid = RegExp(r'^[\w\.\-]+@[\w\.\-]+\.\w{2,}$').hasMatch(e));
  }

  void _validatePassword() {
    final p = _passCtrl.text;
    int strength = 0;
    if (p.length >= 8) strength++;
    if (RegExp(r'[A-Z]').hasMatch(p)) strength++;
    if (RegExp(r'[0-9]').hasMatch(p)) strength++;
    if (RegExp(r'[!@#\$%\^&\*\(\)_\+\-=\[\]\{\};:,\.<>\?/\\|]').hasMatch(p)) strength++;
    setState(() => _passStrength = strength);
    _validateConfirm();
  }

  void _validateConfirm() {
    setState(() => _passMatch = _confirmPassCtrl.text.isNotEmpty && _confirmPassCtrl.text == _passCtrl.text);
  }

  bool get _formReady => _nameValid && _emailValid && _passStrength >= 2 && _passMatch && _acceptedTerms;

  Future<void> _register() async {
    if (!_formReady) {
      setState(() => _error = _buildFormError());
      return;
    }
    setState(() { _loading = true; _error = null; });
    try {
      final provider = context.read<AppProvider>();
      await provider.auth.register(
        email: _emailCtrl.text.trim(),
        password: _passCtrl.text,
        name: _nameCtrl.text.trim(),
        country: _country,
      );
      if (!mounted) return;
      Navigator.of(context).pushReplacementNamed('/home');
    } on ApiException catch (e) {
      setState(() => _error = e.message);
    } catch (e) {
      setState(() => _error = 'Connection error. Please try again.');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  String _buildFormError() {
    if (!_nameValid) return 'Name must be at least 2 characters';
    if (!_emailValid) return 'Please enter a valid email address';
    if (_passStrength < 2) return 'Password is too weak. See tips below.';
    if (!_passMatch) return 'Passwords do not match';
    if (!_acceptedTerms) return 'Please accept the Terms of Service';
    return 'Please fill in all fields';
  }

  @override
  void dispose() {
    _nameCtrl.dispose();
    _emailCtrl.dispose();
    _passCtrl.dispose();
    _confirmPassCtrl.dispose();
    _nameFocus.dispose();
    _emailFocus.dispose();
    _passFocus.dispose();
    _confirmPassFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      body: Stack(
        children: [
          const Positioned.fill(child: GradientMesh()),
          SafeArea(
            child: Center(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 72,
                      height: 72,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(color: AppColors.royalBlue.withValues(alpha: 0.3), blurRadius: 30),
                        ],
                      ),
                      child: ClipOval(
                        child: Image.asset('assets/icon/reasonabledoubt-icon.png', fit: BoxFit.cover),
                      ),
                    ),
                    const SizedBox(height: 20),
                    Text('Create Account', style: AppTypography.displayLg.copyWith(color: Colors.white)),
                    const SizedBox(height: 8),
                    Text('Your AI legal assistant awaits', style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary)),
                    const SizedBox(height: 32),
                    GlassCard(
                      padding: const EdgeInsets.all(24),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          // Full Name
                          _buildTextField(
                            ctrl: _nameCtrl,
                            focus: _nameFocus,
                            nextFocus: _emailFocus,
                            label: 'Full Name',
                            hint: 'e.g. John Doe',
                            icon: Icons.person_rounded,
                            isValid: _nameCtrl.text.isNotEmpty ? _nameValid : null,
                            helperText: 'How we\'ll address you in consultations',
                          ),
                          const SizedBox(height: 16),

                          // Email
                          _buildTextField(
                            ctrl: _emailCtrl,
                            focus: _emailFocus,
                            nextFocus: _passFocus,
                            label: 'Email Address',
                            hint: 'your.email@example.com',
                            icon: Icons.email_rounded,
                            type: TextInputType.emailAddress,
                            isValid: _emailCtrl.text.isNotEmpty ? _emailValid : null,
                            helperText: 'We\'ll use this for login & account recovery',
                          ),
                          const SizedBox(height: 16),

                          // Password
                          _buildTextField(
                            ctrl: _passCtrl,
                            focus: _passFocus,
                            nextFocus: _confirmPassFocus,
                            label: 'Password',
                            hint: 'Min. 8 characters, mix letters & numbers',
                            icon: Icons.lock_rounded,
                            obscure: _obscure,
                            suffix: IconButton(
                              icon: Icon(_obscure ? Icons.visibility_off_rounded : Icons.visibility_rounded, color: AppColors.textMuted, size: 20),
                              onPressed: () => setState(() => _obscure = !_obscure),
                            ),
                            isValid: _passCtrl.text.isNotEmpty ? _passStrength >= 2 : null,
                          ),

                          // Password strength bar
                          if (_passCtrl.text.isNotEmpty) ...[
                            const SizedBox(height: 8),
                            _buildStrengthBar(),
                          ],

                          // Password tips (show when focused or weak)
                          if (_showPassTips || (_passCtrl.text.isNotEmpty && _passStrength < 3))
                            _buildPasswordTips(),

                          const SizedBox(height: 16),

                          // Confirm password
                          _buildTextField(
                            ctrl: _confirmPassCtrl,
                            focus: _confirmPassFocus,
                            label: 'Confirm Password',
                            hint: 'Re-type your password',
                            icon: Icons.lock_outline_rounded,
                            obscure: _obscureConfirm,
                            suffix: IconButton(
                              icon: Icon(_obscureConfirm ? Icons.visibility_off_rounded : Icons.visibility_rounded, color: AppColors.textMuted, size: 20),
                              onPressed: () => setState(() => _obscureConfirm = !_obscureConfirm),
                            ),
                            isValid: _confirmPassCtrl.text.isNotEmpty ? _passMatch : null,
                          ),
                          if (_confirmPassCtrl.text.isNotEmpty && !_passMatch)
                            Padding(
                              padding: const EdgeInsets.only(top: 4, left: 4),
                              child: Text('Passwords don\'t match', style: AppTypography.bodySm.copyWith(color: AppColors.error, fontSize: 11)),
                            ),
                          const SizedBox(height: 16),

                          // Country picker
                          Text('Country', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted, fontWeight: FontWeight.w500)),
                          const SizedBox(height: 6),
                          Container(
                            decoration: BoxDecoration(
                              color: AppColors.glassSurface,
                              borderRadius: BorderRadius.circular(14),
                              border: Border.all(color: AppColors.glassBorder),
                            ),
                            child: DropdownButtonFormField<String>(
                              value: _country,
                              dropdownColor: AppColors.navy,
                              decoration: InputDecoration(
                                prefixIcon: Icon(Icons.public_rounded, color: AppColors.textMuted, size: 20),
                                border: InputBorder.none,
                                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
                              ),
                              style: AppTypography.bodyMd.copyWith(color: Colors.white),
                              items: _countries.map((c) => DropdownMenuItem(value: c.$1, child: Text(c.$2))).toList(),
                              onChanged: (v) => setState(() => _country = v ?? 'US'),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(top: 4, left: 4),
                            child: Text('We\'ll customize legal info for your jurisdiction',
                                style: AppTypography.bodySm.copyWith(color: AppColors.textMuted, fontSize: 11)),
                          ),
                          const SizedBox(height: 16),

                          // Terms checkbox
                          GestureDetector(
                            onTap: () => setState(() => _acceptedTerms = !_acceptedTerms),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                AnimatedContainer(
                                  duration: const Duration(milliseconds: 200),
                                  width: 22,
                                  height: 22,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(6),
                                    color: _acceptedTerms ? AppColors.royalBlue : Colors.transparent,
                                    border: Border.all(
                                      color: _acceptedTerms ? AppColors.royalBlue : AppColors.glassBorder,
                                      width: 2,
                                    ),
                                  ),
                                  child: _acceptedTerms ? const Icon(Icons.check, size: 14, color: Colors.white) : null,
                                ),
                                const SizedBox(width: 10),
                                Expanded(
                                  child: Text.rich(
                                    TextSpan(
                                      text: 'I agree to the ',
                                      style: AppTypography.bodySm.copyWith(color: AppColors.textSecondary),
                                      children: [
                                        WidgetSpan(
                                          child: GestureDetector(
                                            onTap: () => Navigator.pushNamed(context, '/terms'),
                                            child: Text('Terms of Service', style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue)),
                                          ),
                                        ),
                                        TextSpan(text: ' and '),
                                        WidgetSpan(
                                          child: GestureDetector(
                                            onTap: () => Navigator.pushNamed(context, '/privacy'),
                                            child: Text('Privacy Policy', style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue)),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),

                          if (_error != null) ...[
                            const SizedBox(height: 12),
                            Container(
                              padding: const EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                color: AppColors.error.withValues(alpha: 0.1),
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: Row(
                                children: [
                                  Icon(Icons.error_outline_rounded, color: AppColors.error, size: 16),
                                  const SizedBox(width: 8),
                                  Expanded(child: Text(_error!, style: AppTypography.bodySm.copyWith(color: AppColors.error))),
                                ],
                              ),
                            ),
                          ],
                          const SizedBox(height: 20),

                          // Register button
                          GestureDetector(
                            onTap: _loading ? null : _register,
                            child: AnimatedContainer(
                              duration: const Duration(milliseconds: 200),
                              height: 52,
                              decoration: BoxDecoration(
                                gradient: LinearGradient(colors: _formReady
                                    ? [AppColors.royalBlue, AppColors.royalBlue.withValues(alpha: 0.8)]
                                    : [AppColors.glassSurface, AppColors.glassSurface]),
                                borderRadius: BorderRadius.circular(14),
                                boxShadow: _formReady
                                    ? [BoxShadow(color: AppColors.royalBlue.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(0, 6))]
                                    : [],
                              ),
                              child: Center(
                                child: _loading
                                    ? const SizedBox(width: 22, height: 22, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2.5))
                                    : Text('Create Account', style: AppTypography.button.copyWith(
                                        color: _formReady ? Colors.white : AppColors.textMuted)),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 24),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('Already have an account? ', style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted)),
                        GestureDetector(
                          onTap: () => Navigator.of(context).pushReplacementNamed('/login'),
                          child: Text('Sign In', style: AppTypography.button.copyWith(color: AppColors.royalBlue)),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTextField({
    required TextEditingController ctrl,
    required FocusNode focus,
    FocusNode? nextFocus,
    required String label,
    required String hint,
    required IconData icon,
    TextInputType? type,
    bool obscure = false,
    Widget? suffix,
    bool? isValid,
    String? helperText,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: AppTypography.bodySm.copyWith(color: AppColors.textMuted, fontWeight: FontWeight.w500)),
        const SizedBox(height: 6),
        Container(
          decoration: BoxDecoration(
            color: AppColors.glassSurface,
            borderRadius: BorderRadius.circular(14),
            border: Border.all(
              color: isValid == true
                  ? AppColors.success.withValues(alpha: 0.5)
                  : isValid == false
                      ? AppColors.error.withValues(alpha: 0.5)
                      : focus.hasFocus
                          ? AppColors.royalBlue.withValues(alpha: 0.5)
                          : AppColors.glassBorder,
            ),
          ),
          child: TextField(
            controller: ctrl,
            focusNode: focus,
            keyboardType: type,
            obscureText: obscure,
            textInputAction: nextFocus != null ? TextInputAction.next : TextInputAction.done,
            onSubmitted: (_) => nextFocus?.requestFocus(),
            style: AppTypography.bodyMd.copyWith(color: Colors.white),
            decoration: InputDecoration(
              hintText: hint,
              hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted.withValues(alpha: 0.5)),
              prefixIcon: Icon(icon, color: AppColors.textMuted, size: 20),
              suffixIcon: suffix ?? (isValid == true
                  ? const Icon(Icons.check_circle_rounded, color: AppColors.success, size: 18)
                  : null),
              border: InputBorder.none,
              contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
            ),
          ),
        ),
        if (helperText != null)
          Padding(
            padding: const EdgeInsets.only(top: 4, left: 4),
            child: Text(helperText, style: AppTypography.bodySm.copyWith(color: AppColors.textMuted, fontSize: 11)),
          ),
      ],
    );
  }

  Widget _buildStrengthBar() {
    const labels = ['', 'Weak', 'Fair', 'Good', 'Strong'];
    const colors = [AppColors.error, AppColors.error, AppColors.warning, AppColors.success, AppColors.success];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: List.generate(4, (i) {
            return Expanded(
              child: Container(
                height: 3,
                margin: EdgeInsets.only(right: i < 3 ? 4 : 0),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(2),
                  color: i < _passStrength ? colors[_passStrength] : AppColors.glassSurface,
                ),
              ),
            );
          }),
        ),
        const SizedBox(height: 4),
        if (_passStrength > 0)
          Text(labels[_passStrength], style: AppTypography.bodySm.copyWith(
            color: colors[_passStrength], fontSize: 11, fontWeight: FontWeight.w600)),
      ],
    );
  }

  Widget _buildPasswordTips() {
    final p = _passCtrl.text;
    final has8 = p.length >= 8;
    final hasUpper = RegExp(r'[A-Z]').hasMatch(p);
    final hasDigit = RegExp(r'[0-9]').hasMatch(p);
    final hasSpecial = RegExp(r'[!@#\$%\^&\*\(\)_\+\-=\[\]\{\};:,\.<>\?/\\|]').hasMatch(p);

    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: AppColors.glassSurface,
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: AppColors.glassBorder),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Password must have:', style: AppTypography.bodySm.copyWith(color: AppColors.textSecondary, fontWeight: FontWeight.w600, fontSize: 11)),
            const SizedBox(height: 6),
            _tipRow('At least 8 characters', has8),
            _tipRow('One uppercase letter (A-Z)', hasUpper),
            _tipRow('One number (0-9)', hasDigit),
            _tipRow('One special character (!@#\$...)', hasSpecial),
          ],
        ),
      ),
    );
  }

  Widget _tipRow(String text, bool met) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 3),
      child: Row(
        children: [
          Icon(
            met ? Icons.check_circle_rounded : Icons.circle_outlined,
            size: 14,
            color: met ? AppColors.success : AppColors.textMuted,
          ),
          const SizedBox(width: 8),
          Text(text, style: AppTypography.bodySm.copyWith(
            color: met ? AppColors.success : AppColors.textMuted, fontSize: 11)),
        ],
      ),
    );
  }
}
