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

import '../../../application/void/void_form/void_form_bloc.dart';
import '../../../common/theme/theme.dart';
import '../../../domain/order/order.dart';
import '../../components/spaces/space.dart';
import '../../components/toast/flushbar.dart';
import '../../router/app_router.gr.dart';
import 'widgets/void_left_panel.dart';
import 'widgets/void_right_panel.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocListener<VoidFormBloc, VoidFormState>(
      listenWhen: (previous, current) =>
          previous.failureOrVoid != current.failureOrVoid,
      listener: (context, state) {
        state.failureOrVoid.fold(
          () => null,
          (either) => either.fold(
            (f) => AppFlushbar.showOrderFailureToast(context, f),
            (success) {
              if (context.mounted) {
                context.router.replace(const VoidSuccessRoute());
              }
            },
          ),
        );
      },
      child: Scaffold(
        backgroundColor: AppColor.background,
        body: SafeArea(
          child: BlocBuilder<VoidFormBloc, VoidFormState>(
            builder: (context, state) {
              return Container(
                padding: const EdgeInsets.all(24),
                child: Row(
                  children: [
                    // Left Panel - Order Details & Items
                    Expanded(flex: 3, child: VoidLeftPanel(state: state)),
                    const SpaceWidth(24),
                    // Right Panel - Void Configuration
                    Expanded(flex: 2, child: VoidRightPanel(state: state)),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  Widget wrappedRoute(BuildContext context) {
    context.read<VoidFormBloc>().add(VoidFormEvent.setOrder(order));
    return this;
  }
}
