import 'dart:convert';

import 'package:car_customer_app/api/shared_prefrence.dart';
import 'package:car_customer_app/api/client/user_api_client.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/basic_otp.dart';
import 'package:car_customer_app/models/user/login_password.dart';
import 'package:car_customer_app/models/user/register_user.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/extensions/int_extensions.dart';
import 'package:car_customer_app/extensions/string_extensions.dart';
import 'package:car_customer_app/extensions/widget_extensions.dart';
import 'package:car_customer_app/widgets/show_fill_button.dart';
import 'package:car_customer_app/widgets/tab/login_email_tab.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:http/http.dart';

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

class LoginWithPassword extends StatefulWidget {
  @override
  State<LoginWithPassword> createState() => _LoginWithPasswordState();
}

class _LoginWithPasswordState extends State<LoginWithPassword> {
  int otpType = 1;

  ClassType type = ClassType.EMAIL;
  String phoneNum = "", password = "";
  String email = "";
  String countryCode = "";
  Country? _country;

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(context, title: ""),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Column(
            children: [
              12.height,
              LocaleKeys.login.tr().toText20(),
              // 20.height,
              // (type == ClassType.NUMBER ? LocaleKeys.enterPhoneNumber.tr() : LocaleKeys.enterEmail.tr()).toText14(
              //   color: MyColors.lightTextColor,
              //   textAlign: TextAlign.center,
              // ),
              30.height,
              LoginEmailTab(
                onSelection: (ClassType type) {
                  setState(() {
                    this.type = type;
                  });
                },
              ),
              10.height,
              Column(
                children: [
                  if (type == ClassType.NUMBER) getCountry(context),
                  10.height,
                  TxtField(
                    hint: type == ClassType.NUMBER ? LocaleKeys.enterPhoneNumber.tr() : LocaleKeys.enterEmail.tr(),
                    value: phoneNum,
                    isSidePaddingZero: true,
                    onChanged: (v) {
                      phoneNum = v;
                    },
                  ),
                  10.height,
                  TxtField(
                    hint: LocaleKeys.EnterPass.tr(),
                    value: password,
                    isPasswordEnabled: true,
                    isSidePaddingZero: true,
                    maxLines: 1,
                    onChanged: (v) {
                      password = v;
                    },
                  ),
                ],
              ),
              20.height,
              LocaleKeys.forgetPasswordQ.tr().toText14(color: MyColors.textColor),
              ShowFillButton(
                title: LocaleKeys.recover.tr(),
                isFlatButton: true,
                isBold: false,
                fontSize: 14,
                maxHeight: 24,
                txtColor: MyColors.darkPrimaryColor,
                onPressed: () {
                  navigateWithName(context, AppRoutes.forgetPassword);
                },
              ),
              30.height,
              ShowFillButton(
                title: LocaleKeys.continu.tr(),
                maxWidth: double.infinity,
                onPressed: () {
                  performBasicOtp(context);
                },
              ),
              20.height,
            ],
          ),
        ),
      ),
    );
  }

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

  Future<void> performBasicOtp(BuildContext context) async {
    Utils.showLoading(context);
    Response response = await UserApiClent().login_V1(type == ClassType.NUMBER ? countryCode + phoneNum : phoneNum, password);
    Utils.hideLoading(context);
    LoginPassword user = LoginPassword.fromJson(jsonDecode(response.body));
    if (user.messageStatus == 1) {
      SharedPrefManager.setPhoneOrEmail(type == ClassType.NUMBER ? countryCode + phoneNum : phoneNum);
      SharedPrefManager.setUserPassword(password);
      navigateReplaceWithName(context, AppRoutes.loginMethodSelection, arguments: user.data!.userToken);
    } else {
      Utils.showToast(user.message ?? "");
    }
  }
}
