import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/core/entity/event_entity.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_popup_button.dart';
import 'package:krow/features/events/domain/blocs/details/event_details_bloc.dart';
import 'package:krow/features/events/domain/events_repository.dart';
import 'package:krow/features/events/presentation/event_details/widgets/event_completed_by_card_widget.dart';
import 'package:krow/features/events/presentation/event_details/widgets/event_info_card_widget.dart';
import 'package:krow/features/events/presentation/event_details/widgets/shift/shift_widget.dart';
import 'package:krow/features/home/presentation/home_screen.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

import '../../domain/blocs/events_list_bloc/events_bloc.dart';
import '../../domain/blocs/events_list_bloc/events_event.dart';

@RoutePage()
class EventDetailsScreen extends StatefulWidget implements AutoRouteWrapper {
  final EventEntity event;
  final bool isPreview;

  const EventDetailsScreen(
      {super.key, required this.event, this.isPreview = false});

  @override
  State<EventDetailsScreen> createState() => _EventDetailsScreenState();

  @override
  Widget wrappedRoute(BuildContext context) {
    return BlocProvider(
      key: Key(event.id),
      create: (context) {
        return EventDetailsBloc(event, getIt<EventsRepository>(),isPreview)
        ..add(EventDetailsInitialEvent());
      },
      child: this,
    );
  }
}

class _EventDetailsScreenState extends State<EventDetailsScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: KwAppBar(
        titleText: widget.isPreview ? 'Event Preview' : 'Event Details',
      ),
      body: BlocConsumer<EventDetailsBloc, EventDetailsState>(
        listenWhen: (previous, current) =>
            previous.showErrorPopup != current.showErrorPopup ||
            previous.needDeepPop != current.needDeepPop,
        listener: (context, state) {
          if (state.needDeepPop) {
            context.router.popUntilRoot();
            homeContext?.maybePop();
            return;
          }

          if (state.showErrorPopup != null) {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
              content: Text(state.showErrorPopup ?? ''),
            ));
          }
        },
        builder: (context, state) {
          return ModalProgressHUD(
            inAsyncCall: state.inLoading,
            child: ScrollLayoutHelper(
                padding: const EdgeInsets.only(left: 16, right: 16, bottom: 24),
                upperWidget: Column(
                  children: [
                    EventInfoCardWidget(
                      item: state.event,
                      isPreview: widget.isPreview,
                    ),
                    EventCompletedByCardWidget(
                      completedBy: state.event.completedBy,
                      completedNote: state.event.completedNode,
                    ),
                    ListView.builder(
                      shrinkWrap: true,
                      primary: false,
                      itemCount: state.shifts.length,
                      itemBuilder: (context, index) {
                        return ShiftWidget(
                            index: index, shiftState: state.shifts[index]);
                      },
                    ),
                  ],
                ),
                lowerWidget: widget.isPreview
                    ? _buildPreviewButtons()
                    : const SizedBox.shrink()),
          );
        },
      ),
    );
  }

  Widget _buildPreviewButtons() {
    return Padding(
      padding: const EdgeInsets.only(top: 24),
      child: KwPopUpButton(
        label: widget.event.status == null ||
                widget.event.status == EventStatus.draft
            ? widget.event.id.isEmpty
                ? 'Save as Draft'
                : 'Update Draft'
            : 'Save Event',
        popUpPadding: 16,
        items: [
          KwPopUpButtonItem(
            title: 'Publish Event',
            onTap: () {
              BlocProvider.of<EventDetailsBloc>(context)
                  .add(DetailsPublishEvent());
            },
          ),
          if (widget.event.status == EventStatus.draft ||
              widget.event.status == null)
            KwPopUpButtonItem(
              title: widget.event.id.isEmpty ? 'Save as Draft' : 'Update Draft',
              onTap: () {
                BlocProvider.of<EventDetailsBloc>(context)
                    .add(CreateEventPostEvent());
              },
            ),
          KwPopUpButtonItem(
              title: widget.event.status == null ||
                      widget.event.status == EventStatus.draft
                  ? 'Edit Event Draft'
                  : 'Edit Event',
              onTap: () {
                context.router.maybePop();
              },
              color: AppColors.primaryBlue),
          if (widget.event.status == EventStatus.draft ||
              widget.event.status == null)
            KwPopUpButtonItem(
                title: 'Delete Event Draft',
                onTap: () {
                  BlocProvider.of<EventDetailsBloc>(context)
                      .add(DetailsDeleteDraftEvent());
                  BlocProvider.of<EventsBloc>(context)
                      .add(LoadTabEventEvent(tabIndex: 3, subTabIndex: 0));
                },
                color: AppColors.statusError),
        ],
      ),
    );
  }
}
