import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/classes/app_state.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/theme/colors.dart';
import 'package:mc_common_app/utils/navigator.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/button/show_fill_button.dart';
import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:mc_common_app/widgets/txt_field.dart';
import 'package:provider/provider.dart';

class AddPhoneNumWidget extends StatefulWidget {
  const AddPhoneNumWidget({super.key});

  @override
  State<AddPhoneNumWidget> createState() => _AddPhoneNumWidgetState();
}

class _AddPhoneNumWidgetState extends State<AddPhoneNumWidget> {
  String phoneNum = "", countryCode = "";
  DropValue? countryCodeVal;
  late UserVM userVM;
  Country? _country;

  @override
  void initState() {
    super.initState();
    scheduleMicrotask(() {
      userVM = Provider.of(context, listen: false);
      getCountryList();
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            LocaleKeys.enterPhoneNumber.tr().toText(fontSize: 20, isBold: true, letterSpacing: -1.44),
            30.height,
            if (_country != null) ...[
              DropdownField(
                dropdownValue: countryCodeVal,
                (DropValue value) {
                  AppState().setUserRegisterCountrySelection = value;
                  countryCode = value.subValue;
                  countryCodeVal = value;
                  setState(() {});
                },
                list: _country!.data?.map((element) {
                  return DropValue(
                    element.id ?? 0,
                    "${element.countryName ?? ""} ${element.countryCode ?? ""}",
                    element.countryCode ?? "",
                  );
                }).toList() ?? [],
                hint: LocaleKeys.selectCountryCode.tr(),
              ),
              10.height,
              TxtField(
                keyboardType: TextInputType.phone,
                hint: LocaleKeys.enterPhoneNumber.tr(),
                value: phoneNum,
                isSidePaddingZero: true,
                onChanged: (v) {
                  // Remove country code if user enters it
                  String cleanedPhone = v.trim();

                  // If country code is selected and phone starts with it, remove it
                  if (countryCode.isNotEmpty && cleanedPhone.startsWith(countryCode)) {
                    cleanedPhone = cleanedPhone.substring(countryCode.length).trim();
                  }

                  // Also handle cases where user adds + before country code
                  if (countryCode.isNotEmpty && cleanedPhone.startsWith('+$countryCode')) {
                    cleanedPhone = cleanedPhone.substring(countryCode.length + 1).trim();
                  }

                  // Handle case where user just types + followed by digits matching country code
                  if (countryCode.isNotEmpty && cleanedPhone.startsWith('+')) {
                    String codeWithoutPlus = countryCode.replaceAll('+', '');
                    if (cleanedPhone.substring(1).startsWith(codeWithoutPlus)) {
                      cleanedPhone = cleanedPhone.substring(codeWithoutPlus.length + 1).trim();
                    }
                  }

                  setState(() {
                    phoneNum = cleanedPhone;
                  });
                },
              ),
            ] else ...[
              const Center(child: CircularProgressIndicator()),
            ],
            30.height,
            Row(
              children: [
                Expanded(
                  child: ShowFillButton(
                    title: LocaleKeys.cancel.tr(),
                    backgroundColor: MyColors.greyButtonColor,
                    txtColor: Colors.black,
                    onPressed: () {
                      pop(context);
                    },
                  ),
                ),
                12.width,
                Expanded(
                  child: ShowFillButton(
                    title: LocaleKeys.sendOTP.tr(),
                    onPressed: () {
                      //User Role: Dealer|Manager for a branch
                      FocusScope.of(context).unfocus();
                      if (validation()) {
                        userVM.performBasicOtpRegisterPage(context, countryCode: countryCode, phoneNum: phoneNum, role: 7, isNeedToPassToken: true, reloadPage: () {
                          pop(context);
                        });
                      }
                    },
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  bool validation() {
    bool isValid = true;
    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;
  }
}
