import 'package:enaklo_pos/core/components/buttons.dart';
import 'package:enaklo_pos/core/components/spaces.dart';
import 'package:enaklo_pos/core/extensions/build_context_ext.dart';
import 'package:enaklo_pos/core/function/app_function.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/payment/pages/payment_page.dart';
import 'package:enaklo_pos/presentation/refund/pages/refund_page.dart';
import 'package:enaklo_pos/presentation/sales/blocs/order_loader/order_loader_bloc.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_payment_summary.dart';
import 'package:enaklo_pos/presentation/split_bill/pages/split_bill_page.dart';
import 'package:enaklo_pos/presentation/void/pages/void_page.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_list_order.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_order_information.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_payment.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_right_title.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../core/constants/colors.dart';
import '../widgets/sales_card.dart';
import '../widgets/sales_title.dart';

class SalesPage extends StatefulWidget {
  final String status;
  const SalesPage({super.key, required this.status});

  @override
  State<SalesPage> createState() => _SalesPageState();
}

class _SalesPageState extends State<SalesPage> {
  ScrollController scrollController = ScrollController();
  DateTime startDate = DateTime.now();
  DateTime endDate = DateTime.now();
  Order? orderDetail;

  String searchQuery = '';

  @override
  void initState() {
    context.read<OrderLoaderBloc>().add(OrderLoaderEvent.getByStatus(
        widget.status,
        dateFrom: startDate,
        dateTo: endDate));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: AppColors.background,
        body: Row(
          children: [
            Expanded(
              flex: 2,
              child: NotificationListener<ScrollNotification>(
                onNotification: (notification) {
                  if (notification is ScrollEndNotification &&
                      scrollController.position.extentAfter == 0) {
                    context.read<OrderLoaderBloc>().add(
                          OrderLoaderEvent.loadMore(
                            widget.status,
                            dateFrom: startDate,
                            dateTo: endDate,
                            search: searchQuery,
                          ),
                        );
                    return true;
                  }

                  return true;
                },
                child: Material(
                  color: AppColors.white,
                  child: Column(
                    children: [
                      SalesTitle(
                        title: widget.status == 'pending'
                            ? "Pending Pesanan"
                            : "Daftar Pesanan",
                        startDate: startDate,
                        endDate: endDate,
                        onChanged: (value) {
                          setState(() {
                            searchQuery = value;
                          });
                          Future.delayed(const Duration(milliseconds: 800), () {
                            context.read<OrderLoaderBloc>().add(
                                  OrderLoaderEvent.getByStatus(
                                    widget.status,
                                    dateFrom: startDate,
                                    dateTo: endDate,
                                    search: searchQuery,
                                  ),
                                );
                          });
                        },
                        onDateRangeChanged: (start, end) {
                          setState(() {
                            startDate = start ?? startDate;
                            endDate = end ?? endDate;
                          });

                          context.read<OrderLoaderBloc>().add(
                              OrderLoaderEvent.getByStatus(widget.status,
                                  dateFrom: startDate, dateTo: endDate));
                        },
                      ),
                      Expanded(
                        child: BlocBuilder<OrderLoaderBloc, OrderLoaderState>(
                          builder: (context, state) {
                            return state.maybeWhen(
                              orElse: () => const Center(
                                child: CircularProgressIndicator(),
                              ),
                              loading: () => const Center(
                                child: CircularProgressIndicator(),
                              ),
                              error: (message) => Center(
                                child: Text(
                                  message,
                                  style: TextStyle(
                                    fontSize: 16.0,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                              loaded: (orders, totalOrder, hasReachedMax,
                                  currentPage, isLoadingMore) {
                                if (orders.isEmpty) {
                                  return Center(
                                    child: Text(
                                      "Belum ada transaksi saat ini. ",
                                      style: TextStyle(
                                        fontSize: 16.0,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  );
                                } else {
                                  return ListView.builder(
                                    itemCount: orders.length,
                                    controller: scrollController,
                                    itemBuilder: (context, index) {
                                      return GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            orderDetail = orders[index];
                                          });
                                          context.read<OrderFormBloc>().add(
                                              OrderFormEvent.started(
                                                  orders[index]));
                                        },
                                        child: SalesCard(
                                          order: orders[index],
                                          isActive:
                                              orders[index] == orderDetail,
                                        ),
                                      );
                                    },
                                  );
                                }
                              },
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Expanded(
              flex: 4,
              child: orderDetail == null
                  ? Center(
                      child: Text(
                        "Belum ada order yang dipilih.",
                        style: TextStyle(
                          fontSize: 16.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    )
                  : Column(
                      children: [
                        SalesRightTitle(
                          order: orderDetail,
                          actionWidget: [
                            if (widget.status == 'pending') ...[
                              BlocBuilder<OrderFormBloc, OrderFormState>(
                                  builder: (context, state) {
                                return state.maybeWhen(
                                  orElse: () => Button.outlined(
                                    onPressed: () {},
                                    label: 'Void',
                                    icon: Icon(Icons.undo),
                                  ),
                                  loaded: (order, selectedItems,
                                          totalVoidOrRefund, isAllSelected) =>
                                      Button.outlined(
                                    onPressed: () {
                                      context.push(VoidPage(
                                        selectedOrder: order,
                                      ));
                                      //   showDialog(
                                      //   context: context,
                                      //   builder: (context) => VoidDialog(
                                      //     order: orderDetail!,
                                      //     selectedItems: selectedItems,
                                      //   ),
                                      // );
                                    },
                                    label: 'Void',
                                    icon: Icon(Icons.undo),
                                  ),
                                );
                              }),
                              SpaceWidth(8),
                              Button.outlined(
                                onPressed: () {
                                  context.push(
                                    SplitBillPage(
                                      order: orderDetail!,
                                    ),
                                  );
                                },
                                label: 'Split Bill',
                                icon: Icon(
                                  Icons.calculate_outlined,
                                ),
                              ),
                              SpaceWidth(8),
                              Button.filled(
                                width: 120,
                                onPressed: () {
                                  context.push(
                                    PaymentPage(
                                      order: orderDetail!,
                                    ),
                                  );
                                },
                                label: 'Bayar',
                                icon: Icon(Icons.payment, color: Colors.white),
                              ),
                            ],
                            if (widget.status == 'completed')
                              if (orderDetail?.isRefund == false)
                                Button.outlined(
                                  onPressed: () {
                                    context.push(RefundPage(
                                      selectedOrder: orderDetail!,
                                    ));
                                  },
                                  label: 'Refund',
                                  icon: Icon(Icons.autorenew),
                                ),
                            SpaceWidth(8),
                            Button.outlined(
                              onPressed: () {
                                if (widget.status == 'completed') {
                                  onPrintRecipt(
                                    context,
                                    order: orderDetail!,
                                    paymentMethod: orderDetail!.payments
                                            ?.map((p) => p.paymentMethodName)
                                            .join(', ') ??
                                        "",
                                    nominalBayar: orderDetail?.totalPaid ?? 0,
                                    kembalian: 0,
                                    productQuantity: orderDetail!.orderItems!
                                        .where((item) =>
                                            item.status != 'cancelled')
                                        .toList()
                                        .toProductQuantities(),
                                  );
                                } else {
                                  onPrintBill(
                                    context,
                                    productQuantity: orderDetail!.orderItems!
                                        .where((item) =>
                                            item.status != 'cancelled')
                                        .toList()
                                        .toProductQuantities(),
                                    order: orderDetail!,
                                  );
                                }
                              },
                              label: 'Print Bill',
                              icon: Icon(
                                Icons.print,
                              ),
                            ),
                            SpaceWidth(8),
                          ],
                        ),
                        Expanded(
                          child: SingleChildScrollView(
                            child: Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  // Order Header
                                  SalesOrderInformation(
                                    order: orderDetail,
                                  ),
                                  // Order Items
                                  SalesListOrder(order: orderDetail),
                                  const SpaceHeight(16),

                                  // Payment Summary
                                  SalesPaymentSummary(order: orderDetail),
                                  const SpaceHeight(16),

                                  // Payment Information
                                  if (orderDetail?.payments != null &&
                                      orderDetail?.payments!.isNotEmpty ==
                                          true) ...[
                                    SalesPayment(order: orderDetail),
                                    const SpaceHeight(20),
                                  ],
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
