import 'package:car_customer_app/api/api_client.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/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/country.dart';
import 'package:car_customer_app/models/user/register_user.dart';
import 'package:car_customer_app/models/user/role.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/dialog/dialogs.dart';
import 'package:car_customer_app/widgets/dialog/otp_dialog.dart';
import 'package:car_customer_app/widgets/dropdown/dropdow_field.dart';
import 'package:car_customer_app/widgets/show_fill_button.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/txt_field.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';

import '../../classes/colors.dart';

class RegisterPage extends StatefulWidget {
  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  String phoneNum = "", countryCode = "";

  int role = 4, countryId = -1;

  TextEditingController emailController = TextEditingController();

  @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: Container(
            height: MediaQuery.of(context).size.height,
            child: Column(
              children: [
                12.height,
                LocaleKeys.signUp.tr().toText20(),
                20.height,
                LocaleKeys.enterPhoneNumber.tr().toText14(
                      color: MyColors.lightTextColor,
                      textAlign: TextAlign.center,
                    ),
                30.height,
                FutureBuilder<Country>(
                  future: UserApiClent().getAllCountries(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      List<DropValue> dropList = [];
                      snapshot.data?.data?.forEach((element) {
                        dropList.add(new DropValue(
                            element.id ?? 0,
                            EasyLocalization.of(context)?.currentLocale?.countryCode == "SA"
                                ? (element.countryNameN ?? "") + " " + (element.countryCode ?? "")
                                : (element.countryName ?? "") + " " + (element.countryCode ?? ""),
                            element.countryCode ?? ""));
                      });
                      return Column(
                        children: [
                          LocaleKeys.selectYourCountry.tr().toText14(
                                color: MyColors.lightTextColor,
                                textAlign: TextAlign.center,
                              ),
                          10.height,
                          DropdownField(
                            (DropValue value) {
                              setState(() {
                                countryCode = value.subValue;
                                countryId = value.id;
                              });
                            },
                            list: dropList,
                            hint: LocaleKeys.chooseCountry.tr(),
                          ),
                        ],
                      );
                    } else {
                      return CircularProgressIndicator();
                    }
                  },
                ),
                18.height,
                LocaleKeys.enterPhoneForVerfication.tr().toText14(
                      color: MyColors.lightTextColor,
                      textAlign: TextAlign.center,
                    ),
                10.height,
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    mExp(1),
                    Expanded(
                      flex: 3,
                      child: Row(
                        children: [
                          Text(
                            (countryCode.isEmpty ? "+00" : "+" + countryCode),
                            style: const TextStyle(
                              fontSize: 20,
                              color: MyColors.black,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const Text(
                            " | ",
                            style: TextStyle(
                              fontSize: 20,
                              color: MyColors.black,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Flexible(
                            child: TextField(
                              controller: emailController,
                              onChanged: (v){
                                phoneNum=v;
                              },
                              style: const TextStyle(
                                fontSize: 20,
                                color: MyColors.black,
                              ),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: MyColors.lightTextColor, fontSize: 20),
                                hintText: "546758594",
                                contentPadding: EdgeInsets.zero,
                                border: InputBorder.none,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    mExp(1),
                  ],
                ),

                40.height,
                ShowFillButton(
                  title: LocaleKeys.continu.tr(),
                  maxWidth: double.infinity,
                  onPressed: () {
                    if (validation()) performBasicOtp(context);
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<void> performBasicOtp(BuildContext context) async {
    Utils.showLoading(context);
    BasicOtp basicOtp = await UserApiClent().basicOtp(countryCode + phoneNum, roleId: role);
    Utils.hideLoading(context);
    if (basicOtp.messageStatus == 1) {
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          pop(context);
          Utils.showLoading(context);
          RegisterUser user = await UserApiClent().basicVerify(countryCode + phoneNum, code, basicOtp.data!.userToken ?? "");
          Utils.hideLoading(context);
          if (user.messageStatus == 1) {
            Utils.showToast(user.message ?? "");
            navigateReplaceWithName(context, AppRoutes.completeProfile, arguments: user);
          } else {
            Utils.showToast(user.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(basicOtp.message ?? "");
    }
  }

  bool validation() {
    bool isValid = true;
    if (role == -1) {
      Utils.showToast(LocaleKeys.selectProviderRole.tr());
      //("Please select Provider Role");
      isValid = false;
    } else if (countryCode.isEmpty) {
      Utils.showToast(LocaleKeys.selectCountryCode.tr());
      //("Please select Country Code");
      isValid = false;
    } else if (phoneNum.isEmpty) {
      Utils.showToast(LocaleKeys.addPhoneNo.tr());
      //("Please add Phone No");
      isValid = false;
    }
    return isValid;
  }
}
