import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:lba/gen/assets.gen.dart';
import 'package:lba/screens/auth/userInfo.dart';
import 'package:lba/widgets/loginButton.dart';

class OTPverifaction extends StatefulWidget {
  final String phoneNumber;
  const OTPverifaction({super.key, required this.phoneNumber});

  @override
  State<OTPverifaction> createState() => _LoginState();
}

class _LoginState extends State<OTPverifaction> {
  final List<FocusNode> _focusNodes = List.generate(5, (_) => FocusNode());
  final List<TextEditingController> _controllers = List.generate(5, (_) => TextEditingController());

  Timer? _timer;
  int _remainingSeconds = 600;
  bool _canResend = false;

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

  void _startTimer() {
    _timer?.cancel();
    _remainingSeconds = 600;
    _canResend = false;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_remainingSeconds == 0) {
        setState(() {
          _canResend = true;
          timer.cancel();
        });
      } else {
        setState(() {
          _remainingSeconds--;
        });
      }
    });
  }

  String _formatTime(int seconds) {
    final minutes = (seconds ~/ 60).toString().padLeft(2, '0');
    final secs = (seconds % 60).toString().padLeft(2, '0');
    return "$minutes:$secs";
  }

  @override
  void dispose() {
    for (final node in _focusNodes) {
      node.dispose();
    }
    for (final controller in _controllers) {
      controller.dispose();
    }
    _timer?.cancel();
    super.dispose();
  }

  Widget _buildOTPFields() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: List.generate(5, (index) {
        return SizedBox(
          width: 50,
          child: TextField(
            controller: _controllers[index],
            focusNode: _focusNodes[index],
            keyboardType: TextInputType.number,
            textAlign: TextAlign.center,
            maxLength: 1,
            style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            decoration: InputDecoration(
              counterText: '',
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(color: Colors.grey),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(color: Color.fromARGB(255, 14, 63, 102)),
              ),
            ),
            onChanged: (value) {
              if (value.length == 1 && index < 4) {
                FocusScope.of(context).requestFocus(_focusNodes[index + 1]);
              }
            },
          ),
        );
      }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                IconButton(
                  icon: SvgPicture.asset(Assets.icons.back.path,),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 20),
                  Center(child: SvgPicture.asset(Assets.images.logo.path)),
                  const SizedBox(height: 24),
                  const Text("OTP Verification", style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold)),
                  const SizedBox(height: 8),
                  const Text("Enter the verification code we just sent to your device."),
                  const SizedBox(height: 25),
                  _buildOTPFields(),
                  const SizedBox(height: 70),
                  SizedBox(
                  width: double.infinity,
                  height: 48,
                  child: LogInButton(text: "Verify",onPressed: () {
                    Navigator.push(context, MaterialPageRoute(builder: (context) => UserInfo(),));
                  },)
                  ),    
                  const SizedBox(height: 40),
                  Center(
                    child: Column(
                      children: [
                        Row(
                          children: [
                            const Expanded(
                              child: Divider(thickness: 1, color: Colors.grey),
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: 8.0),
                              child: Text("Resend OTP in ${_formatTime(_remainingSeconds)}",style: TextStyle(fontWeight: FontWeight.bold),),
                            ),
                            const Expanded(
                              child: Divider(thickness: 1, color: Colors.grey),
                            ),
                          ],
                        ),
                        const SizedBox(height: 8),
                        GestureDetector(
                          onTap: _canResend ? () => _startTimer() : null,
                          child: Text(
                            "Resend Code",
                            style: TextStyle(
                              fontSize: 16,
                              color: _canResend ? const Color.fromARGB(255, 0, 0, 0) : Colors.grey,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}