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

// ── Brand (match dashboard & order_detail) ────────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const card = Color(0xFF21252D);
  static const amber = Color(0xFFFF9500);
  static const textPrimary = Color(0xFFF2F2F2);
  static const textMuted = Color(0xFF8A8F99);
  static const divider = Color(0xFF2C3040);
  static const error = Color(0xFFFF4545);
}

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

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

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

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

  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');
      return;
    }
    setState(() {
      _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';
      setState(() => _error = msg);
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isPinStep = _phone != null;
    return Scaffold(
      backgroundColor: _Brand.bg,
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Icon(
                Icons.delivery_dining_rounded,
                size: 56,
                color: _Brand.amber,
              ),
              const SizedBox(height: 20),
              Text(
                isPinStep ? 'Enter PIN' : 'Jambo Driver',
                style: const TextStyle(
                  color: _Brand.textPrimary,
                  fontSize: 22,
                  fontWeight: FontWeight.w700,
                ),
              ),
              const SizedBox(height: 6),
              Text(
                isPinStep ? 'Enter your 6-digit PIN' : 'Enter phone (9 digits, starts with 7)',
                style: const TextStyle(
                  color: _Brand.textMuted,
                  fontSize: 14,
                ),
              ),
              const SizedBox(height: 24),
              if (_error != null) ...[
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  decoration: BoxDecoration(
                    color: _Brand.error.withOpacity(0.12),
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: _Brand.error.withOpacity(0.4)),
                  ),
                  child: Text(
                    _error!,
                    style: const TextStyle(color: _Brand.error, fontSize: 13),
                  ),
                ),
                const SizedBox(height: 16),
              ],
              if (!isPinStep) ...[
                TextField(
                  controller: _phoneController,
                  keyboardType: TextInputType.phone,
                  maxLength: 9,
                  style: const TextStyle(color: _Brand.textPrimary, fontSize: 16),
                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  decoration: InputDecoration(
                    hintText: '712345678',
                    hintStyle: TextStyle(color: _Brand.textMuted.withOpacity(0.7)),
                    counterText: '',
                    filled: true,
                    fillColor: _Brand.card,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: const BorderSide(color: _Brand.divider),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: const BorderSide(color: _Brand.divider),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: const BorderSide(color: _Brand.amber, width: 1.5),
                    ),
                  ),
                ),
                const SizedBox(height: 20),
                FilledButton(
                  onPressed: _loading ? null : _submitPhone,
                  style: FilledButton.styleFrom(
                    backgroundColor: _Brand.amber,
                    foregroundColor: _Brand.bg,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text('Next'),
                ),
              ] else ...[
                TextField(
                  controller: _pinController,
                  keyboardType: TextInputType.number,
                  maxLength: 6,
                  obscureText: true,
                  style: const TextStyle(color: _Brand.textPrimary, fontSize: 18, letterSpacing: 8),
                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  decoration: InputDecoration(
                    hintText: '••••••',
                    hintStyle: TextStyle(color: _Brand.textMuted.withOpacity(0.7)),
                    counterText: '',
                    filled: true,
                    fillColor: _Brand.card,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: const BorderSide(color: _Brand.divider),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: const BorderSide(color: _Brand.divider),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: const BorderSide(color: _Brand.amber, width: 1.5),
                    ),
                  ),
                ),
                const SizedBox(height: 20),
                FilledButton(
                  onPressed: _loading ? null : _submitLogin,
                  style: FilledButton.styleFrom(
                    backgroundColor: _Brand.amber,
                    foregroundColor: _Brand.bg,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: _loading
                      ? const SizedBox(
                          height: 22,
                          width: 22,
                          child: CircularProgressIndicator(strokeWidth: 2, color: _Brand.bg),
                        )
                      : const Text('Login'),
                ),
                const SizedBox(height: 12),
                TextButton(
                  onPressed: () => setState(() => _phone = null),
                  child: const Text('Change number', style: TextStyle(color: _Brand.amber)),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}
