import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:geolocator/geolocator.dart';
import 'package:krow/core/data/models/staff/pivot.dart';
import 'package:krow/core/entity/event_entity.dart';
import 'package:krow/core/entity/staff_contact_entity.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_box_decorations.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/staff_position_details_widget.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/core/presentation/widgets/ui_kit/kw_popup_button.dart';
import 'package:krow/features/events/domain/blocs/details/event_details_bloc.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

class StaffContactInfoPopup {
  static Future<void> show(
    BuildContext context,
    StaffContact staff,
    String department,
  ) async {
    var bloc = (BlocProvider.of<EventDetailsBloc>(context));
    return showDialog<void>(
        context: context,
        builder: (context) {
          return Center(
            child: _StaffPopupWidget(
              staff,
              bloc: bloc,
              department: department,
            ),
          );
        });
  }
}

class _StaffPopupWidget extends StatelessWidget {
  final StaffContact staff;

  final EventDetailsBloc bloc;

  final String department;

  const _StaffPopupWidget(this.staff,
      {required this.bloc, required this.department});

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<EventDetailsBloc, EventDetailsState>(
      listener: (context, state) {
        geoFencingServiceDialog(context, state);
      },
      bloc: bloc,
      builder: (context, state) {
        return ModalProgressHUD(
          inAsyncCall: state.inLoading,
          child: Center(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
              // margin: const EdgeInsets.symmetric(horizontal: 12),
              decoration: KwBoxDecorations.white24,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: _ongoingBtn(context),
              ),
            ),
          ),
        );
      },
    );
  }

  List<Widget> _ongoingBtn(BuildContext context) {
    return [
      const Gap(32),
      StaffPositionAvatar(
        imageUrl: staff.photoUrl,
        userName: '${staff.firstName} ${staff.lastName}',
        status: staff.status,
      ),
      const Gap(16),
      StaffContactsWidget(staff: staff),
      StaffPositionDetailsWidget(staff: staff),
      if (staff.status == PivotStatus.confirmed &&
          staff.parentPosition?.parentShift?.parentEvent?.status ==
              EventStatus.active)
        ..._confirmedBtn(context),
      if (staff.status == PivotStatus.confirmed &&
          staff.parentPosition?.parentShift?.parentEvent?.status ==
              EventStatus.confirmed)
        _buildReplaceStaffButton(context),
      if (staff.status == PivotStatus.ongoing) ...[
        KwButton.primary(
          onPressed: () {
            _clockOutDialog(context);
          },
          label: 'Clock Out',
        ),
      ],
      const Gap(12),
    ];
  }

  List<Widget> _confirmedBtn(BuildContext context) {
    return [
      KwButton.primary(
        onPressed: () {
          _clockinDialog(context);
        },
        label: 'Clock In',
      ),
      const Gap(8),
      _buildReplaceStaffButton(context),
    ];
  }

  Widget _buildReplaceStaffButton(BuildContext context) {
    return KwPopUpButton(
      label: 'Staff Didn’t Show Up',
      colorPallet: KwPopupButtonColorPallet.transparent(),
      withBorder: true,
      popUpPadding: 28,
      items: [
        KwPopUpButtonItem(
            title: 'Replace Staff',
            onTap: () {
              // Navigator.of(context).pop();
              _replaceStaff(context);
            },
            color: AppColors.statusError),
        KwPopUpButtonItem(
            title: 'Do Nothing',
            onTap: () {
              bloc.add(NotShowedPositionStaffEvent(staff.id));

              Navigator.of(context).pop();
            })
      ],
    );
  }

  void _replaceStaff(BuildContext context) async {
    var controller = TextEditingController();
    StateSetter? setStateInDialog;
    var inputError = false;
    var result = await KwDialog.show(
      context: context,
      icon: Assets.images.icons.profileDelete,
      title: 'Request Staff Replacement',
      message:
          'Please provide a reason for the staff replacement request in the text area below:',
      state: KwDialogState.negative,
      child: StatefulBuilder(builder: (context, setDialogState) {
        setStateInDialog = setDialogState;
        return KwTextInput(
          controller: controller,
          maxLength: 300,
          showCounter: true,
          showError: inputError,
          minHeight: 144,
          hintText: 'Enter your reason here...',
          title: 'Reason',
        );
      }),

      primaryButtonLabel: 'Submit Request',
      onPrimaryButtonPressed: (dialogContext) {
        if (controller.text.isEmpty) {
          setStateInDialog?.call(() {
            inputError = true;
          });
          return;
        }

        bloc.add(ReplacePositionStaffEvent(staff.id, controller.text));
        Navigator.of(dialogContext).pop(true);
      },
      secondaryButtonLabel: 'Cancel',
    );

    if (result && context.mounted) {
      await KwDialog.show(
        context: context,
        state: KwDialogState.negative,
        icon: Assets.images.icons.documentUpload,
        title: 'Request is Under Review',
        message:
            'Thank you! Your request for staff replacement is now under review. You will be notified of the outcome shortly.',
        primaryButtonLabel: 'Back to Event',
        onPrimaryButtonPressed: (dialogContext) {
          Navigator.of(dialogContext).pop();
          Navigator.of(context).maybePop();
        },
      );
    }
  }

  void geoFencingServiceDialog(BuildContext context, EventDetailsState state) {
    switch (state.geofencingDialogState) {
      case GeofencingDialogState.tooFar:
        KwDialog.show(
          context: context,
          icon: Assets.images.icons.alertTriangle,
          state: KwDialogState.warning,
          title: "You're too far",
          message: 'Please move closer to the designated location.',
          primaryButtonLabel: 'OK',
        );
        break;
      case GeofencingDialogState.locationDisabled:
        KwDialog.show(
          context: context,
          icon: Assets.images.icons.alertTriangle,
          state: KwDialogState.negative,
          title: 'Location Disabled',
          message: 'Please enable location services to continue.',
          primaryButtonLabel: 'Go to Settings',
          onPrimaryButtonPressed: (dialogContext) {
            Geolocator.openLocationSettings();
            Navigator.of(dialogContext).pop();
          },
        );
        break;
      case GeofencingDialogState.goToSettings:
        KwDialog.show(
          context: context,
          icon: Assets.images.icons.alertTriangle,
          state: KwDialogState.info,
          title: 'Permission Required',
          message: 'You need to allow location access in settings.',
          primaryButtonLabel: 'Open Settings',
          onPrimaryButtonPressed: (dialogContext) {
            Geolocator.openAppSettings();
            Navigator.of(dialogContext).pop();
          },
        );
        break;
      case GeofencingDialogState.permissionDenied:
        KwDialog.show(
          context: context,
          icon: Assets.images.icons.alertTriangle,
          state: KwDialogState.negative,
          title: 'Permission Denied',
          message: 'You have denied location access. Please allow it manually.',
          primaryButtonLabel: 'OK',
        );
        break;
      default:
        break;
    }
  }

  Future<dynamic> _clockinDialog(BuildContext context) {
    return KwDialog.show(
      context: context,
      icon: Assets.images.icons.profileAdd,
      state: KwDialogState.warning,
      title: 'Do you want to Clock In this Staff member?',
      primaryButtonLabel: 'Yes',
      onPrimaryButtonPressed: (dialogContext) async {
        bloc.add(TrackClientClockin(staff));
        await Navigator.of(dialogContext).maybePop();
        Navigator.of(context).maybePop();
      },
      secondaryButtonLabel: 'No',
    );
  }

  Future<dynamic> _clockOutDialog(BuildContext context) {
    return KwDialog.show(
      context: context,
      icon: Assets.images.icons.profileDelete,
      state: KwDialogState.warning,
      title: 'Do you want to Clock Out this Staff member?',
      primaryButtonLabel: 'Yes',
      onPrimaryButtonPressed: (dialogContext) async {
        bloc.add(TrackClientClockout(staff));
        await Navigator.of(dialogContext).maybePop();
        Navigator.of(context).maybePop();
      },
      secondaryButtonLabel: 'No',
    );
  }
}
