import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_pos_ecommerce/core/components/custom_date_picker.dart';
import 'package:flutter_pos_ecommerce/core/components/dashed_line.dart';
import 'package:flutter_pos_ecommerce/core/components/spaces.dart';
import 'package:flutter_pos_ecommerce/core/extensions/date_time_ext2.dart';
import 'package:flutter_pos_ecommerce/core/extensions/int_ext.dart';
import 'package:flutter_pos_ecommerce/module/pos/presentation/report/bloc/transaction_report/transaction_report_bloc.dart';
import 'package:flutter_pos_ecommerce/module/pos/presentation/report/widgets/report_title.dart';

class ReportPage extends StatefulWidget {
  const ReportPage({super.key});

  @override
  State<ReportPage> createState() => _ReportPageState();
}

class _ReportPageState extends State<ReportPage> {
  int selectedMenu = 0;
  String title = 'Laporan Penjualan';
  DateTime fromDate = DateTime.now().subtract(const Duration(days: 30));
  DateTime toDate = DateTime.now();

  @override
  Widget build(BuildContext context) {
    String searchDateFormatted =
        '${fromDate.toFormattedDate2()} to ${toDate.toFormattedDate2()}';
    final isMobile = MediaQuery.of(context).size.width < 600;

    return Scaffold(
      body: SafeArea(
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const ReportTitle(),
                Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: isMobile
                      ? Column(
                          children: [
                            CustomDatePicker(
                              prefix: const Text('Dari: '),
                              initialDate: fromDate,
                              onDateSelected: (selectedDate) {
                                setState(() {
                                  fromDate = selectedDate;
                                });
                              },
                            ),
                            const SpaceHeight(10.0),
                            CustomDatePicker(
                              prefix: const Text('Sampai: '),
                              initialDate: toDate,
                              onDateSelected: (selectedDate) {
                                setState(() {
                                  toDate = selectedDate;
                                });
                              },
                            ),
                            const SpaceHeight(10.0),
                            ElevatedButton(
                              onPressed: () {
                                setState(() {});
                                context.read<TransactionReportBloc>().add(
                                    TransactionReportEvent.getReport(
                                        startDate: DateTime.now(),
                                        endDate: DateTime.now().subtract(
                                            const Duration(days: 30))));
                              },
                              child: const Text("Cari"),
                            ),
                            // MenuButton(
                            //     iconPath: Assets.icons.search.path,
                            //     label: 'Cari',
                            //     onPressed: () {
                            //       setState(() {});
                            //       context.read<TransactionReportBloc>().add(
                            //           TransactionReportEvent.getReport(
                            //               startDate: DateTime.now(),
                            //               endDate: DateTime.now().subtract(
                            //                   const Duration(days: 30))));
                            //     }),
                          ],
                        )
                      : Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Flexible(
                              child: CustomDatePicker(
                                prefix: const Text('Dari: '),
                                initialDate: fromDate,
                                onDateSelected: (selectedDate) {
                                  setState(() {
                                    fromDate = selectedDate;
                                  });
                                },
                              ),
                            ),
                            const SpaceWidth(10.0),
                            Flexible(
                              child: CustomDatePicker(
                                prefix: const Text('Sampai: '),
                                initialDate: toDate,
                                onDateSelected: (selectedDate) {
                                  setState(() {
                                    toDate = selectedDate;
                                  });
                                },
                              ),
                            ),
                            const SpaceWidth(10.0),
                            ElevatedButton(
                                onPressed: () {
                                  setState(() {});
                                  context.read<TransactionReportBloc>().add(
                                      TransactionReportEvent.getReport(
                                          startDate: DateTime.now(),
                                          endDate: DateTime.now().subtract(
                                              const Duration(days: 30))));
                                },
                                child: const Text("Cari"))
                          ],
                        ),
                ),
              ],
            ),
            BlocBuilder<TransactionReportBloc, TransactionReportState>(
              builder: (context, state) {
                final totalRevenue = state.maybeMap(
                  orElse: () => 0,
                  loaded: (value) {
                    return value.transactionReport.fold(
                      0,
                      (previousValue, element) =>
                          previousValue + element.total_cost,
                    );
                  },
                );
                print("totalRevenue $totalRevenue");
                final subTotal = state.maybeMap(
                  orElse: () => 0,
                  loaded: (value) {
                    return value.transactionReport.fold(
                      0,
                      (previousValue, element) =>
                          previousValue + element.subtotal,
                    );
                  },
                );

                print("subtotal $subTotal");

                final discount = state.maybeMap(
                  orElse: () => 0,
                  loaded: (value) {
                    return value.transactionReport.fold(
                      0,
                      (previousValue, element) =>
                          previousValue + element.discount,
                    );
                  },
                );

                print("diskon $discount");
                return state.maybeWhen(orElse: () {
                  return const Center(
                    child: Text('Tidak ada Data'),
                  );
                }, loading: () {
                  return const Center(
                    child: CircularProgressIndicator(),
                  );
                }, loaded: (transactionReport) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Center(
                        child: Text(
                          title,
                          style: const TextStyle(
                              fontWeight: FontWeight.w600, fontSize: 16.0),
                        ),
                      ),
                      Center(
                        child: Text(
                          searchDateFormatted,
                          style: const TextStyle(fontSize: 16.0),
                        ),
                      ),
                      const SpaceHeight(16.0),

                      // REVENUE PEN
                      ...[
                        Text('PENDAPATAN : ${totalRevenue.currencyFormatRp}'),
                        const SpaceHeight(8.0),
                        const DashedLine(),
                        const DashedLine(),
                        const SpaceHeight(8.0),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text('Subtotal'),
                            Text(subTotal.currencyFormatRp),
                          ],
                        ),
                        const SpaceHeight(4.0),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text('Diskon'),
                            Text('$discount'),
                          ],
                        ),
                        const SpaceHeight(8.0),
                        const DashedLine(),
                        const DashedLine(),
                        const SpaceHeight(8.0),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text('TOTAL'),
                            Text(totalRevenue.currencyFormatRp),
                          ],
                        ),
                      ],
                      const SpaceHeight(32.0),
                    ],
                  );
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}
