// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:tour_travel_agr/api/all_api.dart';
import 'package:tour_travel_agr/helper/components_widget/custom_appbar.dart';
import 'package:tour_travel_agr/helper/function/timer_date.dart';
import 'package:tour_travel_agr/helper/modal_dialog.dart';
import 'package:tour_travel_agr/helper/widget_responsive.dart';
import 'package:tour_travel_agr/resource/assets.dart';
import 'package:tour_travel_agr/resource/colors.dart';
import 'package:tour_travel_agr/resource/font.dart';
import 'package:tour_travel_agr/resource/routes.dart';
import 'package:tour_travel_agr/resource/size.dart';
import 'package:tour_travel_agr/resource/strings.dart';
import 'package:tour_travel_agr/resource/style.dart';

class OtpVerificationView extends StatefulWidget {
  const OtpVerificationView({
    super.key,
    required this.id,
    required this.phone,
    required this.otpExpiredTime,
  });

  final String id;
  final String phone;
  final String otpExpiredTime;

  @override
  State<OtpVerificationView> createState() => _OtpVerificationViewState();
}

class _OtpVerificationViewState extends State<OtpVerificationView> {
  final TextEditingController otp1Controller = TextEditingController();
  final TextEditingController otp2Controller = TextEditingController();
  final TextEditingController otp3Controller = TextEditingController();
  final TextEditingController otp4Controller = TextEditingController();

  String finalText = "";
  bool disabledInput = false;

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorManager.backgroundColor,
      body: ScreenResponsive(
        widget: bodyWidget(context),
        widthScreen: MediaQuery.of(context).size.width,
      ),
    );
  }

  Container bodyWidget(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
        top: AppPadding.safeAreaTop(context),
        left: AppPadding.p20,
        right: AppPadding.p20,
        bottom: AppPadding.safeAreaBot(context),
      ),
      child: Column(
        children: [
          const CustomAppBar(
            text: "OTP Verification",
          ),
          Expanded(
            child: SingleChildScrollView(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  margin: EdgeInsets.only(
                    top: AppMargin.m12,
                  ),
                  child: Center(
                    child: Image(
                      width: 267,
                      height: 243,
                      image: AssetImage(
                        Assets.verificationHeadImage,
                      ),
                    ),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(
                    top: 40,
                  ),
                  child: Text(
                    "Enter OTP",
                    style: getSemiBoldStyle(
                      color: Colors.black,
                      fontSize: FontSize.s22,
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: AppMargin.m4,
                  ),
                  child: Text(
                    "An 4 digit code has been sent to ${widget.phone}",
                    style: getMediumStyle(
                      color: ColorManager.grey,
                    ),
                  ),
                ),
                CountDownTimeOtp(
                  idRegistration: widget.id,
                  otpExpiredTime: widget.otpExpiredTime,
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: AppMargin.m16,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      inputOtpMethod(
                        context,
                        otp1Controller,
                      ),
                      inputOtpMethod(
                        context,
                        otp2Controller,
                      ),
                      inputOtpMethod(
                        context,
                        otp3Controller,
                      ),
                      inputOtpMethod(
                        context,
                        otp4Controller,
                      )
                    ],
                  ),
                ),
              ],
            )),
          )
        ],
      ),
    );
  }

  Container inputOtpMethod(
      BuildContext context, TextEditingController controller) {
    return Container(
      width: 67,
      height: 67,
      child: TextField(
        autofocus: false,
        textAlign: TextAlign.center,
        keyboardType: TextInputType.number,
        maxLength: 1,
        enabled: !disabledInput,
        cursorColor: Colors.black,
        decoration: InputDecoration(
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
          counterText: '',
          hintStyle: const TextStyle(
            color: Colors.black,
            fontSize: 20.0,
          ),
          filled: disabledInput,
          fillColor: Colors.grey.withOpacity(0.8),
        ),
        controller: controller,
        onChanged: (value) async {
          finalText =
              "${otp1Controller.text}${otp2Controller.text}${otp3Controller.text}${otp4Controller.text}";
          if (finalText.length >= 4) {
            await EasyLoading.show(
              status: Strings.pleaseWait,
              maskType: EasyLoadingMaskType.none,
            );
            setState(() {
              disabledInput = true;
            });
            // ignore: use_build_context_synchronously
            FocusScope.of(context).unfocus();
            Api.confirmRegistration(
              widget.id,
              finalText,
            ).then((apiResponse) {
              EasyLoading.dismiss();
              if (apiResponse.error) {
                setState(() {
                  disabledInput = false;
                  modalDialogGlobal(
                    context: context,
                    title: "Gagal",
                    contentBody: apiResponse.msg,
                    buttonText: 'Ok',
                    tapButton: () => Navigator.pop(context),
                  );
                });
                return;
              } else {
                modalDialogGlobal(
                  context: context,
                  title: "Success",
                  contentBody: "Registration success",
                  buttonText: 'Login',
                  tapButton: () {
                    Navigator.pushNamedAndRemoveUntil(
                      context,
                      Routes.loginRoute,
                      (route) => false,
                    );
                  },
                );
              }
            });
          } else {
            setState(() {});
            if (controller.text.isNotEmpty) {
              FocusScope.of(context).nextFocus();
            }
          }
        },
      ),
    );
  }
}

class CountDownTimeOtp extends StatefulWidget {
  const CountDownTimeOtp({
    Key? key,
    required this.idRegistration,
    required this.otpExpiredTime,
  }) : super(key: key);

  final String idRegistration;
  final String otpExpiredTime;

  @override
  State<CountDownTimeOtp> createState() => _CountDownTimeOtpState();
}

class _CountDownTimeOtpState extends State<CountDownTimeOtp> {
  late Timer? _timer;
  late String hours = "00";
  late String minutes = "00";
  late String seconds = "00";
  late bool isTimerExpired = false;
  late String? timerExpired;

  @override
  void initState() {
    timerExpired = widget.otpExpiredTime;
    startTimer();
    super.initState();
  }

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

  void startTimer() {
    Duration oneSec = const Duration(seconds: 1);
    _timer = Timer.periodic(
      oneSec,
      (Timer timer) {
        setState(() {
          Map<String, dynamic> diffTime = differenceTimeFromNow(timerExpired!);
          hours = diffTime['hour'];
          minutes = diffTime['minutes'];
          seconds = diffTime['seconds'];
          if (hours == "00" && minutes == "00" && seconds == "00") {
            isTimerExpired = true;
            cancelTimer();
          }
        });
      },
    );
  }

  void cancelTimer() {
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
        top: AppMargin.m6,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          (isTimerExpired == false)
              ? Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      "$hours :",
                      style: getRegularStyle(
                        color: ColorManager.primary,
                        fontSize: 20,
                        fontFamily: FontConstants.mulish,
                      ),
                    ),
                    Text(
                      " $minutes :",
                      style: getRegularStyle(
                        color: ColorManager.primary,
                        fontSize: 20,
                        fontFamily: FontConstants.mulish,
                      ),
                    ),
                    Text(
                      " $seconds",
                      style: getRegularStyle(
                        color: ColorManager.primary,
                        fontSize: 20,
                        fontFamily: FontConstants.mulish,
                      ),
                    )
                  ],
                )
              : GestureDetector(
                  onTap: () async {
                    await EasyLoading.show(
                      status: Strings.pleaseWait,
                      maskType: EasyLoadingMaskType.none,
                    );
                    Api.resendOtpVerification(widget.idRegistration)
                        .then((apiResponse) {
                      EasyLoading.dismiss();
                      if (apiResponse.error) {
                        modalDialogGlobal(
                          context: context,
                          title: "Gagal",
                          contentBody: apiResponse.msg,
                          buttonText: "Ok",
                          tapButton: () => Navigator.pop(context),
                        );
                        return;
                      }
                      setState(() {
                        isTimerExpired = false;
                        timerExpired = apiResponse.data["can_resend_after"];
                        startTimer();
                      });
                    });
                  },
                  child: Text(
                    "Resend otp",
                    style: getRegularStyle(
                      color: ColorManager.primary,
                      fontSize: FontSize.s16,
                    ),
                  ),
                ),
        ],
      ),
    );
  }
}
