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

import '../../../../../../application/analytic/category_analytic_loader/category_analytic_loader_bloc.dart';
import '../../../../../../common/data/report_menu.dart';
import '../../../../../../common/extension/extension.dart';
import '../../../../../../common/theme/theme.dart';
import '../../../../../../domain/analytic/analytic.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';

class ReportCategorySection extends StatelessWidget {
  final ReportMenu menu;
  final CategoryAnalyticLoaderState state;
  final DateTime startDate;
  final DateTime endDate;
  const ReportCategorySection({
    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(
      () =>
          BlocBuilder<CategoryAnalyticLoaderBloc, CategoryAnalyticLoaderState>(
            builder: (context, state) {
              return ListView(
                padding: const EdgeInsets.all(16),
                children: [
                  ReportHeader(
                    menu: menu,
                    endDate: endDate,
                    startDate: startDate,
                  ),
                  const SpaceHeight(16),
                  _buildSummary(state),
                  Container(
                    margin: const EdgeInsets.only(top: 16),
                    decoration: BoxDecoration(
                      color: AppColor.white,
                      borderRadius: BorderRadius.circular(14),
                    ),
                    child: Column(
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            color: AppColor.disabled.withOpacity(0.8),
                            borderRadius: const BorderRadius.vertical(
                              top: Radius.circular(14),
                            ),
                          ),
                          padding: const EdgeInsets.symmetric(
                            horizontal: 20,
                            vertical: 16,
                          ),
                          child: Row(
                            children: [
                              Expanded(
                                flex: 3,
                                child: Text(
                                  'Kategori',
                                  style: AppStyle.lg.copyWith(
                                    fontWeight: FontWeight.w600,
                                    color: AppColor.textPrimary,
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 2,
                                child: Text(
                                  'Pendapatan',
                                  textAlign: TextAlign.center,
                                  style: AppStyle.lg.copyWith(
                                    fontWeight: FontWeight.w600,
                                    color: AppColor.textPrimary,
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 1,
                                child: Text(
                                  'Qty',
                                  textAlign: TextAlign.center,
                                  style: AppStyle.lg.copyWith(
                                    fontWeight: FontWeight.w600,
                                    color: AppColor.textPrimary,
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 1,
                                child: Text(
                                  'Order',
                                  textAlign: TextAlign.center,
                                  style: AppStyle.lg.copyWith(
                                    fontWeight: FontWeight.w600,
                                    color: AppColor.textPrimary,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          decoration: const BoxDecoration(
                            color: AppColor.white,
                            borderRadius: BorderRadius.vertical(
                              bottom: Radius.circular(14),
                            ),
                          ),
                          child: ListView.builder(
                            padding: EdgeInsets.zero,
                            itemCount: state.categoryAnalytic.data.length,
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemBuilder: (context, index) {
                              return _buildCategoryItem(
                                state.categoryAnalytic.data[index],
                                index,
                                state.categoryAnalytic.data.length,
                              );
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              );
            },
          ),
      (f) => AnalyticErrorStateWidget(
        failure: f,
        menu: menu,
        onRefresh: () {
          context.read<CategoryAnalyticLoaderBloc>().add(
            CategoryAnalyticLoaderEvent.fetched(
              startDate: startDate,
              endDate: endDate,
            ),
          );
        },
      ),
    );
  }

  Widget _buildCategoryItem(
    CategoryAnalyticItem category,
    int index,
    int totalCount,
  ) {
    final isEven = index % 2 == 0;
    final isLast = index == totalCount - 1;

    return Container(
      decoration: BoxDecoration(
        color: isEven ? AppColor.white : AppColor.disabled.withOpacity(0.3),
        borderRadius: BorderRadius.vertical(
          bottom: Radius.circular(isLast ? 14 : 0),
        ),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
      child: Row(
        children: [
          Expanded(
            flex: 3,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  category.categoryName,
                  style: AppStyle.lg.copyWith(
                    fontWeight: FontWeight.w500,
                    color: AppColor.textPrimary,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '${category.productCount} produk',
                  style: AppStyle.sm.copyWith(color: AppColor.textSecondary),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 2,
            child: Column(
              children: [
                Text(
                  category.totalRevenue.currencyFormatRpV2,
                  textAlign: TextAlign.center,
                  style: AppStyle.md.copyWith(
                    fontWeight: FontWeight.w500,
                    color: AppColor.success,
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 1,
            child: Text(
              '${category.totalQuantity}',
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w500,
                color: AppColor.textPrimary,
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Text(
              '${category.orderCount}',
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w500,
                color: AppColor.textPrimary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Row _buildSummary(CategoryAnalyticLoaderState state) {
    return Row(
      children: [
        Expanded(
          child: ReportSummaryCard(
            color: AppColor.success,
            icon: Icons.trending_up,
            title: 'Total Pendapatan',
            value: state.categoryAnalytic.totalRevenue.currencyFormatRpV2,
          ),
        ),
        const SpaceWidth(12),
        Expanded(
          child: ReportSummaryCard(
            color: AppColor.info,
            icon: Icons.shopping_cart_outlined,
            title: 'Total Item Terjual',
            value: "${state.categoryAnalytic.totalQuantity} pcs",
          ),
        ),
        const SpaceWidth(12),
        Expanded(
          child: ReportSummaryCard(
            color: AppColor.primary,
            icon: Icons.receipt_outlined,
            title: 'Total Pesanan',
            value: state.categoryAnalytic.totalOrders.toString(),
          ),
        ),
      ],
    );
  }
}
