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/presentation/gen/assets.gen.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/dialogs/kw_dialog.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/features/invoice/data/models/invoice_decline_model.dart';
import 'package:krow/features/invoice/data/models/invoice_model.dart';
import 'package:krow/features/invoice/domain/blocs/invoice_details_bloc/invoice_details_bloc.dart';
import 'package:krow/features/invoice/domain/invoice_entity.dart';
import 'package:krow/features/invoice/presentation/screens/invoice_details/dialogs/dispute_info_dialog.dart';
import 'package:krow/features/invoice/presentation/screens/invoice_details/dialogs/invoice_dispute_dialog.dart';
import 'package:krow/features/invoice/presentation/screens/invoice_details/widgets/invoice_details_widget.dart';
import 'package:krow/features/invoice/presentation/screens/invoice_details/widgets/invoice_from_to_widget.dart';
import 'package:krow/features/invoice/presentation/screens/invoice_details/widgets/invoice_info_card.dart';
import 'package:krow/features/invoice/presentation/screens/invoice_details/widgets/invoice_total_widget.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

@RoutePage()
class InvoiceDetailsScreen extends StatelessWidget implements AutoRouteWrapper {
  final InvoiceListEntity invoice;

  const InvoiceDetailsScreen({required this.invoice, super.key});

  @override
  Widget wrappedRoute(BuildContext context) {
    return BlocProvider(
        create: (context) => InvoiceDetailsBloc(invoice.invoiceModel!),
        child: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: KwAppBar(
        titleText: 'Invoice Details',
      ),
      body: BlocConsumer<InvoiceDetailsBloc, InvoiceDetailsState>(
        listener: (context, state) {
          if (state.showErrorPopup != null) {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
              content: Text(state.showErrorPopup ?? ''),
            ));
          } else if (state.success) {
            context.router.maybePop();
          }
        },
        builder: (context, state) {
          return ModalProgressHUD(
            inAsyncCall: state.inLoading,
            child: ScrollLayoutHelper(
              padding: const EdgeInsets.only(left: 16, right: 16, bottom: 24),
              upperWidget: Column(
                children: [
                  InvoiceInfoCardWidget(item: state.invoiceModel??invoice.invoiceModel!),
                  Gap(12),
                  InvoiceFromToWidget(item: state.invoiceModel??invoice.invoiceModel!),
                  Gap(12),
                  InvoiceDetailsWidget(invoice: state.invoiceModel??invoice.invoiceModel!),
                  Gap(12),
                  InvoiceTotalWidget(),
                  Gap(24),
                ],
              ),
              lowerWidget: _buildButtons(context, state),
            ),
          );
        },
      ),
    );
  }

  _buildButtons(BuildContext context, InvoiceDetailsState state) {
    return Column(
      children: [
        if (invoice.invoiceModel?.status == InvoiceStatus.open) ...[
          KwButton.primary(
            label: 'Approve Invoice',
            onPressed: () {
              context.read<InvoiceDetailsBloc>().add(InvoiceApproveEvent());
            },
          ),
          Gap(8),
          KwButton.outlinedPrimary(
            label: 'Dispute Invoice',
            onPressed: () async {
              var result = await ShiftDeclineDialog.showCustomDialog(context);
              print(result);
              if (result != null) {
                context.read<InvoiceDetailsBloc>().add(InvoiceDisputeEvent(
                    reason: result['reason'], comment: result['comment']));
                KwDialog.show(
                  icon: Assets.images.icons.receiptSearch,
                  state: KwDialogState.negative,
                  context: context,
                  title: 'Request is \nUnder Review',
                  message:
                      'Thank you! Your request for invoice issue, it is now under review. You will be notified of the outcome shortly.',
                  primaryButtonLabel: 'Back to Event',
                  onPrimaryButtonPressed: (dialogContext) {
                    dialogContext.pop();
                  },
                  secondaryButtonLabel: 'Cancel',
                  onSecondaryButtonPressed: (dialogContext) {
                    dialogContext.pop();
                    context.router.maybePop();
                  },
                );
              }
            },
          ).copyWith(
              color: AppColors.statusError, borderColor: AppColors.statusError),
        ],
        if (invoice.invoiceModel?.status == InvoiceStatus.disputed) ...[
          _buildViewDispute(context, state.invoiceModel?.dispute),
        ],
      ],
    );
  }

  _buildViewDispute(BuildContext context, InvoiceDeclineModel? dispute) {
    return KwButton.primary(
      label: 'View Dispute',
      onPressed: () {
        DisputeInfoDialog.showCustomDialog(
          context,
          reason: dispute?.reason ?? '',
          details: dispute?.details ?? '',
          supportNote: dispute?.supportNote,
        );
      },
    );
  }
}
