// ignore_for_file: deprecated_member_use

import 'dart:async';

import 'package:didvan/config/design_config.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/providers/user.dart';
import 'package:didvan/views/authentication/authentication_state.dart';
import 'package:didvan/views/authentication/widgets/authentication_layout.dart';
import 'package:didvan/views/widgets/didvan/button.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:provider/provider.dart';
import 'package:sms_autofill/sms_autofill.dart';

class Verification extends StatefulWidget {
  const Verification({Key? key}) : super(key: key);

  @override
  State<Verification> createState() => _VerificationState();
}

class _VerificationState extends State<Verification> {
  Timer? _timer;
  int _secondsRemaining = 119;

  bool _isResendButtonEnabled = false;

  @override
  void initState() {
    final state = context.read<AuthenticationState>();
    if (state.username == '') {
      final user = context.read<UserProvider>().user;
      state.username = user.phoneNumber;
    }
    Future.delayed(
      Duration.zero,
      state.sendOtpToken,
    );
    _handleTimer();
    super.initState();
    _listenForSms();
  }
  
  Future<void> _listenForSms() async {
    if (kDebugMode) {
      print("<<<<< در حال تلاش برای دریافت امضای برنامه >>>>>");
    }

    final appSignature = await SmsAutoFill().getAppSignature;

    if (kDebugMode) {
      print("App Signature: $appSignature");
    }

    await SmsAutoFill().listenForCode();
}


  @override
  Widget build(BuildContext context) {
    final AuthenticationState state = context.read<AuthenticationState>();
    return WillPopScope(
      onWillPop: () async {
        _timer?.cancel();
        return true;
      },
      child: AuthenticationLayout(
        appBarTitle: 'تغییر رمز عبور',
        children: [
          DidvanText(
            'کد 6 رقمی ارسال شده به موبایل',
            style: Theme.of(context).textTheme.titleSmall,
            fontWeight: FontWeight.normal,
          ),
          const SizedBox(
            height: 8,
          ),
          DidvanText(
            state.username,
            style: Theme.of(context).textTheme.titleMedium,
          ),
          const SizedBox(
            height: 8,
          ),
          DidvanText(
            'را وارد کنید:',
            style: Theme.of(context).textTheme.titleSmall,
            fontWeight: FontWeight.normal,
          ),
          const SizedBox(
            height: 24,
          ),
          Directionality(
            textDirection: TextDirection.ltr,
            child: PinCodeTextField(
              keyboardType: TextInputType.number,
              animationType: AnimationType.scale,
              cursorColor: Theme.of(context).colorScheme.text,
              pinTheme: PinTheme(
                fieldHeight: 48,
                fieldWidth: 48,
                selectedColor: Theme.of(context).colorScheme.primary,
                inactiveColor: Theme.of(context).colorScheme.border,
                activeFillColor: Theme.of(context).colorScheme.primary,
                activeColor: Theme.of(context).colorScheme.primary,
                borderRadius: DesignConfig.lowBorderRadius,
                borderWidth: 1,
                shape: PinCodeFieldShape.box,
              ),
              appContext: context,
              length: 6,
              onCompleted: (value) async {
                final result = await state.verifyOtpToken(value);
                if (result) {
                  _timer?.cancel();
                }
              },
              onChanged: (value) {},
            ),
          ),
          const Spacer(),
          DidvanButton(
            enabled: _isResendButtonEnabled,
            onPressed: () {
              _handleTimer();
              state.sendOtpToken();
            },
            title: !_isResendButtonEnabled
                ? '$_secondsRemaining ثانیه دیگر'
                : 'ارسال مجدد کد',
          ),
          const SizedBox(
            height: 48,
          ),
        ],
      ),
    );
  }

  Future<void> _handleTimer() async {
    _timer?.cancel();
    _isResendButtonEnabled = false;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      try {
        setState(() {
          _secondsRemaining -= 1;
          if (_secondsRemaining == 0) {
            _isResendButtonEnabled = true;
            _secondsRemaining = 129;
            _timer?.cancel();
          }
        });
      } catch (e) {
        _timer?.cancel();
      }
    });
    setState(() {});
  }
}
