import 'dart:developer';

import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/application/routing/routes.gr.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_app_bar.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_loading_overlay.dart';
import 'package:krow/features/profile/personal_info/domain/bloc/personal_info_bloc.dart';
import 'package:krow/features/profile/personal_info/presentation/widgets/personal_info_form.dart';

@RoutePage()
class PersonalInfoScreen extends StatelessWidget implements AutoRouteWrapper {
  const PersonalInfoScreen({
    super.key,
    this.isInEditMode = false,
  });

  final bool isInEditMode;

  @override
  Widget wrappedRoute(BuildContext context) {
    return BlocProvider(
      create: (context) =>
          PersonalInfoBloc()..add(InitializeProfileInfoEvent(isInEditMode)),
      child: this,
    );
  }

  bool _handleBuildWhen(
    PersonalInfoState previous,
    PersonalInfoState current,
  ) {
    return previous.status != current.status;
  }

  bool _handleListenWhen(
    PersonalInfoState previous,
    PersonalInfoState current,
  ) {
    return previous.status != current.status ||
        previous.shouldRouteToVerification != current.shouldRouteToVerification;
  }

  Future<void> _handleListen(
    BuildContext context,
    PersonalInfoState state,
  ) async {
    if (state.shouldRouteToVerification) {
      final isEmailVerified = await context.pushRoute<bool>(
        EmailVerificationRoute(
          verifiedEmail: state.email,
          userPhone: state.phoneNumber,
        ),
      );

      if (!context.mounted) return;
      context.read<PersonalInfoBloc>().add(
            UpdateEmailVerificationStatus(
              isEmailVerified: isEmailVerified ?? false,
            ),
          );
      return;
    }

    if (state.status == StateStatus.success && context.mounted) {
      if (isInEditMode) {
        context.maybePop();
      } else {
        context.pushRoute(
          EmergencyContactsRoute(isInEditMode: false),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: KwAppBar(
        titleText: 'Personal Information'.tr(),
        showNotification: isInEditMode,
      ),
      body: SingleChildScrollView(
        primary: false,
        padding: const EdgeInsets.all(16),
        child: PersonalInfoForm(isInEditMode: isInEditMode),
      ),
      bottomNavigationBar: SafeArea(
        top: false,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: BlocConsumer<PersonalInfoBloc, PersonalInfoState>(
            buildWhen: _handleBuildWhen,
            listenWhen: _handleListenWhen,
            listener: _handleListen,
            builder: (context, state) {
              return KwLoadingOverlay(
                shouldShowLoading: state.status == StateStatus.loading,
                child: KwButton.primary(
                  label: isInEditMode ? 'save_changes'.tr() : 'save_and_continue'.tr(),
                  onPressed: () {
                    context
                        .read<PersonalInfoBloc>()
                        .add(const SaveProfileChanges());
                  },
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}
