import 'package:car_customer_app/api/client/user_api_client.dart';
import 'package:car_customer_app/api/shared_prefrence.dart';

import 'package:car_customer_app/classes/utils.dart';
import 'package:car_customer_app/config/constants.dart';
import 'package:car_customer_app/config/routes.dart';
import 'package:car_customer_app/generated/locale_keys.g.dart';
import 'package:car_customer_app/models/user/forget_password_otp_compare.dart';
import 'package:car_customer_app/models/user/forget_password_otp_request.dart';
import 'package:car_customer_app/pages/user/vertify_password_page.dart';
import 'package:car_customer_app/utils/navigator.dart';
import 'package:car_customer_app/utils/utils.dart';
import 'package:car_customer_app/widgets/app_bar.dart';
import 'package:car_customer_app/widgets/button/show_image_button.dart';
import 'package:car_customer_app/widgets/dialog/dialogs.dart';
import 'package:car_customer_app/widgets/dialog/message_dialog.dart';
import 'package:car_customer_app/widgets/dialog/otp_dialog.dart';
import 'package:car_customer_app/widgets/show_fill_button.dart';
import 'package:car_customer_app/extensions/string_extensions.dart';
import 'package:car_customer_app/extensions/int_extensions.dart';
import 'package:car_customer_app/extensions/widget_extensions.dart';
import 'package:car_customer_app/widgets/txt_field.dart';
import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';
import 'package:car_customer_app/models/user/user.dart';

import 'dart:convert';
import 'package:http/http.dart';

import '../../classes/colors.dart';
import '../../models/user/country.dart';
import '../../widgets/dropdown/dropdow_field.dart';
import '../../widgets/tab/login_email_tab.dart';

class ForgetPasswordPage extends StatefulWidget {
  @override
  State<ForgetPasswordPage> createState() => _ForgetPasswordPageState();
}

class _ForgetPasswordPageState extends State<ForgetPasswordPage> {
  int otpType = 1;

  String userName = "";
  ClassType type = ClassType.EMAIL;
  Country? _country;
  String countryCode = "";

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

  getCountryList() async {
    _country = await UserApiClent().getAllCountries();
    setState(() {});
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(context,title: LocaleKeys.changePassword.tr()),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height,
            child: Column(
              children: [
                12.height,
                LocaleKeys.forgetPassword.tr().toText20(),
                20.height,
                LocaleKeys.retrievePassword.tr().toText14(
                  color: MyColors.lightTextColor,
                  textAlign: TextAlign.center,
                ),
                30.height,
                LoginEmailTab(
                  onSelection: (ClassType type) {
                    setState(() {
                      this.type = type;
                    });
                  },
                ),
                12.height,
                type == ClassType.NUMBER
                    ? Column(
                  children: [
                    getCountry(),
                    6.height,
                    TxtField(
                      hint: "5********",
                      value: userName,
                      onChanged: (v) {
                        userName = v;
                      },
                    )
                  ],
                )
                    : TxtField(
                  hint: LocaleKeys.emailAddress.tr(),
                  value: userName,
                  onChanged: (v) {
                    userName = v;
                  },
                ),
                20.height,
                (type == ClassType.NUMBER ? LocaleKeys.retriveOnPhone.tr() : LocaleKeys.retriveOnEmail.tr()).toText14(
                  color: MyColors.lightTextColor,
                  textAlign: TextAlign.center,
                ),
                30.height,
                ShowFillButton(
                  title: LocaleKeys.send.tr(),
                  maxWidth: double.infinity,
                  onPressed: () {
                    if (userName.isNum() && type == ClassType.NUMBER) {
                      forgetPasswordPhoneOTP(context);
                    } else if (!userName.isNum() && type == ClassType.EMAIL) {
                      forgetPasswordEmailOTP(context);
                    }
                  },
                ),
                mFlex(10),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget getCountry() {
    if (_country != null) {
      List<DropValue> dropList = [];
      _country!.data?.forEach((element) {
        dropList.add(new DropValue(element.id ?? 0, (element.countryName ?? "") + " " + (element.countryCode ?? ""), element.countryCode ?? ""));
      });
      return Padding(
        padding: const EdgeInsets.all(2.0),
        child: DropdownField((DropValue value) {
          countryCode = value.subValue;
        }, list: dropList, hint: LocaleKeys.selectCountryCode.tr()),
      );
    } else {
      return Center(
        child: CircularProgressIndicator(),
      );
    }
  }

  Future<void> forgetPasswordPhoneOTP(BuildContext context) async {
    Utils.showLoading(context);
    Response response = await UserApiClent().ForgetPasswordOTPRequest(countryCode+userName, otpType);
    Utils.hideLoading(context);
    PasswordOTPRequest otpRequest = PasswordOTPRequest.fromJson(jsonDecode(response.body));
    if (otpRequest.messageStatus == 1) {
      var userToken = otpRequest.data!.userToken;
      navigateReplaceWithName(context, AppRoutes.forgetPasswordMethodPage, arguments: userToken);
    } else {
      Utils.showToast(otpRequest.message ?? "");
    }
  }

  Future<void> forgetPasswordEmailOTP(BuildContext context) async {
    Utils.showLoading(context);
    Response response = await UserApiClent().ForgetPasswordOTPRequest(userName, otpType);
    Utils.hideLoading(context);
    PasswordOTPRequest otpRequest = PasswordOTPRequest.fromJson(jsonDecode(response.body));
    if (otpRequest.messageStatus == 1) {
      Utils.showToast(LocaleKeys.codeSentToEmail.tr());
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          pop(context);
          Utils.showLoading(context);
          Response res = await UserApiClent().ForgetPasswordOTPCompare(otpRequest.data!.userToken ?? "", code);
          Utils.hideLoading(context);
          PasswordOTPCompare otpCompare = PasswordOTPCompare.fromJson(jsonDecode(res.body));
          if (otpCompare.messageStatus == 1) {
            var userToken = otpCompare.data!.userToken;
            print("token is ________");
            print(userToken);
            navigateWithName(context, AppRoutes.confirmNewPasswordPage, arguments: userToken);
          } else {
            Utils.showToast(otpCompare.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(otpRequest.message ?? "");
    }
  }
}
