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

import '../../../../../../application/analytic/dashboard_analytic_loader/dashboard_analytic_loader_bloc.dart';
import '../../../../../../common/data/report_menu.dart';
import '../../../../../../common/extension/extension.dart';
import '../../../../../../common/theme/theme.dart';
import '../../../../../components/error/analytic_error_state_widget.dart';
import '../../../../../components/loader/loader_with_text.dart';
import '../../../../../components/spaces/space.dart';
import '../../../../../components/widgets/report/report_header.dart';
import '../../../../../components/widgets/report/report_summary_card.dart';
import '../widgets/dashboard/report_dashboard_order.dart';
import '../widgets/dashboard/report_dashboard_product_chart.dart';
import '../widgets/dashboard/report_dashboard_sales_chart.dart';
import '../widgets/dashboard/report_dashboard_top_product.dart';

class ReportDashboardSection extends StatelessWidget {
  final ReportMenu menu;
  final DashboardAnalyticLoaderState state;
  final DateTime startDate;
  final DateTime endDate;

  const ReportDashboardSection({
    super.key,
    required this.menu,
    required this.state,
    required this.startDate,
    required this.endDate,
  });

  @override
  Widget build(BuildContext context) {
    if (state.isFetching) {
      return const Center(child: LoaderWithText());
    }

    return state.failureOption.fold(
      () => RefreshIndicator(
        backgroundColor: AppColor.white,
        color: AppColor.primary,
        onRefresh: () {
          context.read<DashboardAnalyticLoaderBloc>().add(
            DashboardAnalyticLoaderEvent.fetched(
              startDate: startDate,
              endDate: endDate,
            ),
          );

          return Future.value();
        },
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            ReportHeader(menu: menu, startDate: startDate, endDate: endDate),
            _buildSummary(),
            Padding(
              padding: const EdgeInsets.only(top: 16),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    flex: 2,
                    child: ReportDashboardSalesChart(
                      sales: List.of(state.dashboardAnalytic.recentSales)
                        ..sort(
                          (a, b) => DateTime.parse(
                            a.date,
                          ).compareTo(DateTime.parse(b.date)),
                        ),
                    ),
                  ),
                  const SpaceWidth(12),
                  Expanded(
                    flex: 1,
                    child: ReportDashboardProductChart(
                      data: state.dashboardAnalytic.topProducts,
                    ),
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 16),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    flex: 2,
                    child: ReportDashboardTopProduct(
                      data: state.dashboardAnalytic.topProducts,
                    ),
                  ),
                  const SpaceWidth(12),
                  Expanded(
                    flex: 1,
                    child: ReportDashboardOrder(data: state.dashboardAnalytic),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      (f) => AnalyticErrorStateWidget(
        failure: f,
        menu: menu,
        onRefresh: () => context.read<DashboardAnalyticLoaderBloc>().add(
          DashboardAnalyticLoaderEvent.fetched(
            startDate: startDate,
            endDate: endDate,
          ),
        ),
      ),
    );
  }

  Padding _buildSummary() {
    final successfulOrders =
        state.dashboardAnalytic.overview.totalOrders -
        state.dashboardAnalytic.overview.voidedOrders -
        state.dashboardAnalytic.overview.refundedOrders;

    return Padding(
      padding: const EdgeInsets.only(top: 16),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.success,
                  icon: Icons.trending_up,
                  title: 'Total Penjualan',
                  value: state
                      .dashboardAnalytic
                      .overview
                      .totalSales
                      .currencyFormatRpV2,
                ),
              ),
              const SpaceWidth(12),
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.info,
                  icon: Icons.shopping_cart_outlined,
                  title: 'Total Pesanan',
                  value: state.dashboardAnalytic.overview.totalOrders
                      .toString(),
                ),
              ),
            ],
          ),
          const SpaceHeight(12),
          Row(
            children: [
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.warning,
                  icon: Icons.attach_money,
                  title: 'Rata-rata Pesanan',
                  value: state
                      .dashboardAnalytic
                      .overview
                      .averageOrderValue
                      .currencyFormatRpV2,
                ),
              ),
              const SpaceWidth(12),
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.primary,
                  icon: Icons.check_circle_outline,
                  title: 'Pesanan Sukses',
                  value: successfulOrders.toString(),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
