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:gap/gap.dart';
import 'package:krow/core/application/routing/routes.gr.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/core/presentation/styles/kw_box_decorations.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/scroll_layout_helper.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_suggestion_input.dart';
import 'package:krow/features/profile/address/domain/bloc/address_bloc.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

@RoutePage()
class AddressScreen extends StatefulWidget implements AutoRouteWrapper {
  final bool isInEditMode;

  const AddressScreen({super.key, this.isInEditMode = true});

  @override
  State<AddressScreen> createState() => _AddressScreenState();

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

class _AddressScreenState extends State<AddressScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: KwAppBar(
        showNotification: widget.isInEditMode,
        titleText: 'location_and_availability'.tr(),
      ),
      body: BlocConsumer<AddressBloc, AddressState>(
        listenWhen: (previous, current) => previous.status != current.status,
        listener: (context, state) {
          if (state.status == StateStatus.success) {
            if (widget.isInEditMode) {
              Navigator.pop(context);
            } else {
              context.router.push(
                WorkingAreaRoute(),
              );
            }
          }
        },
        builder: (context, state) {
          return ModalProgressHUD(
            inAsyncCall: state.status == StateStatus.loading,
            child: ScrollLayoutHelper(
              padding: const EdgeInsets.all(16),
              upperWidget: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  if (!widget.isInEditMode) ...[
                    const Gap(4),
                     Text(
                      'what_is_your_address'.tr(),
                      style: AppTextStyles.headingH1,
                    ),
                    Text(
                      'let_us_know_your_home_base'.tr(),
                      style: AppTextStyles.bodyMediumReg
                          .copyWith(color: AppColors.blackGray),
                    ),
                    const Gap(24),
                  ]
                  else
                    const Gap(8),
                  KwSuggestionInput(
                    title: 'address'.tr(),
                    hintText: 'select_address'.tr(),
                    horizontalPadding: 16,
                    items: state.suggestions,
                    onQueryChanged: (query) {
                      context
                          .read<AddressBloc>()
                          .add(AddressQueryChangedEvent(query));
                    },
                    itemToStringBuilder: (item) => item.description,
                    onSelected: (item) {
                      context.read<AddressBloc>().add(AddressSelectEvent(item));
                    },
                  ),
                  const Gap(8),
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: KwBoxDecorations.primaryLight12,
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          ..._textBlock('country'.tr(), state.fullAddress?.country),
                          ..._textBlock('state'.tr(), state.fullAddress?.region),
                          ..._textBlock('city'.tr(), state.fullAddress?.city),
                          ..._textBlock('apt_suite_building'.tr(),
                              state.fullAddress?.streetNumber),
                          ..._textBlock(
                              'street_address'.tr(), state.fullAddress?.street),
                          ..._textBlock('zip_code'.tr(), state.fullAddress?.zipCode,
                              hasNext: false),
                        ]),
                  )
                ],
              ),
              lowerWidget: KwButton.primary(
                disabled: state.fullAddress == null,
                  label: widget.isInEditMode
                      ? 'save_changes'.tr()
                      : 'save_and_continue'.tr(),
                  onPressed: () {
                    if (widget.isInEditMode) {
                      context.read<AddressBloc>().add(SubmitAddressEvent());
                    } else {
                      context.router.push(WorkingAreaRoute(isInEditMode: false));
                    }
                  }),
            ),
          );
        },
      ),
    );
  }

  List<Widget> _textBlock(String key, String? value, {bool hasNext = true}) {
    return [
      ...[
        Text(
          key,
          style: AppTextStyles.captionReg.copyWith(color: AppColors.blackGray),
        ),
        const Gap(8),
        Text(
          value ?? '',
          style: AppTextStyles.bodyMediumMed,
        ),
        hasNext ? const Gap(24) : const Gap(0),
      ],
    ];
  }
}
