import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../application/refund/refund_form/refund_form_bloc.dart';
import '../../../common/theme/theme.dart';
import '../../../domain/order/order.dart';
import '../../../injection.dart';
import '../../components/toast/flushbar.dart';
import '../../router/app_router.gr.dart';
import 'widgets/refund_left_panel.dart';
import 'widgets/refund_right_panel.dart';

@RoutePage()
class RefundPage extends StatelessWidget implements AutoRouteWrapper {
  final Order order;
  const RefundPage({super.key, required this.order});

  @override
  Widget build(BuildContext context) {
    return BlocListener<RefundFormBloc, RefundFormState>(
      listenWhen: (p, c) => p.failureOrRefund != c.failureOrRefund,
      listener: (context, state) {
        state.failureOrRefund.fold(
          () {},
          (either) => either.fold(
            (f) => AppFlushbar.showOrderFailureToast(context, f),
            (data) {
              if (context.mounted) {
                context.router.replace(RefundSuccessRoute(orderId: order.id));
              }
            },
          ),
        );
      },
      child: Scaffold(
        backgroundColor: AppColor.background,
        body: SafeArea(
          child: BlocBuilder<RefundFormBloc, RefundFormState>(
            builder: (context, state) {
              return Row(
                children: [
                  Expanded(flex: 2, child: RefundLeftPanel(state: state)),
                  Expanded(flex: 4, child: RefundRightPanel(state: state)),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  Widget wrappedRoute(BuildContext context) => BlocProvider(
    create: (_) =>
        getIt<RefundFormBloc>()..add(RefundFormEvent.setOrder(order)),
    child: this,
  );
}
