import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/profile_icon.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_input.dart';
import 'package:krow/features/profile/personal_info/domain/bloc/personal_info_bloc.dart';

class PersonalInfoForm extends StatefulWidget {
  const PersonalInfoForm({
    super.key,
    required this.isInEditMode,
  });

  final bool isInEditMode;

  @override
  State<PersonalInfoForm> createState() => _PersonalInfoFormState();
}

class _PersonalInfoFormState extends State<PersonalInfoForm> {
  final _firstNameController = TextEditingController();
  final _lastNameController = TextEditingController();
  final _middleNameController = TextEditingController();
  final _emailController = TextEditingController();
  late final _bloc = context.read<PersonalInfoBloc>();

  void _syncControllersWithState(PersonalInfoState state) {
    _firstNameController.text = state.firstName;
    _lastNameController.text = state.lastName;
    _middleNameController.text = state.middleName ?? '';
    _emailController.text = state.email;
  }

  @override
  void initState() {
    super.initState();

    _syncControllersWithState(_bloc.state);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (!widget.isInEditMode) ...[
          const Gap(4),
           Text(
            'lets_get_started'.tr(),
            style: AppTextStyles.headingH1,
            textAlign: TextAlign.start,
          ),
          const Gap(8),
          Text(
            'tell_us_about_yourself'.tr(),
            style: AppTextStyles.bodyMediumReg.copyWith(
              color: AppColors.blackGray,
            ),
            textAlign: TextAlign.start,
          ),
          const Gap(24),
        ],
        BlocBuilder<PersonalInfoBloc, PersonalInfoState>(
          buildWhen: (previous, current) =>
              previous.profileImageUrl != current.profileImageUrl ||
              previous.validationErrors != current.validationErrors,
          builder: (context, state) {
            return ProfileIcon(
              onChange: (imagePath) {
                _bloc.add(UpdateProfileImage(imagePath));
              },
              imagePath: state.profileImagePath,
              imageUrl: state.profileImageUrl,
              showError: state.validationErrors
                  .containsKey(ProfileRequiredField.avatar),
            );
          },
        ),
        const Gap(8),
        BlocConsumer<PersonalInfoBloc, PersonalInfoState>(
          buildWhen: (previous, current) {
            return previous.status != current.status ||
                previous.validationErrors != current.validationErrors;
          },
          listenWhen: (previous, current) =>
              previous.isUpdateReceived != current.isUpdateReceived,
          listener: (_, state) {
            if (!state.isUpdateReceived) return;

            _syncControllersWithState(state);
          },
          builder: (context, state) {
            return Column(
              children: [
                KwTextInput(
                  title: 'first_name'.tr(),
                  hintText: 'enter_first_name'.tr(),
                  controller: _firstNameController,
                  keyboardType: TextInputType.name,
                  textInputAction: TextInputAction.next,
                  textCapitalization: TextCapitalization.sentences,
                  showError: state.validationErrors
                      .containsKey(ProfileRequiredField.firstName),
                  helperText:
                      state.validationErrors[ProfileRequiredField.firstName],
                  onChanged: (firstName) {
                    _bloc.add(UpdateFirstName(firstName));
                  },
                ),
                const Gap(8),
                KwTextInput(
                  title: 'last_name'.tr(),
                  hintText: 'enter_last_name'.tr(),
                  controller: _lastNameController,
                  keyboardType: TextInputType.name,
                  textInputAction: TextInputAction.next,
                  textCapitalization: TextCapitalization.sentences,
                  showError: state.validationErrors
                      .containsKey(ProfileRequiredField.lastName),
                  helperText:
                      state.validationErrors[ProfileRequiredField.lastName],
                  onChanged: (lastName) {
                    _bloc.add(UpdateLastName(lastName));
                  },
                ),
                const Gap(8),
                KwTextInput(
                  title: 'middle_name_optional'.tr(),
                  hintText: 'enter_middle_name'.tr(),
                  controller: _middleNameController,
                  keyboardType: TextInputType.name,
                  textInputAction: TextInputAction.next,
                  textCapitalization: TextCapitalization.sentences,
                  onChanged: (middleName) {
                    _bloc.add(UpdateMiddleName(middleName));
                  },
                ),
                const Gap(8),
                KwTextInput(
                  title: 'email'.tr(),
                  hintText: 'email@website.com',
                  controller: _emailController,
                  keyboardType: TextInputType.emailAddress,
                  showError: state.validationErrors
                      .containsKey(ProfileRequiredField.email),
                  helperText:
                      state.validationErrors[ProfileRequiredField.email],
                  textInputAction: TextInputAction.done,
                  onChanged: (email) {
                    _bloc.add(UpdateEmail(email));
                  },
                ),
                // It is nor clear if we will need it in future.
                // if (widget.isInEditMode) ...[
                //   const Gap(8),
                //   KwPhoneInput(
                //     label: 'Phone',
                //     onChanged: (phoneNumber) {
                //       _bloc.add(UpdatePhoneNumber(phoneNumber));
                //     },
                //   ),
                // ]
              ],
            );
          },
        ),
        const Gap(40),
      ],
    );
  }
}
