import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/text_utils.dart';
import 'verify.dart';

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

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

class _LoginScreenState extends State<LoginScreen>
    with SingleTickerProviderStateMixin {
  bool isDarkMode = false;
  bool _phoneHasFocus = false;
  bool _phoneContainsText = false;

  final TextEditingController _phoneController = TextEditingController();

  // Auto-generated verification code
  String? _generatedCode;

  // Timer variables
  late Timer _timer;
  int _countdown = 60;
  bool _isCounting = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _phoneController.dispose();
    if (_isCounting) _timer.cancel();
    super.dispose();
  }

  /// Validates phone number input
  String? _validatePhone(String value) {
    if (value.isEmpty) return 'Phone number cannot be empty';
    if (!RegExp(r'^\d{10}$').hasMatch(value)) {
      return 'Enter a valid 10-digit phone number';
    }
    return null;
  }

  /// Generates a random 4-digit code
  String _generateVerificationCode() {
    final random = DateTime.now().millisecondsSinceEpoch % 9000 + 1000;
    return random.toString();
  }

  /// Starts a countdown timer for code expiration
  void _startCountdown() {
    if (_isCounting) return;

    _isCounting = true;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_countdown == 0) {
        _isCounting = false;
        timer.cancel();
      } else {
        setState(() {
          _countdown--;
        });
      }
    });
  }

  /// Sends user to Verification Screen with generated code
  void _connect() {
    final validation = _validatePhone(_phoneController.text);
    if (validation != null) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text(validation)));
      return;
    }

    // Generate new code
    _generatedCode = _generateVerificationCode();

    // Show snackbar and auto-fill in verification screen
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Auto-filled code: $_generatedCode")),
      );
    });

    // Start countdown
    _countdown = 60;
    _startCountdown();

    // Navigate to verification screen
    Navigator.push(
      context,
      MaterialPageRoute(
        builder:
            (context) => VerificationScreen(
              correctCode: _generatedCode!,
              autoFillCode: _generatedCode, // Pass generated code for auto-fill
            ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: isDarkMode ? ThemeData.dark() : ThemeData.light(),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xFFC76723),
          elevation: 0,
          actions: [
            IconButton(
              icon: Icon(isDarkMode ? Icons.light_mode : Icons.dark_mode),
              color: Colors.white,
              onPressed: () {
                setState(() {
                  isDarkMode = !isDarkMode;
                });
              },
            ),
          ],
        ),
        body: Container(
          height: double.infinity,
          width: double.infinity,
          color: isDarkMode ? Color.fromARGB(255, 26, 24, 24) : Colors.white,
          child: Align(
            alignment: Alignment.center,
            child: Container(
              width: double.infinity,
              margin: EdgeInsets.symmetric(horizontal: 30),
              decoration: BoxDecoration(
                border: Border.all(
                  color:
                      isDarkMode
                          ? Color.fromARGB(255, 35, 38, 46)
                          : Color.fromARGB(136, 71, 69, 69),
                ),
                borderRadius: BorderRadius.circular(15),
                color:
                    isDarkMode
                        ? Color.fromARGB(133, 93, 75, 75)
                        : Colors.white70,
              ),
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Logo with tagline directly underneath
                      Center(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            // Logo
                            SizedBox(
                              height: 100,
                              width: 160,
                              child: Image.asset(
                                'assets/logo.png',
                                fit: BoxFit.contain,
                              ),
                            ),
                            const SizedBox(height: 4), // Reduced space between logo and tagline
                            // Tagline
                            Text(
                              'Fast . Reliable . Affordable',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                letterSpacing: 1.0,
                                color:
                                    isDarkMode ? Colors.white : Colors.black87,
                              ),
                            ),
                            // Removed the blue line and adjusted spacing
                            const SizedBox(height: 24), // Added more space after tagline
                            // "Sign in here" text
                            TextUtil(
                              text: "Sign in here",
                              weight: true,
                              size: 20,
                              color: isDarkMode ? Colors.white : Colors.black,
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 16),
                      TextUtil(text: "Phone Number"),
                      Container(
                        height: 50,
                        padding: EdgeInsets.symmetric(horizontal: 12),
                        decoration: BoxDecoration(
                          color: isDarkMode ? Colors.grey[800] : Colors.white,
                          border: Border.all(
                            color:
                                _phoneHasFocus || _phoneContainsText
                                    ? (isDarkMode
                                        ? Colors.blueAccent
                                        : Colors.blue)
                                    : (isDarkMode ? Colors.white : Colors.black)
                                        .withOpacity(0.4),
                            width: 1.5,
                          ),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              Icons.phone,
                              color: isDarkMode ? Colors.white : Colors.black,
                              size: 20,
                            ),
                            const SizedBox(width: 10),
                            Expanded(
                              child: TextFormField(
                                controller: _phoneController,
                                keyboardType: TextInputType.number,
                                maxLength: 10,
                                style: TextStyle(
                                  color:
                                      isDarkMode ? Colors.white : Colors.black,
                                ),
                                decoration: InputDecoration(
                                  hintText: "Enter phone number",
                                  counterText: "",
                                  border: InputBorder.none,
                                  hintStyle: TextStyle(
                                    color:
                                        isDarkMode
                                            ? Colors.white70
                                            : Colors.black45,
                                  ),
                                  isDense: true,
                                ),
                                inputFormatters: [
                                  FilteringTextInputFormatter.digitsOnly,
                                  LengthLimitingTextInputFormatter(10),
                                ],
                                onChanged: (value) {
                                  setState(() {
                                    _phoneContainsText = value.isNotEmpty;
                                  });
                                },
                                onTap: () {
                                  setState(() {
                                    _phoneHasFocus = true;
                                  });
                                },
                                onEditingComplete: () {
                                  setState(() {
                                    _phoneHasFocus = false;
                                  });
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 20),
                      GestureDetector(
                        onTap: _connect,
                        child: Container(
                          height: 40,
                          width: double.infinity,
                          decoration: BoxDecoration(
                            color: Colors.blue,
                            borderRadius: BorderRadius.circular(30),
                          ),
                          alignment: Alignment.center,
                          child: TextUtil(text: "Connect", color: Colors.white),
                        ),
                      ),
                      const SizedBox(height: 16),
                      Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: isDarkMode ? Colors.white24 : Colors.black26,
                          ),
                          borderRadius: BorderRadius.circular(12),
                          color:
                              isDarkMode ? Colors.grey[850] : Colors.grey[200],
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.headset_mic,
                              color:
                                  isDarkMode ? Colors.blueAccent : Colors.blue,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              'Need help? Contact support',
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                                color:
                                    isDarkMode
                                        ? Colors.white70
                                        : Colors.black54,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 16),
                      Align(
                        alignment: Alignment.bottomCenter,
                        child: Container(
                          padding: const EdgeInsets.all(12),
                          width: double.infinity,
                          decoration: BoxDecoration(
                            border: Border.all(
                              color: isDarkMode ? Colors.white24 : Colors.black26,
                            ),
                            borderRadius: BorderRadius.circular(12),
                            color:
                                isDarkMode ? Colors.grey[850] : Colors.grey[200],
                          ),
                          child: Text(
                            '© Lence Amazons Ltd • All rights reserved • 2025',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              color:
                                  isDarkMode ? Colors.white70 : Colors.black54,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}