import 'package:enaklo_pos/core/components/buttons.dart';
import 'package:enaklo_pos/core/components/custom_modal_dialog.dart';
import 'package:enaklo_pos/core/components/custom_text_field.dart';
import 'package:enaklo_pos/core/components/flushbar.dart';
import 'package:enaklo_pos/core/components/spaces.dart';
import 'package:enaklo_pos/core/constants/colors.dart';
import 'package:enaklo_pos/core/extensions/build_context_ext.dart';
import 'package:enaklo_pos/core/extensions/date_time_ext.dart';
import 'package:enaklo_pos/core/extensions/string_ext.dart';
import 'package:enaklo_pos/data/models/response/order_response_model.dart';
import 'package:enaklo_pos/presentation/home/bloc/order_form/order_form_bloc.dart';
import 'package:enaklo_pos/presentation/sales/blocs/order_loader/order_loader_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class VoidDialog extends StatefulWidget {
  final Order order;
  final List<OrderItem> selectedItems;
  const VoidDialog(
      {super.key, required this.order, required this.selectedItems});

  @override
  State<VoidDialog> createState() => _VoidDialogState();
}

class _VoidDialogState extends State<VoidDialog> {
  final TextEditingController _reasonController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return CustomModalDialog(
      title: 'Void',
      minWidth: context.deviceWidth * 0.5,
      contentPadding:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('No. Pesanan'),
              Text(
                widget.order.orderNumber ?? '',
                style: TextStyle(
                  color: AppColors.black,
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          SpaceHeight(8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('Tanggal'),
              Text(
                (widget.order.createdAt ?? DateTime.now()).toFormattedDate2(),
                style: TextStyle(
                  color: AppColors.black,
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          SpaceHeight(8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('Tagihan'),
              Text(
                widget.selectedItems.isEmpty
                    ? widget.order.totalAmount.toString().currencyFormatRpV2
                    : widget.selectedItems
                        .fold(
                          0,
                          (sum, item) =>
                              sum +
                              ((item.unitPrice ?? 0) * (item.quantity ?? 0)),
                        )
                        .toString()
                        .currencyFormatRpV2,
                style: TextStyle(
                  color: AppColors.black,
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          if (widget.selectedItems.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(top: 16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Pesanan yang akan di void',
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: AppColors.black,
                    ),
                  ),
                  SpaceHeight(12),
                  Column(
                    children: widget.selectedItems
                        .map((item) => _item(context, item))
                        .toList(),
                  ),
                ],
              ),
            ),
          SpaceHeight(16),
          CustomTextField(
            controller: _reasonController,
            label: 'Alasan',
          ),
          SpaceHeight(24),
          BlocListener<OrderFormBloc, OrderFormState>(
            listener: (context, state) {
              state.maybeWhen(
                orElse: () {},
                successMsg: () {
                  context.pop();
                  AppFlushbar.showSuccess(context, 'Void berhasil!');
                  context.read<OrderLoaderBloc>().add(
                        OrderLoaderEvent.getByStatus(
                          'pending',
                          dateFrom: DateTime.now(),
                          dateTo: DateTime.now(),
                        ),
                      );
                },
                error: (msg) {
                  AppFlushbar.showError(context, msg);
                },
              );
            },
            child: BlocBuilder<OrderFormBloc, OrderFormState>(
              builder: (context, state) {
                return state.maybeWhen(
                  orElse: () => Button.filled(
                    onPressed: () {
                      context.read<OrderFormBloc>().add(
                            OrderFormEvent.voidOrder(
                              orderId: widget.order.id ?? '',
                              reason: _reasonController.text,
                              items: widget.selectedItems,
                            ),
                          );
                    },
                    label: 'Refund',
                  ),
                  loading: () => Center(
                    child: const CircularProgressIndicator(),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Row _item(
    BuildContext context,
    OrderItem product,
  ) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(
          width: context.deviceWidth * 0.1,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                product.productName ?? '',
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
              Text(
                (product.unitPrice ?? 0).toString().currencyFormatRpV2,
                style: const TextStyle(
                  fontSize: 14,
                ),
              ),
            ],
          ),
        ),
        Text(
          'X${product.quantity}',
          style: const TextStyle(
            fontSize: 14,
          ),
        ),
        Text(
          (product.totalPrice ?? 0).toString().currencyFormatRpV2,
          style: const TextStyle(
            fontSize: 14,
          ),
        ),
      ],
    );
  }
}
