import 'package:flutter/material.dart';
import 'package:login_page/screens/home.dart';
import 'dart:async';

class VerificationScreen extends StatefulWidget {
  final String correctCode;
  final String? autoFillCode;

  const VerificationScreen({
    super.key,
    required this.correctCode,
    this.autoFillCode,
  });

  @override
  State<VerificationScreen> createState() => _VerificationScreenState();
}

class _VerificationScreenState extends State<VerificationScreen> {
  late List<TextEditingController> _controllers;
  late List<FocusNode> _focusNodes;

  int _resendTimer = 60;
  late Timer _timer;

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

    // Initialize controllers and focus nodes
    _controllers = List.generate(4, (_) => TextEditingController());
    _focusNodes = List.generate(4, (_) => FocusNode());

    // Auto-fill if provided
    if (widget.autoFillCode != null && widget.autoFillCode!.length == 4) {
      for (int i = 0; i < 4; i++) {
        _controllers[i].text = widget.autoFillCode![i];
      }
    }

    // Start resend timer
    _startResendTimer();
  }

  void _startResendTimer() {
    const oneSecond = Duration(seconds: 1);
    _timer = Timer.periodic(oneSecond, (timer) {
      if (_resendTimer <= 0) {
        setState(() {
          _resendTimer = 60;
        });
        timer.cancel();
      } else {
        setState(() {
          _resendTimer--;
        });
      }
    });
  }

  @override
  void dispose() {
    // Cancel the timer before disposing
    _timer.cancel();

    // Dispose all controllers and focus nodes
    for (var c in _controllers) {
      c.dispose();
    }
    for (var f in _focusNodes) {
      f.dispose();
    }

    super.dispose();
  }

  Widget _buildDigitField(int index) {
    return SizedBox(
      width: 60,
      child: TextField(
        controller: _controllers[index],
        focusNode: _focusNodes[index],
        keyboardType: TextInputType.number,
        textAlign: TextAlign.center,
        maxLength: 1,
        decoration: InputDecoration(
          counterText: '',
          border: OutlineInputBorder(),
        ),
        onChanged: (value) {
          if (value.isNotEmpty && index < 3) {
            FocusScope.of(context).requestFocus(_focusNodes[index + 1]);
          }
        },
      ),
    );
  }

  void _verifyCode() {
    String enteredCode = _controllers.map((c) => c.text).join();

    if (enteredCode == widget.correctCode) {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => HomePage(email: "Verified")),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Invalid code")),
      );
    }
  }

  Widget _buildResendText() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          "Resend code in: $_resendTimer seconds",
          style: TextStyle(color: Colors.grey),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Enter Code")),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Logo Section
            Image.asset('assets/logo.png', width: 200),
            SizedBox(height: 10),
            Text(
              "Fast. Reliable. Affordable",
              style: TextStyle(fontSize: 16, color: Colors.grey),
            ),
            SizedBox(height: 20),

            // Instruction
            Text(
              "Enter verification code sent via SMS",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20),

            // 4 Digit Input Fields
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: List.generate(4, (index) => _buildDigitField(index)),
            ),
            SizedBox(height: 30),

            // Verify Button
            ElevatedButton(
              onPressed: _verifyCode,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
                minimumSize: Size(double.infinity, 50),
              ),
              child: Text("Verify"),
            ),

            SizedBox(height: 20),
            _buildResendText(),

            SizedBox(height: 30),
            Text(
              "Customer Service",
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            Text(
              "0702026554 | 0790882866",
              style: TextStyle(fontSize: 16),
            ),
          ],
        ),
      ),
    );
  }
}