// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers

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/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,
  });

  final String id;
  final String phone;

  @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,
                    ),
                  ),
                ),
                const CountDownTimeOtp(),
                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.resendOtpVerification(widget.id).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,
  }) : super(key: key);

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

class _CountDownTimeOtpState extends State<CountDownTimeOtp> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
        top: AppMargin.m6,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                "00 :",
                style: getRegularStyle(
                  color: ColorManager.primary,
                  fontSize: 20,
                  fontFamily: FontConstants.mulish,
                ),
              ),
              Text(
                " 02 :",
                style: getRegularStyle(
                  color: ColorManager.primary,
                  fontSize: 20,
                  fontFamily: FontConstants.mulish,
                ),
              ),
              Text(
                " 59",
                style: getRegularStyle(
                  color: ColorManager.primary,
                  fontSize: 20,
                  fontFamily: FontConstants.mulish,
                ),
              )
            ],
          ),
          // Text(
          //   "Resend otp",
          //   style: getRegularStyle(
          //     color: ColorManager.primary,
          //     fontSize: FontSize.s16,
          //   ),
          // ),
        ],
      ),
    );
  }
}
