import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:tanami_app/core/styles/app_color.dart';
import 'package:tanami_app/core/styles/app_text.dart';
import 'package:tanami_app/features/login/presentation/bloc/login_bloc.dart';
import 'package:tanami_app/shared/components/password_text_form_field.dart';
import 'package:tanami_app/shared/components/text_widget.dart';

import '../../core/routes/route_name.dart';
import '../../core/routes/routes.dart';
import '../../core/utils/language/localizations_delegate.dart';
import '../../features/forgotPassword/presentation/bloc/restore_password_phone_verification_bloc.dart';
import '../../features/register/presentation/bloc/register_bloc.dart';
import 'text_from_field_widget.dart';

class FormLabelTextField extends StatelessWidget {
  const FormLabelTextField({
    super.key,
    required this.title,
    required this.type,
    required this.textEditingController,
    required this.hintText,
    this.prefixWidget,
    this.onChangeFun,
    this.originalPasswordController,
  });
  final String title;
  final String type;
  final String hintText;
  final TextEditingController textEditingController;
  final Widget? prefixWidget;
  final Function(String)? onChangeFun;
  final TextEditingController? originalPasswordController;

  @override
  Widget build(BuildContext context) {
    // Map of country codes to phone number lengths
    final Map<String, int> countryPhoneLengths = {
      "+973": 8, // Bahrain
      "+965": 8, // Kuwait
      "+968": 8, // Oman
      "+974": 8, // Qatar
      "+966": 9, // Saudi Arabia
      "+971": 9, // United Arab Emirates
      "+91": 10,
    };
    var registerBloc = context.read<RegisterBloc>();
    var loginBloc = context.read<LoginBloc>();
    var restorePasswordBloc =
        context.read<RestorePasswordPhoneVerificationBloc>();
    var localizations = AppLocalizations.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TextWidget().text14W500(
          title,
          clr: AppColor.textLabelColor,
          txtAlign: type == "description" ? TextAlign.start : TextAlign.center,
        ),
        const Gap(10),
        (type == "password" ||
                type == "repeat-password" ||
                type == "login-password")
            ? PasswordField(
                controller: textEditingController,
                hintText: hintText,
                originalPasswordController: originalPasswordController,
                type: type,
              )
            : textFormField(
                onInput: onChangeFun,
                validator: (value) {
                  if (type == "phone number") {
                    if (value != null && value.isEmpty) {
                      return localizations.translate(AppText.enterPhoneNo);
                    }
                    if (registerBloc.isdcode.isNotEmpty) {
                      // Validate phone number length based on selected country
                      if (countryPhoneLengths.containsKey(
                        registerBloc.isdcode,
                      )) {
                        final expectedLength =
                            countryPhoneLengths[registerBloc.isdcode];
                        if (value.length != expectedLength) {
                          return localizations.translate(
                            "Invalid Phone Number",
                          );
                        }
                      }
                    } else if (loginBloc.isdcode.isNotEmpty) {
                      // Validate phone number length based on selected country
                      if (countryPhoneLengths.containsKey(
                        loginBloc.isdcode,
                      )) {
                        final expectedLength =
                            countryPhoneLengths[loginBloc.isdcode];
                        if (value.length != expectedLength) {
                          return localizations.translate(
                            "Invalid Phone Number",
                          );
                        }
                      }
                    } else if (restorePasswordBloc.isdcode.isNotEmpty) {
                      // Validate phone number length based on selected country
                      if (countryPhoneLengths.containsKey(
                        restorePasswordBloc.isdcode,
                      )) {
                        final expectedLength =
                            countryPhoneLengths[restorePasswordBloc.isdcode];
                        if (value.length != expectedLength) {
                          return localizations.translate(
                            "Invalid Phone Number",
                          );
                        }
                      }
                    }

                    return null;
                  } else if (type == "country selection") {
                    if (textEditingController.text.isEmpty) {
                      return localizations.translate(AppText.chooseCountry);
                    }
                    return null;
                  } else if (type == "description") {
                    if (textEditingController.text.isEmpty) {
                      return localizations
                          .translate(AppText.pleaseEnteraDescription);
                    }
                    return null;
                  } else if (type == "email") {
                    if (value == null || value.isEmpty) {
                      return 'Please enter an email address.';
                    }
                    // Email validation
                    if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
                      return 'Please enter a valid email address.';
                    }
                    return null;
                  } else {
                    return null;
                  }
                },
                inputFormatters: (type == "first name")
                    ? [
                        LengthLimitingTextInputFormatter(35),
                      ]
                    : (type == "phone number")
                        ? registerBloc.isdcode.isNotEmpty
                            ? [
                                LengthLimitingTextInputFormatter(
                                    countryPhoneLengths[registerBloc.isdcode]),
                              ]
                            : restorePasswordBloc.isdcode.isNotEmpty
                                ? [
                                    LengthLimitingTextInputFormatter(
                                        countryPhoneLengths[
                                            restorePasswordBloc.isdcode]),
                                  ]
                                : [
                                    LengthLimitingTextInputFormatter(
                                        countryPhoneLengths[loginBloc.isdcode]),
                                  ]
                        : [
                            LengthLimitingTextInputFormatter(350),
                          ],
                maxlines: type == "description" ? 6 : 1,
                texttype: type == "phone number"
                    ? TextInputType.phone
                    : type == "Email"
                        ? TextInputType.emailAddress
                        : TextInputType.name,
                textEditingController: textEditingController,
                readonly: type == "country selection" ? true : false,
                hintText: hintText,
                leadingIcon: prefixWidget,
                suffixIcon: type == "country selection"
                    ? const Icon(
                        Icons.arrow_forward_ios_rounded,
                        color: Color(0xFFB4B4B4),
                      )
                    : const SizedBox(),
                onTap: () {
                  if (type == "country selection") {
                    goRouter.pushNamed(RouteName.chooseCountryScreen);
                  }
                })
      ],
    );
  }
}
