import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api_client.dart';
import '../auth_storage.dart';

// ── Brand tokens (matches login_screen.dart) ──────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const surface = Color(0xFF1A1D22);
  static const card = Color(0xFF21252D);
  static const amber = Color(0xFFFF9500);
  static const amberGlow = Color(0x33FF9500);
  static const textPrimary = Color(0xFFF2F2F2);
  static const textMuted = Color(0xFF8A8F99);
  static const error = Color(0xFFFF4545);
  static const divider = Color(0xFF2C3040);
  static const success = Color(0xFF34C759);
}

// ─────────────────────────────────────────────────────────────────────────────

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

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

class _RegisterScreenState extends State<RegisterScreen>
    with SingleTickerProviderStateMixin {
  final _phoneController = TextEditingController();
  final _pinController = TextEditingController();
  bool _loading = false;
  bool _policyAccepted = false;
  String? _error;

  late final AnimationController _fadeCtrl;
  late final Animation<double> _fadeAnim;
  late final Animation<Offset> _slideAnim;

  @override
  void initState() {
    super.initState();
    _fadeCtrl = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 450),
    );
    _fadeAnim = CurvedAnimation(parent: _fadeCtrl, curve: Curves.easeOut);
    _slideAnim = Tween<Offset>(
      begin: const Offset(0, 0.06),
      end: Offset.zero,
    ).animate(CurvedAnimation(parent: _fadeCtrl, curve: Curves.easeOutCubic));
    _fadeCtrl.forward();
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _pinController.dispose();
    _fadeCtrl.dispose();
    super.dispose();
  }

  // ── Logic (unchanged) ──────────────────────────────────────────────────────

  Future<void> _submit() async {
    if (!_policyAccepted) {
      setState(() => _error = 'Please accept the Terms and Privacy Policy');
      return;
    }
    final raw = _phoneController.text.trim().replaceAll(RegExp(r'\D'), '');
    if (raw.length != 9 || !raw.startsWith('7')) {
      setState(() => _error = 'Enter 9 digits starting with 7');
      return;
    }
    final pin = _pinController.text.trim();
    if (pin.length != 6) {
      setState(() => _error = 'PIN must be 6 digits');
      return;
    }
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final dio = createApiClient(() {});
      final r = await dio.post('/api/auth/register', data: {
        'phone': '256$raw',
        'pin': pin,
        'role': 'user',
      });
      final data = r.data;
      if (data is Map && data['data'] != null) {
        final token = data['data']['token'] as String?;
        if (token != null) {
          await AuthStorage.setToken(token);
          if (mounted) Navigator.of(context).pushReplacementNamed('/dashboard');
          return;
        }
      }
      setState(() => _error = 'Registration failed');
    } catch (e) {
      final msg = e is DioException && e.response?.data != null
          ? (e.response!.data is Map
              ? (e.response!.data['error']?['message'] ?? 'Registration failed')
              : 'Registration failed')
          : 'Check connection';
      setState(() => _error = msg);
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  // ── UI ─────────────────────────────────────────────────────────────────────

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));

    return Scaffold(
      backgroundColor: _Brand.bg,
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
          child: SlideTransition(
            position: _slideAnim,
            child: FadeTransition(
              opacity: _fadeAnim,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  const SizedBox(height: 2),

                  // ── Back button ───────────────────────────────────────────
                  Align(
                    alignment: Alignment.centerLeft,
                    child: GestureDetector(
                      onTap: () => Navigator.of(context)
                          .pushReplacementNamed('/login'),
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 12, vertical: 8),
                        decoration: BoxDecoration(
                          color: _Brand.card,
                          borderRadius: BorderRadius.circular(8),
                          border:
                              Border.all(color: _Brand.divider, width: 1),
                        ),
                        child: const Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.arrow_back_ios_new,
                                size: 13, color: _Brand.textMuted),
                            SizedBox(width: 6),
                            Text('Back',
                                style: TextStyle(
                                    color: _Brand.textMuted, fontSize: 13)),
                          ],
                        ),
                      ),
                    ),
                  ),

                  const SizedBox(height: 10),
                  const Text(
                    'JAMBO',
                    style: TextStyle(
                      fontFamily: 'RobotoMono',
                      color: _Brand.textPrimary,
                      fontSize: 32,
                      fontWeight: FontWeight.w700,
                      letterSpacing: 6,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      Container(width: 24, height: 2, color: _Brand.amber),
                      const SizedBox(width: 8),
                      const Text(
                        'CREATE ACCOUNT',
                        style: TextStyle(
                          color: _Brand.textMuted,
                          fontSize: 11,
                          letterSpacing: 2.5,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 40),

                  // ── Perks strip ───────────────────────────────────────────
                  _PerksStrip(),

                  const SizedBox(height: 36),

                  // ── Error ─────────────────────────────────────────────────
                  if (_error != null) ...[
                    _ErrorBanner(_error!),
                    const SizedBox(height: 20),
                  ],

                  // ── Phone field ───────────────────────────────────────────
                  _Label('UGANDA PHONE NUMBER'),
                  const SizedBox(height: 8),
                  _FuelTextField(
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    maxLength: 9,
                    hintText: '7XX XXX XXX',
                    prefixWidget: const _PhonePrefix(),
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  ),
                  const SizedBox(height: 6),
                  const Text(
                    '9 digits starting with 7 — country code added automatically',
                    style: TextStyle(
                        color: _Brand.textMuted, fontSize: 12, height: 1.5),
                  ),

                  const SizedBox(height: 24),

                  // ── PIN field ─────────────────────────────────────────────
                  _Label('CREATE A 6-DIGIT PIN'),
                  const SizedBox(height: 8),
                  _FuelTextField(
                    controller: _pinController,
                    keyboardType: TextInputType.number,
                    maxLength: 6,
                    hintText: '••••••',
                    obscureText: true,
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  ),
                  const SizedBox(height: 6),
                  const Text(
                    'Keep this PIN safe — you\'ll use it every time you log in',
                    style: TextStyle(
                        color: _Brand.textMuted, fontSize: 12, height: 1.5),
                  ),

                  const SizedBox(height: 24),

                  // ── Policy acceptance ─────────────────────────────────────
                  GestureDetector(
                    onTap: () => setState(() => _policyAccepted = !_policyAccepted),
                    behavior: HitTestBehavior.opaque,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 24,
                          height: 24,
                          child: Checkbox(
                            value: _policyAccepted,
                            onChanged: (v) => setState(() => _policyAccepted = v ?? false),
                            activeColor: _Brand.amber,
                            checkColor: Colors.black,
                            fillColor: WidgetStateProperty.resolveWith((states) {
                              if (states.contains(WidgetState.selected)) return _Brand.amber;
                              return _Brand.card;
                            }),
                            side: BorderSide(
                              color: _policyAccepted ? _Brand.amber : _Brand.divider,
                              width: 1.5,
                            ),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(4),
                            ),
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.only(top: 2),
                            child: RichText(
                              text: TextSpan(
                                style: const TextStyle(
                                  color: _Brand.textMuted,
                                  fontSize: 13,
                                  height: 1.4,
                                ),
                                children: [
                                  const TextSpan(text: 'I accept the '),
                                  TextSpan(
                                    text: 'Terms of Service',
                                    style: TextStyle(
                                      color: _Brand.amber,
                                      fontWeight: FontWeight.w600,
                                      decoration: TextDecoration.underline,
                                      decorationColor: _Brand.amber,
                                    ),
                                  ),
                                  const TextSpan(text: ' and '),
                                  TextSpan(
                                    text: 'Privacy Policy',
                                    style: TextStyle(
                                      color: _Brand.amber,
                                      fontWeight: FontWeight.w600,
                                      decoration: TextDecoration.underline,
                                      decorationColor: _Brand.amber,
                                    ),
                                  ),
                                  const TextSpan(text: '.'),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  const SizedBox(height: 24),

                  // ── Submit ────────────────────────────────────────────────
                  _FuelButton(
                    label: 'CREATE ACCOUNT',
                    onPressed: (_loading || !_policyAccepted) ? null : _submit,
                    loading: _loading,
                    trailing: _loading
                        ? null
                        : const Icon(Icons.check_circle_outline,
                            size: 18, color: Colors.black),
                  ),

                  const SizedBox(height: 16),

                  // ── Divider ───────────────────────────────────────────────
                  Row(
                    children: [
                      Expanded(
                          child: Container(height: 1, color: _Brand.divider)),
                      const Padding(
                        padding: EdgeInsets.symmetric(horizontal: 12),
                        child: Text('or',
                            style: TextStyle(
                                color: _Brand.textMuted, fontSize: 12)),
                      ),
                      Expanded(
                          child: Container(height: 1, color: _Brand.divider)),
                    ],
                  ),

                  const SizedBox(height: 16),

                  TextButton(
                    onPressed: () => Navigator.of(context)
                        .pushReplacementNamed('/login'),
                    style: TextButton.styleFrom(
                      foregroundColor: _Brand.textMuted,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                    child: const Text(
                      'Already have an account? Login',
                      style: TextStyle(fontSize: 13, letterSpacing: 0.3),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

// ── Perks strip ───────────────────────────────────────────────────────────────

class _PerksStrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final perks = [
      (Icons.bolt_rounded, 'Fast\nDelivery'),
      (Icons.shield_rounded, 'Secure\nPayments'),
      (Icons.location_on_rounded, 'Track\nOrder'),
    ];

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8),
      decoration: BoxDecoration(
        color: _Brand.card,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _Brand.divider, width: 1),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: perks.map((p) {
          return Column(
            children: [
              Icon(p.$1, color: _Brand.amber, size: 22),
              const SizedBox(height: 6),
              Text(
                p.$2,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: _Brand.textMuted,
                  fontSize: 11,
                  height: 1.4,
                  letterSpacing: 0.3,
                ),
              ),
            ],
          );
        }).toList(),
      ),
    );
  }
}

// ── Shared widgets (mirror of login_screen.dart) ──────────────────────────────

class _Label extends StatelessWidget {
  final String text;
  const _Label(this.text);

  @override
  Widget build(BuildContext context) => Text(
        text,
        style: const TextStyle(
          color: _Brand.textMuted,
          fontSize: 10,
          letterSpacing: 2,
          fontWeight: FontWeight.w600,
        ),
      );
}

class _PhonePrefix extends StatelessWidget {
  const _PhonePrefix();

  @override
  Widget build(BuildContext context) => const Padding(
        padding: EdgeInsets.only(right: 8),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('+256',
                style: TextStyle(
                  color: _Brand.amber,
                  fontFamily: 'RobotoMono',
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                )),
            SizedBox(width: 8),
            SizedBox(
                height: 20,
                child: VerticalDivider(color: _Brand.divider, width: 1)),
            SizedBox(width: 8),
          ],
        ),
      );
}

class _FuelTextField extends StatelessWidget {
  final TextEditingController controller;
  final TextInputType keyboardType;
  final int maxLength;
  final String hintText;
  final bool obscureText;
  final Widget? prefixWidget;
  final List<TextInputFormatter>? inputFormatters;

  const _FuelTextField({
    required this.controller,
    required this.keyboardType,
    required this.maxLength,
    required this.hintText,
    this.obscureText = false,
    this.prefixWidget,
    this.inputFormatters,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: _Brand.card,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _Brand.divider, width: 1.5),
      ),
      child: TextField(
        controller: controller,
        keyboardType: keyboardType,
        maxLength: maxLength,
        obscureText: obscureText,
        inputFormatters: inputFormatters,
        style: const TextStyle(
          color: _Brand.textPrimary,
          fontFamily: 'RobotoMono',
          fontSize: 18,
          letterSpacing: 2,
        ),
        cursorColor: _Brand.amber,
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: const TextStyle(
            color: _Brand.textMuted,
            letterSpacing: 2,
            fontSize: 16,
          ),
          counterText: '',
          prefix: prefixWidget,
          border: InputBorder.none,
          contentPadding:
              const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        ),
      ),
    );
  }
}

class _FuelButton extends StatelessWidget {
  final String label;
  final VoidCallback? onPressed;
  final Widget? trailing;
  final bool loading;

  const _FuelButton({
    required this.label,
    required this.onPressed,
    this.trailing,
    this.loading = false,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 54,
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: _Brand.amber,
          disabledBackgroundColor: _Brand.amber.withOpacity(0.4),
          foregroundColor: Colors.black,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: loading
            ? const SizedBox(
                width: 22,
                height: 22,
                child: CircularProgressIndicator(
                  strokeWidth: 2.5,
                  valueColor: AlwaysStoppedAnimation(Colors.black54),
                ),
              )
            : Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    label,
                    style: const TextStyle(
                      fontWeight: FontWeight.w800,
                      letterSpacing: 2,
                      fontSize: 14,
                    ),
                  ),
                  if (trailing != null) ...[
                    const SizedBox(width: 8),
                    trailing!,
                  ],
                ],
              ),
      ),
    );
  }
}

class _ErrorBanner extends StatelessWidget {
  final String message;
  const _ErrorBanner(this.message);

  @override
  Widget build(BuildContext context) => Container(
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
        decoration: BoxDecoration(
          color: _Brand.error.withOpacity(0.12),
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: _Brand.error.withOpacity(0.4)),
        ),
        child: Row(
          children: [
            const Icon(Icons.warning_amber_rounded,
                color: _Brand.error, size: 18),
            const SizedBox(width: 10),
            Expanded(
              child: Text(message,
                  style: const TextStyle(
                      color: _Brand.error, fontSize: 13, height: 1.4)),
            ),
          ],
        ),
      );
}