import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gap/gap.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:tanami_app/core/styles/app_text.dart';

import '../../../../core/styles/app_color.dart';
import '../../../../core/utils/language/localizations_delegate.dart';
import '../../../../core/utils/phone_number_hint_generator/phone_number_hint_generator.dart';
import '../../../../shared/api/api_endpoints.dart';
import '../../../../shared/components/form_label_textfield.dart';
import '../../../countrySelection/bloc/GetCountry/get_country_bloc.dart';
import '../../../countrySelection/bloc/GetCountry/get_country_state.dart';
import '../../../countrySelection/bloc/choose_country_bloc.dart';
import '../../../countrySelection/bloc/choose_country_state.dart';
import '../bloc/restore_password_phone_verification_bloc.dart';

class RestorePasswordPhoneVerificationForm extends StatelessWidget {
  const RestorePasswordPhoneVerificationForm({super.key});

  @override
  Widget build(BuildContext context) {
    String flag = "";
    final countrydata = context.read<GetCountryBlock>();
    var localizations = AppLocalizations.of(context);
    final restorePasswordBloc =
        context.read<RestorePasswordPhoneVerificationBloc>();

    // Reset fields when the screen is built
    restorePasswordBloc.resetFields();
    String hintText = '00 000 000';

    return BlocConsumer<RadioBloc, RadioState>(listener: (context, state) {
      int selectedCountry = -1;
      if (state is RadioSelectionChanged) {
        final countryState = countrydata.state;
        selectedCountry = state.selectedIndex;
        if (countryState is CountryLoaded) {
          restorePasswordBloc.isdcode =
              "${countryState.countryModel.data![selectedCountry].iSDcode}";
          restorePasswordBloc.countrySelectionTextField.text = countryState
              .countryModel.data![selectedCountry].countryName
              .toString();
          restorePasswordBloc.phoneNumberTextField.text = "";
          if (PhoneNumberHintGenerator().countryPhoneLengths.containsKey(
                restorePasswordBloc.isdcode,
              )) {
            final expectedLength = PhoneNumberHintGenerator()
                .countryPhoneLengths[restorePasswordBloc.isdcode];
            hintText = PhoneNumberHintGenerator().formatPhoneNumber(
                restorePasswordBloc.isdcode, expectedLength!);
          }
          restorePasswordBloc.countryId =
              countryState.countryModel.data![selectedCountry].id!.toString();
          flag =
              "${ApiEndpoints.base}${countryState.countryModel.data![selectedCountry].flagIcon}";
        }
      }
    }, builder: (context, state) {
      int selectedCountry = -1;
      if (state is RadioSelectionChanged) {
        selectedCountry = state.selectedIndex;
      }
      return Form(
        key: restorePasswordBloc.formKey,
        child: Padding(
          padding: const EdgeInsets.symmetric(
            horizontal: 14,
          ),
          child: Align(
            alignment: Alignment.topLeft,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Gap(50),
                FormLabelTextField(
                  prefixWidget: selectedCountry == -1
                      ? null
                      : Padding(
                          padding: EdgeInsets.only(left: 12.w),
                          child: SizedBox(
                            height: 50.h,
                            width: 30.w,
                            child: Align(
                              alignment: Alignment.centerLeft,
                              child: SizedBox(
                                height: 30.h,
                                width: 30.w,
                                child: ClipRRect(
                                  borderRadius: const BorderRadius.all(
                                      Radius.circular(100)),
                                  child: CachedNetworkImage(
                                      maxHeightDiskCache: 200,
                                      maxWidthDiskCache: 200,
                                      cacheKey: restorePasswordBloc
                                          .countrySelectionTextField.text,
                                      key: UniqueKey(),
                                      imageUrl: "${ApiEndpoints.baseurl}$flag",
                                      height: 30.h,
                                      width: 30.w,
                                      placeholder: (context, url) => SizedBox(
                                            height: 30.h,
                                            width: 30.w,
                                            child:
                                                const CircularProgressIndicator(),
                                          ),
                                      errorWidget: (context, url, error) =>
                                          const Icon(Icons.error),
                                      fit: BoxFit.cover),
                                ),
                              ),
                            ),
                          ),
                        ),
                  hintText: localizations.translate(AppText.chooseCountry),
                  title: localizations.translate(AppText.countryOfResidence),
                  type: "country selection",
                  textEditingController:
                      restorePasswordBloc.countrySelectionTextField,
                ),
                const Gap(20),
                FormLabelTextField(
                  prefixWidget: selectedCountry == -1
                      ? null
                      : Row(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            const Gap(10),
                            SizedBox(
                              height: 50.h,
                              width: 30.w,
                              child: Align(
                                alignment: Alignment.centerLeft,
                                child: SizedBox(
                                  height: 30.h,
                                  width: 30.w,
                                  child: ClipRRect(
                                    borderRadius: const BorderRadius.all(
                                        Radius.circular(100)),
                                    child: CachedNetworkImage(
                                        maxHeightDiskCache: 200,
                                        maxWidthDiskCache: 200,
                                        key: UniqueKey(),
                                        imageUrl: flag,
                                        height: 30.h,
                                        width: 30.w,
                                        placeholder: (context, url) => SizedBox(
                                              height: 30.h,
                                              width: 30.w,
                                              child:
                                                  const CircularProgressIndicator(),
                                            ),
                                        errorWidget: (context, url, error) =>
                                            const Icon(Icons.error),
                                        fit: BoxFit.cover),
                                  ),
                                ),
                              ),
                            ),
                            const Gap(5),
                            Container(
                                margin: const EdgeInsets.only(top: 10),
                                height: 30.h,
                                width: 40.w,
                                child: Text(
                                  restorePasswordBloc.isdcode,
                                  style: GoogleFonts.dmSans(
                                    color: AppColor.charcoalColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.w500,
                                  ),
                                )),
                          ],
                        ),
                  hintText: hintText,
                  title: localizations.translate(AppText.phoneNumber),
                  type: "phone number",
                  textEditingController:
                      restorePasswordBloc.phoneNumberTextField,
                ),
              ],
            ),
          ),
        ),
      );
    });
  }
}
