import 'package:auto_route/auto_route.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/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/dialogs/kw_dialog.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_input.dart';
import 'package:krow/features/events/domain/blocs/details/event_details_bloc.dart';
import 'package:krow/features/events/presentation/event_details/widgets/event_qr_popup.dart';

class EventButtonGroupWidget extends StatelessWidget {
  final EventEntity item;

  final bool isPreview;

  const EventButtonGroupWidget(
      {super.key, required this.item, required this.isPreview});

  @override
  Widget build(BuildContext context) {
    if (isPreview) return const SizedBox.shrink();

    final now = DateTime.now();
    final startTime =
        item.startDate ?? DateTime.now(); // adjust property name if needed
    final hoursUntilStart = startTime.difference(now).inHours;
    final showDraftButton = hoursUntilStart >= 24;

    switch (item.status) {
      case EventStatus.confirmed:
        return Column(children: [
          _buildActiveButtonGroup(context),
          Gap(8),
          _buildConfirmedButtonGroup(context)
        ]);
      case EventStatus.active:
        return _buildActiveButtonGroup(context);
      case EventStatus.finished:
        return _buildCompletedButtonGroup(context);
      case EventStatus.pending:
      case EventStatus.assigned:
        return Column(children: [
          if (showDraftButton) _buildDraftButtonGroup(context),
          if (showDraftButton) Gap(8),
          _buildConfirmedButtonGroup(context)
        ]);
      case EventStatus.draft:
        return Column(children: [
          _buildDraftButtonGroup(context)
        ]);

      case EventStatus.completed:
      case EventStatus.closed:
      // return _buildClosedButtonGroup();
      default:
        return const SizedBox.shrink();
    }
  }

  Widget _buildActiveButtonGroup(BuildContext context) {
    return Column(
      children: [
        KwButton.primary(
          label: 'QR Code',
          onPressed: () {
            EventQrPopup.show(context, item);
          },
        ),
        const Gap(8),
        KwButton.outlinedPrimary(
          label: 'Clock Manually',
          onPressed: () {
            context.router.push(ClockManualRoute(
                staffContacts: item.shifts
                        ?.expand(
                            (s) => s.positions.expand((p) => p.staffContacts))
                        .toList() ??
                    []));
          },
        ),
      ],
    );
  }

  Widget _buildConfirmedButtonGroup(BuildContext context) {
    return KwButton.outlinedPrimary(
      label: 'Cancel Event',
      onPressed: () {
        BlocProvider.of<EventDetailsBloc>(context).add(CancelClientEvent());
      },
    ).copyWith(
        color: AppColors.statusError,
        textColors: AppColors.statusError,
        borderColor: AppColors.statusError);
  }

  Widget _buildDraftButtonGroup(BuildContext context) {
    return Column(
      children: [
        KwButton.accent(
          label: 'Edit Event',
          onPressed: () async {
            BlocProvider.of<EventDetailsBloc>(context).add(
              DisablePollingEvent(),
            );
            await context.router.push(
              CreateEventFlowRoute(children: [
                CreateEventRoute(
                  eventModel: item.dto,
                ),
              ]),
            );
            BlocProvider.of<EventDetailsBloc>(context).add(
              RefreshEventDetailsEvent(),
            );
            BlocProvider.of<EventDetailsBloc>(context).add(
              EnablePollingEvent(),
            );
          },
        ),
        // Gap(8),
        // KwButton.outlinedPrimary(
        //   label: 'Delete Event Draft',
        //   onPressed: () {
        //     BlocProvider.of<EventDetailsBloc>(context)
        //         .add(DetailsDeleteDraftEvent());
        //   },
        // ).copyWith(
        //     color: AppColors.statusError,
        //     textColors: AppColors.statusError,
        //     borderColor: AppColors.statusError),
      ],
    );
  }

  Widget _buildCompletedButtonGroup(context) {
    return Column(
      children: [
        KwButton.primary(
          label: 'Complete Event',
          onPressed: () {
            _completeEvent(context);
          },
        ),
      ],
    );
  }

  Widget _buildClosedButtonGroup() {
    return Column(
      children: [
        KwButton.primary(
          label: 'View Invoice',
          onPressed: () {},
        ),
      ],
    );
  }

  void _completeEvent(BuildContext context) async {
    var controller = TextEditingController();
    var result = await KwDialog.show(
      context: context,
      icon: Assets.images.icons.navigation.confetti,
      title: 'Complete Event',
      message: 'Please tell us how did the event went:',
      state: KwDialogState.info,
      child: KwTextInput(
        controller: controller,
        maxLength: 300,
        showCounter: true,
        minHeight: 144,
        hintText: 'Enter your note here...',
        title: 'Note (optional)',
      ),
      primaryButtonLabel: 'Complete Event',
      onPrimaryButtonPressed: (dialogContext) {
        BlocProvider.of<EventDetailsBloc>(context)
            .add(CompleteEventEvent(comment: controller.text));
        Navigator.of(dialogContext).pop(true);
      },
      secondaryButtonLabel: 'Cancel',
    );

    if (result) {
      await KwDialog.show(
        context: context,
        icon: Assets.images.icons.navigation.confetti,
        title: 'Thanks!',
        message:
            'Thank you for using our app! We hope you’ve had an awesome event!',
        primaryButtonLabel: 'Close',
      );
    }
  }
}
