import 'dart:convert';

import 'package:car_provider_app/api/shared_prefrence.dart';
import 'package:car_provider_app/api/client/user_api_client.dart';
import 'package:car_provider_app/classes/app_state.dart';
import 'package:car_provider_app/classes/utils.dart';
import 'package:car_provider_app/config/constants.dart';
import 'package:car_provider_app/config/routes.dart';
import 'package:car_provider_app/generated/locale_keys.g.dart';
import 'package:car_provider_app/models/user/login_password.dart';
import 'package:car_provider_app/models/user/register_user.dart';
import 'package:car_provider_app/models/user/user.dart';
import 'package:car_provider_app/utils/navigator.dart';
import 'package:car_provider_app/utils/utils.dart';
import 'package:car_provider_app/widgets/app_bar.dart';
import 'package:car_provider_app/widgets/button/show_image_button.dart';
import 'package:car_provider_app/widgets/dialog/dialogs.dart';
import 'package:car_provider_app/widgets/dialog/message_dialog.dart';
import 'package:car_provider_app/extensions/int_extensions.dart';
import 'package:car_provider_app/extensions/string_extensions.dart';
import 'package:car_provider_app/extensions/widget_extensions.dart';
import 'package:car_provider_app/widgets/dialog/otp_dialog.dart';
import 'package:car_provider_app/widgets/txt_field.dart';
import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';

class LoginVerificationPage extends StatefulWidget {
  @override
  State<LoginVerificationPage> createState() => _LoginVerificationPageState();
}

class _LoginVerificationPageState extends State<LoginVerificationPage> {
  String userToken = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    performApiCall();
  }

  performApiCall() async {
    String userName = await SharedPrefManager.getPhoneOrEmail();
    String password = await SharedPrefManager.getUserPassword();
    if (userName.isNotEmpty && userName.isNotEmpty) {
      Utils.showLoading(context);
      Response response = await UserApiClent().login_V1(userName, password);
      Utils.hideLoading(context);
      LoginPassword user = LoginPassword.fromJson(jsonDecode(response.body));
      if (user.messageStatus == 1) {
        userToken = user.data!.userToken ?? "";
        // navigateWithName(context, AppRoutes.loginMethodSelection, arguments: user.data!.userToken);
      } else {
        Utils.showToast(user.message ?? "");
      }
    }
  }

  Future<void> performBasicOtp(BuildContext context, String userToken) async {
    Utils.showLoading(context);
    Response response = await UserApiClent().login_V2_OTP(userToken, "1");
    Utils.hideLoading(context);
    LoginPassword user = LoginPassword.fromJson(jsonDecode(response.body));
    if (user.messageStatus == 1) {
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          pop(context);
          Utils.showLoading(context);
          Response response2 = await UserApiClent().login_V2_OTPVerify(user.data!.userToken ?? "", code);
          Utils.hideLoading(context);
          RegisterUser verifiedUser = RegisterUser.fromJson(jsonDecode(response2.body));
          if (verifiedUser.messageStatus == 1) {
            User user = User.fromJson(jsonDecode(response2.body));
            AppState().setUser = user;
            print(user.data!.userInfo!.providerId.toString());
            navigateReplaceWithName(context, AppRoutes.dashboard);
          } else {
            Utils.showToast(verifiedUser.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(user.message ?? "");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(context,title: LocaleKeys.login.tr()),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.all(40),
        child: Column(
          children: [
            LocaleKeys.verifyAccount.tr().toText24(),
            mFlex(2),
            Row(
              children: [
                Expanded(
                  child: ShowImageButton(
                    onClick: () {
                      performBasicOtp(context, userToken);
                    },
                    title: LocaleKeys.fingerPrint.tr(),
                    icon: icons + "ic_fingerprint.png",
                  ),
                ),
                20.width,
                Expanded(
                  child: ShowImageButton(
                    onClick: () {
                      performBasicOtp(context, userToken);
                    },
                    title: LocaleKeys.faceRecognition.tr(),
                    icon: icons + "ic_face_id.png",
                  ),
                ),
              ],
            ),
            40.height,
            Row(
              children: [
                Expanded(
                  child: ShowImageButton(
                    onClick: () {
                      performBasicOtp(context, userToken);
                    },
                    title: LocaleKeys.SMS.tr(),
                    icon: icons + "ic_sms.png",
                  ),
                ),
                20.width,
                Expanded(
                  child: ShowImageButton(
                    onClick: () {
                      performBasicOtp(context, userToken);
                    },
                    title: LocaleKeys.whatsapp.tr(),
                    icon: icons + "ic_whatsapp.png",
                  ),
                ),
              ],
            ),
            mFlex(10),
          ],
        ),
      ),
    );
  }

// Future<void> performBasicOtp(BuildContext context) async {
//   Utils.showLoading(context);
//   String userToken=await SharedPrefManager.getUserToken();
//   Response response = await UserApiClent().login_V2_OTP(userToken, "1");
//   Utils.hideLoading(context);
//   if (response.statusCode == 200) {
//     String userToken = jsonDecode(response.body)["token"];
//     showMDialog(context, child: OtpDialog(
//       onClick: (String code) async {
//         pop(context);
//         Utils.showLoading(context);
//         Response response2 = await UserApiClent().login_V2_OTPVerify(userToken, code);
//         Utils.hideLoading(context);
//         if (response2.statusCode == 200) {
//           User user = User.fromJson(jsonDecode(response2.body));
//           SharedPrefManager.setUserToken(user.data!.accessToken ?? "");
//           SharedPrefManager.setUserId(user.data!.userInfo!.userId ?? "");
//           navigateWithName(context, AppRoutes.dashboard);
//         } else {
//           Utils.showToast("Something went wrong");
//         }
//       },
//     ));
//   } else {
//     String res = jsonDecode(response.body)["errors"][0] ?? "";
//     Utils.showToast(res);
//   }
// }
}
