import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/application/common/map_utils.dart';
import 'package:krow/core/application/routing/routes.gr.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/kw_text_styles.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/features/shifts/data/models/staff_shift.dart';
import 'package:krow/features/shifts/domain/blocs/shift_deteils_bloc/shift_details_bloc.dart';
import 'package:krow/features/shifts/domain/services/shift_completer_service.dart';
import 'package:krow/features/shifts/domain/shift_entity.dart';
import 'package:krow/features/shifts/presentation/widgets/shift_timer_widgets/shift_timer_widget.dart';

class ShiftTimerCardWidget extends StatelessWidget {
  const ShiftTimerCardWidget({super.key});

  bool _hasBorder(EventShiftRoleStaffStatus status) =>
      status == EventShiftRoleStaffStatus.ongoing;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ShiftDetailsBloc, ShiftDetailsState>(
      buildWhen: (previous, current) =>
          previous.isToFar != current.isToFar ||
          previous.shiftViewModel != current.shiftViewModel,
      builder: (context, state) {
        return Container(
          padding: const EdgeInsets.all(12),
          margin: const EdgeInsets.only(top: 8, left: 16, right: 16),
          decoration: KwBoxDecorations.primaryLight12.copyWith(
            border: _hasBorder(state.shiftViewModel.status)
                ? Border.all(color: AppColors.tintDarkGreen, width: 2)
                : null,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'timer'.tr().toUpperCase(),
                style: AppTextStyles.captionReg
                    .copyWith(color: AppColors.blackCaptionText),
              ),
              const Gap(16),
              ShiftTimerWidget(
                shiftStatus: state.shiftViewModel.status,
                clockIn: state.shiftViewModel.clockIn,
                clockOut: state.shiftViewModel.clockOut,
              ),
              _buildButton(
                context,
                state.isToFar,
                state.shiftViewModel,
              ),
            ],
          ),
        );
      },
    );
  }

  _buildButton(
    context,
    bool isToFar,
    ShiftEntity viewModel,
  ) {
    final status = viewModel.status;
    return Column(
      children: [
        if (isToFar && status == EventShiftRoleStaffStatus.confirmed ||
            status == EventShiftRoleStaffStatus.ongoing)
          _toFarMessage(status),
        const Gap(16),
        KwButton.primary(
          disabled: (status == EventShiftRoleStaffStatus.confirmed ||
                  status == EventShiftRoleStaffStatus.ongoing) &&
              isToFar != false,
          label: status == EventShiftRoleStaffStatus.confirmed
              ? 'clock_in'.tr()
              : 'clock_out'.tr(),
          onPressed: () async {
            if (status == EventShiftRoleStaffStatus.confirmed) {
              _onClockIn(context, viewModel.eventId);
            } else {
              await _onClocOut(context, viewModel.eventId, viewModel);
            }
          },
        ),
        if (isToFar && status == EventShiftRoleStaffStatus.confirmed) ...[
          const Gap(16),
          KwButton.outlinedPrimary(
            leftIcon: Assets.images.icons.routing,
            label: 'get_direction'.tr(),
            onPressed: () {
              MapUtils.openMapByLatLon(
                viewModel.locationLat,
                viewModel.locationLon,
              );
            },
          )
        ]
      ],
    );
  }

  Widget _toFarMessage(status) {
    return Container(
      margin: const EdgeInsets.only(top: 16),
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: AppColors.graySecondaryFrame,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Container(
            height: 28,
            width: 28,
            decoration: const BoxDecoration(
              color: AppColors.grayWhite,
              shape: BoxShape.circle,
            ),
            child: Assets.images.icons.alertCircle.svg(
              height: 12,
              width: 12,
              colorFilter:
                  const ColorFilter.mode(AppColors.blackBlack, BlendMode.srcIn),
            ),
          ),
          const Gap(8),
          Expanded(
            child: Text(
              status == EventShiftRoleStaffStatus.ongoing
                  ? 'reach_location_to_clock_out'.tr()
                  : 'reach_location_to_clock_in'.tr(),
              style: AppTextStyles.bodySmallMed,
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _onClocOut(
      BuildContext context, String eventId, ShiftEntity shift) async {
    if (!kDebugMode) {
      var qrResult = await context.router.push(const QrScannerRoute());
      if (!context.mounted) return;

      if (qrResult == null || qrResult != eventId) {
        KwDialog.show(
            context: context,
            icon: Assets.images.icons.alertTriangle,
            state: KwDialogState.negative,
            title: 'oops_something_wrong'.tr(),
            message: 'qr_code_error'.tr(),
            primaryButtonLabel: 'retry_scanning'.tr(),
            secondaryButtonLabel: 'cancel'.tr(),
            onPrimaryButtonPressed: (dialogContext) {
              Navigator.pop(dialogContext);
              _onClocOut(context, eventId, shift);
            });
        return;
      }
    }
    ShiftCompleterService().startCompleteProcess(context, shift,
        onComplete: () {

      BlocProvider.of<ShiftDetailsBloc>(context)
          .add(const ShiftCompleteEvent());
    });
  }

  void _onClockIn(BuildContext context, String eventId) async {
    if (kDebugMode) {
      BlocProvider.of<ShiftDetailsBloc>(context).add(const ShiftClockInEvent());
      return;
    }
    var result = await context.router.push(const QrScannerRoute());

    if (!context.mounted) return;

    if (result != null && result == eventId) {
      KwDialog.show(
          context: context,
          icon: Assets.images.icons.like,
          state: KwDialogState.positive,
          title: 'youre_good_to_go'.tr(),
          message: 'shift_timer_started'.tr(),
          child: Text(
            'lunch_break_reminder'.tr(),
            textAlign: TextAlign.center,
            style: AppTextStyles.bodyMediumMed,
          ),
          primaryButtonLabel: 'Continue to Dashboard');
      BlocProvider.of<ShiftDetailsBloc>(context).add(const ShiftClockInEvent());
    } else {
      KwDialog.show(
          context: context,
          icon: Assets.images.icons.alertTriangle,
          state: KwDialogState.negative,
          title: 'oops_something_wrong'.tr(),
          message: 'qr_code_error'.tr(),
          primaryButtonLabel: 'retry_scanning'.tr(),
          secondaryButtonLabel: 'cancel'.tr(),
          onPrimaryButtonPressed: (dialogContext) {
            Navigator.pop(dialogContext);
            _onClockIn(context, eventId);
          });
    }
  }
}
