import 'dart:developer';

import 'package:mc_common_app/config/dependency_injection.dart';
import 'package:mc_common_app/extensions/int_extensions.dart';
import 'package:mc_common_app/extensions/string_extensions.dart';
import 'package:mc_common_app/generated/locale_keys.g.dart';
import 'package:mc_common_app/models/user_models/country.dart';
import 'package:mc_common_app/models/user_models/role.dart';
import 'package:mc_common_app/repositories/user_repo.dart';
import 'package:mc_common_app/utils/utils.dart';
import 'package:mc_common_app/view_models/user_view_model.dart';
import 'package:mc_common_app/widgets/common_widgets/app_bar.dart';

import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart';
import 'package:mc_common_app/widgets/button/show_fill_button.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/widgets/tab/role_type_tab.dart';

import 'package:provider/provider.dart';
import '../../theme/colors.dart';

class RegisterProviderPage extends StatefulWidget {
  const RegisterProviderPage({Key? key}) : super(key: key);

  @override
  State<RegisterProviderPage> createState() => _RegisterPageState();
}

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

  int role = -1, countryId = -1;
  DropValue? selectedDrop;

  TextEditingController emailController = TextEditingController();

  Future<Role>? futureRoles;
  Future<Country>? futureCountries;
  UserVM? userVM;

  @override
  void initState() {
    super.initState();
    userVM = context.read<UserVM>();
    fetchData();
  }

  fetchData() {
    UserRepo userRepo = injector.get<UserRepo>();
    userRepo.getRoles().then((value) {
      setState(() {
        futureRoles = Future.value(value);
      });
    });
    userRepo.getAllCountries().then((value) {
      setState(() {
        futureCountries = Future.value(value);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    log("role: ${role}");
    return Scaffold(
      appBar: const CustomAppBar(isRemoveBackButton: false, title: ""),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: const EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: SizedBox(
            height: MediaQuery.of(context).size.height,
            child: Column(
              children: [
                12.height,
                LocaleKeys.signUp.tr().toText(
                      fontSize: 20,
                      letterSpacing: -1.44,
                    ),
                20.height,
                LocaleKeys.enterPhoneNumber.tr().toText(
                      color: MyColors.lightTextColor,
                      textAlign: TextAlign.center,
                      fontSize: 14,
                      height: 23 / 24,
                      letterSpacing: -0.48,
                    ),
                30.height,
                FutureBuilder<Role>(
                  future: futureRoles,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      List<DropValue> dropList = [];
                      snapshot.data?.data?.forEach((element) {
                        dropList.add(DropValue(element.id ?? 0, EasyLocalization.of(context)?.currentLocale?.countryCode == "SA" ? element.roleNameN ?? "" : element.roleName ?? "", ""));
                      });
                      if (role == -1) {
                        role = snapshot.data?.data?.first.id ?? -1;
                      }
                      return RoleTypeTab(
                        role == 6 ? 1 : 0,
                        dropList,
                        onSelect: (DropValue value) {
                          role = value.id;
                        },
                      );
                    } else {
                      return const CircularProgressIndicator();
                    }
                  },
                ),
                18.height,
                FutureBuilder<Country>(
                  future: futureCountries,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      List<DropValue> dropList = [];
                      snapshot.data?.data?.forEach((element) {
                        dropList.add(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().toText(
                                fontSize: 14,
                                color: MyColors.lightTextColor,
                                textAlign: TextAlign.center,
                              ),
                          10.height,
                          DropdownField(
                            (DropValue value) {
                              selectedDrop = value;
                              setState(() {
                                countryCode = value.subValue;
                                countryId = value.id;
                              });
                            },
                            dropdownValue: selectedDrop,
                            list: dropList,
                            hint: LocaleKeys.chooseCountry.tr(),
                          ),
                        ],
                      );
                    } else {
                      return const CircularProgressIndicator();
                    }
                  },
                ),
                18.height,
                LocaleKeys.enterPhoneForVerfication.tr().toText(
                      fontSize: 14,
                      color: MyColors.lightTextColor,
                      textAlign: TextAlign.center,
                    ),
                10.height,
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Utils.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,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Utils.mExp(1),
                  ],
                ),
                40.height,
                ShowFillButton(
                  title: LocaleKeys.continu.tr(),
                  maxWidth: double.infinity,
                  onPressed: () {
                    if (validation()) userVM!.performBasicOtpRegisterPage(context, countryCode: countryCode, phoneNum: phoneNum, role: role);
                    // 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("Please select Provider Role");
      isValid = false;
    } else if (countryCode.isEmpty) {
      Utils.showToast("Please select Country Code");
      isValid = false;
    } else if (phoneNum.isEmpty) {
      Utils.showToast("Please add Phone No");
      isValid = false;
    }
    return isValid;
  }
}

// class _RegisterPageState extends State<RegisterPage> {
//   String phoneNum = "", countryCode = "";
//
//   int role = 4, countryId = -1;
//
//   TextEditingController emailController = TextEditingController();
//
//   @override
//   Widget build(BuildContext context) {
//     final UserVM userVM = context.read<UserVM>();
//     return Scaffold(
//       appBar:CustomAppBar(
//           isRemoveBackButton: false, title: ""),
//       body: Container(
//         width: double.infinity,
//         height: double.infinity,
//         padding: const EdgeInsets.all(20),
//         child: SingleChildScrollView(
//           child: SizedBox(
//             height: MediaQuery.of(context).size.height,
//             child: Column(
//               children: [
//                 12.height,
//                 LocaleKeys.signUp.tr().toText(fontSize: 20, letterSpacing: -1.44,),
//                 20.height,
//                 LocaleKeys.enterPhoneNumber.tr().toText(
//                       color: MyColors.lightTextColor,
//                       textAlign: TextAlign.center,
//                       fontSize: 14,
//                   height: 23 / 24,
//                       letterSpacing: -0.48,
//                     ),
//                 30.height,
//                 FutureBuilder<Country>(
//                   future: userVM.getAllCountries(),
//                   builder: (context, snapshot) {
//                     if (snapshot.hasData) {
//                       List<DropValue> dropList = [];
//                       snapshot.data?.data?.forEach((element) {
//                         dropList.add(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().toText(
//                                 color: MyColors.lightTextColor,
//                                 textAlign: TextAlign.center,
//                                 fontSize: 14,
//                             height: 23 / 24,
//                                 letterSpacing: -0.48,
//                               ),
//                           10.height,
//                           DropdownField(
//                             (DropValue value) {
//                               setState(() {
//                                 countryCode = value.subValue;
//                                 countryId = value.id;
//                               });
//                             },
//                             list: dropList,
//                             hint: LocaleKeys.chooseCountry.tr(),
//                           ),
//                         ],
//                       );
//                     } else {
//                       return const CircularProgressIndicator();
//                     }
//                   },
//                 ),
//                 18.height,
//                 LocaleKeys.enterPhoneForVerfication.tr().toText(
//                       color: MyColors.lightTextColor,
//                       textAlign: TextAlign.center,
//                       fontSize: 14,
//                   height: 23 / 24,
//                       letterSpacing: -0.48,
//                     ),
//                 10.height,
//                 Row(
//                   mainAxisAlignment: MainAxisAlignment.center,
//                   crossAxisAlignment: CrossAxisAlignment.center,
//                   children: [
//                     Utils.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,
//                               ),
//                             ),
//                           ),
//                         ],
//                       ),
//                     ),
//                     Utils.mExp(1),
//                   ],
//                 ),
//                 40.height,
//                 ShowFillButton(
//                   title: LocaleKeys.continu.tr(),
//                   maxWidth: double.infinity,
//                   onPressed: () {
//                     if (validation()) userVM.performBasicOtpRegisterPage(context, countryCode: countryCode, phoneNum: phoneNum, role: role);
//                   },
//                 ),
//               ],
//             ),
//           ),
//         ),
//       ),
//     );
//   }
//
//   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;
//   }
// }
