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 ──────────────────────────────────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const surface = Color(0xFF1A1D22);
  static const card = Color(0xFF21252D);
  static const amber = Color(0xFFFF9500);
  static const amberDark = Color(0xFFCC7700);
  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);
}

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

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

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen>
    with SingleTickerProviderStateMixin {
  final _phoneController = TextEditingController();
  final _pinController = TextEditingController();
  String? _phone;
  bool _loading = false;
  String? _error;

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

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

  void _transition(VoidCallback fn) {
    _slideCtrl.reverse().then((_) {
      setState(fn);
      _slideCtrl.forward();
    });
  }

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

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

  Future<void> _submitPhone() async {
    final raw = _phoneController.text.trim().replaceAll(RegExp(r'\D'), '');
    if (raw.length != 9 || !raw.startsWith('7')) {
      setState(() => _error = 'Enter 9 digits starting with 7 (e.g. 712345678)');
      return;
    }
    _transition(() {
      _phone = '256$raw';
      _error = null;
      _pinController.clear();
    });
  }

  Future<void> _submitLogin() async {
    if (_phone == null) 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/login', data: {
        'phone': _phone,
        'pin': pin,
      });
      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 = 'Login failed');
    } catch (e) {
      final msg = e is DioException && e.response?.data != null
          ? (e.response!.data is Map
              ? (e.response!.data['error']?['message'] ?? 'Invalid phone or PIN')
              : 'Invalid phone or PIN')
          : 'Check connection and try again';
      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,
    ));

    final isPinStep = _phone != null;

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

              // ── Logo / wordmark ─────────────────────────────────────────
              _Logo(),

              const SizedBox(height: 48),

              // ── Slide + fade wrapper ─────────────────────────────────────
              SlideTransition(
                position: _slideAnim,
                child: FadeTransition(
                  opacity: _fadeAnim,
                  child: isPinStep ? _PinStep(this) : _PhoneStep(this),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ── Logo widget ──────────────────────────────────────────────────────────────

class _Logo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Fuel-drop icon badge
        Container(
          width: 56,
          height: 56,
          decoration: BoxDecoration(
            color: _Brand.amberGlow,
            borderRadius: BorderRadius.circular(14),
            border: Border.all(color: _Brand.amber.withOpacity(0.4), width: 1.5),
          ),
          child: const Icon(_FuelIcons.drop, color: _Brand.amber, size: 28),
        ),
        const SizedBox(height: 20),
        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(
              'GAS & FUEL DELIVERY',
              style: TextStyle(
                color: _Brand.textMuted,
                fontSize: 11,
                letterSpacing: 2.5,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ],
    );
  }
}

// ── Phone step ───────────────────────────────────────────────────────────────

class _PhoneStep extends StatelessWidget {
  final _LoginScreenState s;
  const _PhoneStep(this.s);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _StepLabel(label: 'STEP 1 OF 2', title: 'Phone Number'),
        const SizedBox(height: 28),
        if (s._error != null) ...[
          _ErrorBanner(s._error!),
          const SizedBox(height: 16),
        ],
        _Label('UGANDA NUMBER'),
        const SizedBox(height: 8),
        _FuelTextField(
          controller: s._phoneController,
          keyboardType: TextInputType.phone,
          maxLength: 9,
          hintText: '7XX XXX XXX',
          prefixWidget: _PhonePrefix(),
          inputFormatters: [FilteringTextInputFormatter.digitsOnly],
        ),
        const SizedBox(height: 8),
        const Text(
          '9 digits starting with 7 — country code added automatically',
          style: TextStyle(color: _Brand.textMuted, fontSize: 12, height: 1.5),
        ),
        const SizedBox(height: 28),
        _FuelButton(
          label: 'CONTINUE',
          onPressed: s._loading ? null : s._submitPhone,
          trailing: const Icon(Icons.arrow_forward, size: 18, color: Colors.black),
        ),
        const SizedBox(height: 16),
        _Divider(),
        const SizedBox(height: 16),
        _GhostButton(
          label: "Don't have an account? Register",
          onPressed: () =>
              Navigator.of(context).pushReplacementNamed('/register'),
        ),
      ],
    );
  }
}

// ── PIN step ─────────────────────────────────────────────────────────────────

class _PinStep extends StatelessWidget {
  final _LoginScreenState s;
  const _PinStep(this.s);

  @override
  Widget build(BuildContext context) {
    // Mask display: show first 5 digits, last 4 masked
    final display =
        s._phone != null ? '${s._phone!.substring(0, 7)}••••' : '';

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _StepLabel(label: 'STEP 2 OF 2', title: 'Enter Your PIN'),
        const SizedBox(height: 8),
        // Phone chip
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          decoration: BoxDecoration(
            color: _Brand.amberGlow,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: _Brand.amber.withOpacity(0.3)),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.phone_android, size: 14, color: _Brand.amber),
              const SizedBox(width: 6),
              Text(
                '+$display',
                style: const TextStyle(
                  color: _Brand.amber,
                  fontSize: 13,
                  fontFamily: 'RobotoMono',
                  letterSpacing: 1,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 28),
        if (s._error != null) ...[
          _ErrorBanner(s._error!),
          const SizedBox(height: 16),
        ],
        _Label('6-DIGIT PIN'),
        const SizedBox(height: 8),
        _FuelTextField(
          controller: s._pinController,
          keyboardType: TextInputType.number,
          maxLength: 6,
          hintText: '••••••',
          obscureText: true,
          inputFormatters: [FilteringTextInputFormatter.digitsOnly],
        ),
        const SizedBox(height: 28),
        _FuelButton(
          label: s._loading ? '' : 'LOGIN',
          onPressed: s._loading ? null : s._submitLogin,
          loading: s._loading,
          trailing: s._loading
              ? null
              : const Icon(Icons.local_gas_station,
                  size: 18, color: Colors.black),
        ),
        const SizedBox(height: 16),
        _Divider(),
        const SizedBox(height: 16),
        _GhostButton(
          label: '← Change number',
          onPressed: () => s._transition(() => s._phone = null),
        ),
      ],
    );
  }
}

// ── Shared small widgets ──────────────────────────────────────────────────────

class _StepLabel extends StatelessWidget {
  final String label, title;
  const _StepLabel({required this.label, required this.title});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label,
            style: const TextStyle(
                color: _Brand.amber,
                fontSize: 10,
                letterSpacing: 2.5,
                fontWeight: FontWeight.w700)),
        const SizedBox(height: 4),
        Text(title,
            style: const TextStyle(
                color: _Brand.textPrimary,
                fontSize: 24,
                fontWeight: FontWeight.w700,
                letterSpacing: -0.5)),
      ],
    );
  }
}

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 {
  @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 _GhostButton extends StatelessWidget {
  final String label;
  final VoidCallback? onPressed;
  const _GhostButton({required this.label, this.onPressed});

  @override
  Widget build(BuildContext context) => TextButton(
        onPressed: onPressed,
        style: TextButton.styleFrom(
          foregroundColor: _Brand.textMuted,
          padding: const EdgeInsets.symmetric(vertical: 12),
        ),
        child: Text(label,
            style: const TextStyle(fontSize: 13, letterSpacing: 0.3)),
      );
}

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)),
            ),
          ],
        ),
      );
}

class _Divider extends StatelessWidget {
  @override
  Widget build(BuildContext context) => 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)),
        ],
      );
}

// ── Icon references (using built-in Material icons) ───────────────────────────
class _FuelIcons {
  static const drop = Icons.water_drop_rounded;
}