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

import '../../../application/order/order_loader/order_loader_bloc.dart';
import '../../../application/printer/print_struck/print_struck_bloc.dart';
import '../../../common/theme/theme.dart';
import '../../../injection.dart';
import '../../components/toast/flushbar.dart';
import 'widgets/order_left_panel.dart';
import 'widgets/order_right_panel.dart';

@RoutePage()
class OrderPage extends StatelessWidget implements AutoRouteWrapper {
  final String status;
  const OrderPage({super.key, required this.status});

  @override
  Widget build(BuildContext context) {
    return MultiBlocListener(
      listeners: [
        BlocListener<OrderLoaderBloc, OrderLoaderState>(
          listenWhen: (previous, current) =>
              previous.startDate != current.startDate ||
              previous.endDate != current.endDate,
          listener: (context, state) {
            context.read<OrderLoaderBloc>().add(
              OrderLoaderEvent.fetched(status: status, isRefresh: true),
            );
          },
        ),
        BlocListener<OrderLoaderBloc, OrderLoaderState>(
          listenWhen: (previous, current) => previous.search != current.search,
          listener: (context, state) {
            context.read<OrderLoaderBloc>().add(
              OrderLoaderEvent.fetched(status: status, isRefresh: true),
            );
          },
        ),
        BlocListener<PrintStruckBloc, PrintStruckState>(
          listenWhen: (previous, current) =>
              previous.failureOrPrintStruck != current.failureOrPrintStruck,
          listener: (context, state) {
            state.failureOrPrintStruck.fold(() {}, (either) {
              either.fold(
                (f) => AppFlushbar.showPrinterFailureToast(context, f),
                (success) {
                  AppFlushbar.showSuccess(context, "Struck berhasil dicetak");
                },
              );
            });
          },
        ),
      ],
      child: SafeArea(
        child: Scaffold(
          backgroundColor: AppColor.background,
          body: BlocBuilder<OrderLoaderBloc, OrderLoaderState>(
            builder: (context, state) {
              return Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Material(
                      color: AppColor.white,
                      child: OrderLeftPanel(state: state, status: status),
                    ),
                  ),
                  Expanded(flex: 4, child: OrderRightPanel(state: state)),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  Widget wrappedRoute(BuildContext context) => BlocProvider(
    create: (context) =>
        getIt<OrderLoaderBloc>()
          ..add(OrderLoaderEvent.fetched(status: status, isRefresh: true)),
    child: this,
  );
}
