import 'package:auto_route/auto_route.dart';
import 'package:collection/collection.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/models/event/event_model.dart';
import 'package:krow/core/entity/event_entity.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/theme.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_popup_button.dart';
import 'package:krow/features/create_event/domain/bloc/create_event_bloc.dart';
import 'package:krow/features/create_event/presentation/create_shift_details_section/create_shifts_list.dart';
import 'package:krow/features/create_event/presentation/event_date_section/bloc/date_selector_bloc.dart';
import 'package:krow/features/create_event/presentation/widgets/add_info_input_widget.dart';
import 'package:krow/features/create_event/presentation/widgets/addons_section_widget.dart';
import 'package:krow/features/create_event/presentation/widgets/create_event_details_card_widget.dart';
import 'package:krow/features/create_event/presentation/widgets/create_event_tags_card.dart';
import 'package:krow/features/create_event/presentation/widgets/create_event_title_widget.dart';
import 'package:krow/features/create_event/presentation/widgets/total_cost_row_widget.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

@RoutePage()
class CreateEventScreen extends StatelessWidget implements AutoRouteWrapper {
  final EventScheduleType? eventType;
  final EventModel? eventModel;

  const CreateEventScreen({super.key, this.eventType, this.eventModel});

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CreateEventBloc, CreateEventState>(
      listener: (context, state) {
        if (state.success) {
          context.router.maybePop();
        }

        if (state.valid) {
          context.router
              .push(EventDetailsRoute(event: state.entity, isPreview: true));
        }
        _checkValidation(state, context);
      },
      builder: (context, state) {
        return ModalProgressHUD(
          inAsyncCall: state.inLoading,
          child: Scaffold(
            appBar: KwAppBar(
              titleText: 'Create Event',
            ),
            body: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: CustomScrollView(
                primary: false,
                slivers: [
                  SliverList.list(
                    children: const [
                      CreateEventTitleWidget(),
                      CreateEventDetailsCardWidget(),
                      CreateEventTagsCard(),
                    ],
                  ),
                  const CreateShiftsList(),
                  const SliverGap(24),
                  sliverWrap(
                    KwButton.outlinedPrimary(
                      onPressed: () {
                        BlocProvider.of<CreateEventBloc>(context)
                            .add(CreateEventAddShift());
                      },
                      label: 'Add Shift',
                      leftIcon: Assets.images.icons.add,
                    ),
                  ),
                  const SliverGap(24),
                  sliverWrap(const AddonsSectionWidget()),
                  const SliverGap(24),
                  sliverWrap(const AddInfoInputWidget()),
                  const SliverGap(24),
                  sliverWrap( TotalCostRowWidget()),
                  const SliverGap(24),
                  SliverSafeArea(
                    top: false,
                    sliver: SliverPadding(
                      padding: const EdgeInsets.only(bottom: 36, top: 36),
                      sliver: sliverWrap(
                        KwPopUpButton(
                          disabled: state.validationState != null,
                          label: state.entity.id.isEmpty
                              ? 'Save as Draft'
                              : state.entity.status == EventStatus.draft
                                  ? 'Update Draft'
                                  : 'Update Event',
                          popUpPadding: 16,
                          items: [
                            KwPopUpButtonItem(
                                title: 'Preview',
                                onTap: () {
                                  BlocProvider.of<CreateEventBloc>(context)
                                      .add(CreateEventValidateAndPreview());
                                }),
                            if (state.entity.status == EventStatus.draft)
                              KwPopUpButtonItem(
                                  title: 'Delete Event Draft',
                                  onTap: () {
                                    BlocProvider.of<CreateEventBloc>(context)
                                        .add(DeleteDraftEvent());
                                    context.router.popUntilRoot();
                                    context.router.maybePop();
                                  },
                                  color: AppColors.statusError),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  sliverWrap(Widget widget) {
    return SliverToBoxAdapter(
      child: widget,
    );
  }

  void _checkValidation(CreateEventState state, BuildContext context) {
    if (state.validationState != null && !state.validationState!.showed) {
      state.validationState?.showed = true;
      for (var e in state.shifts) {
        e.bloc.state.validationState?.showed = true;
      }

      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(state.validationState?.message ?? ''),
        backgroundColor: AppColors.statusError,
      ));
    } else {
      var invalidShift = state.shifts
          .firstWhereOrNull((e) => e.bloc.state.validationState != null);

      if (invalidShift != null &&
          !invalidShift.bloc.state.validationState!.showed) {
        invalidShift.bloc.state.validationState?.showed = true;
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text(invalidShift.bloc.state.validationState?.message ?? ''),
          backgroundColor: AppColors.statusError,
        ));
        return;
      }

      var invalidRole = state.shifts
          .expand((shift) => shift.bloc.state.roles)
          .firstWhereOrNull((role) => role.bloc.state.validationState != null);

      if(invalidRole != null && !invalidRole.bloc.state.validationState!.showed) {
        invalidRole.bloc.state.validationState?.showed = true;
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text(invalidRole.bloc.state.validationState?.message ?? ''),
          backgroundColor: AppColors.statusError,
        ));
      }
    }
  }

  @override
  Widget wrappedRoute(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
            create: (_) =>
                CreateEventBloc()..add(CreateEventInit(eventType, eventModel))),
        BlocProvider(
            create: (_) => DateSelectorBloc()
              ..add(DateSelectorEventInit(eventType, eventModel))),
      ],
      child: this,
    );
  }
}
