import 'dart:async';

import 'package:flutter/material.dart';
import 'package:pinput/pinput.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/new_models/general_response_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/forget_password_module/reset_password_view.dart';

class ForgetPasswordVerifyOtpView extends StatefulWidget {
  Map<String, dynamic> data = {};

  ForgetPasswordVerifyOtpView({Key? key, required this.data}) : super(key: key);

  @override
  State<ForgetPasswordVerifyOtpView> createState() => _ForgetPasswordVerifyOtpViewState();
}

class _ForgetPasswordVerifyOtpViewState extends State<ForgetPasswordVerifyOtpView> {
  String otp = '';
  Timer? _timer;
  int _remainingSeconds = 180; // 3 minutes in seconds

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

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startTimer() {
    setState(() {
      _remainingSeconds = 180;
    });

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_remainingSeconds > 0) {
        setState(() {
          _remainingSeconds--;
        });
      } else {
        _timer?.cancel();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final defaultPinTheme = PinTheme(
      width: 68.toScreenWidth,
      height: 86.toScreenHeight,
      textStyle: const TextStyle(
        fontSize: 22,
        color: Colors.black,
      ),
      decoration: BoxDecoration(
        color: AppColor.white10,
        borderRadius: BorderRadius.circular(15),
        border: Border.all(color: AppColor.white10, width: 1),
      ),
    );

    final minutes = (_remainingSeconds ~/ 60).toString().padLeft(2, '0');
    final seconds = (_remainingSeconds % 60).toString().padLeft(2, '0');

    return Scaffold(
      body: Column(
        children: [
          SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                context.translation.otpVerification.heading2(context).custom(color: AppColor.white936, fontWeight: FontWeight.w500),
                8.height,
                '${context.translation.pleaseEnterTheOtpSentTo} ${widget.data['phoneNumber']}'.bodyText2(context).custom(color: AppColor.neutral120, fontWeight: FontWeight.w500),
                40.height,
                Center(
                  child: Pinput(
                    length: 4,
                    defaultPinTheme: defaultPinTheme,
                    focusedPinTheme: defaultPinTheme.copyWith(
                      decoration: defaultPinTheme.decoration?.copyWith(
                        border: Border.all(color: AppColor.neutral40, width: 1),
                      ),
                    ),
                    onCompleted: (pin) {
                      //   setState(() {
                      otp = pin;
                      //});
                      verifyOtp();
                    },
                  ),
                ),
                18.height,
                Row(
                  // mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    InkWell(
                      onTap: _remainingSeconds == 0
                          ? () async {
                              UserProvider _userProvider = Provider.of<UserProvider>(context, listen: false);
                              String employeeId = widget.data['employeeId'];
                              GeneralResponseModel response = await _userProvider.sendForgetPasswordOtp(
                                context: context,
                                employeeId: employeeId,
                              );

                              // Restart the timer
                              _startTimer();
                            }
                          : null,
                      child: Text(
                        'Resend',
                        style: TextStyle(
                          color: _remainingSeconds == 0 ? AppColor.blueStatus(context) : AppColor.neutral40,
                          fontWeight: FontWeight.w500,
                          fontSize: 16.toScreenWidth,
                          decorationColor: AppColor.primary30,
                          decoration: _remainingSeconds == 0 ? TextDecoration.underline : null,
                        ),
                      ),
                    ),
                    7.width,
                    '$minutes:$seconds'.bodyText(context).custom(color: AppColor.neutral10),
                  ],
                ),
              ],
            ),
          ).center.expanded,
          AppFilledButton(
            label: context.translation.verify,
            maxWidth: true,
            onPressed: verifyOtp,
          ),
        ],
      ).paddingOnly(start: 20, end: 20, bottom: 16),
    );
  }

  void verifyOtp() async {
    if (otp.isNotEmpty) {
      UserProvider _userProvider = Provider.of<UserProvider>(context, listen: false);
      GeneralResponseModel generalResponseModel = await _userProvider.forgetPasswordValidateOtp(
        context: context,
        employeeId: widget.data['employeeId'],
        otp: otp,
      );
      if (generalResponseModel.isSuccess == true) {
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => ResetPasswordView()));
      }
    }
  }
}
