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

import '../../../../../../application/analytic/product_analytic_loader/product_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 ReportProductSection extends StatelessWidget {
  final ReportMenu menu;
  final ProductAnalyticLoaderState state;
  final DateTime startDate;
  final DateTime endDate;
  const ReportProductSection({
    super.key,
    required this.state,
    required this.menu,
    required this.startDate,
    required this.endDate,
  });

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

    return state.failureOption.fold(
      () => Column(
        children: [
          Expanded(
            child: RefreshIndicator(
              onRefresh: () {
                context.read<ProductAnalyticLoaderBloc>().add(
                  ProductAnalyticLoaderEvent.fetched(
                    startDate: startDate,
                    endDate: endDate,
                  ),
                );
                return Future.value();
              },
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    ReportHeader(
                      menu: menu,
                      endDate: endDate,
                      startDate: startDate,
                    ),
                    Container(
                      height: 90,
                      margin: const EdgeInsets.only(top: 16),
                      child: ListView.builder(
                        scrollDirection: Axis.horizontal,
                        itemCount: state.productAnalytic.categories.length,
                        itemBuilder: (context, index) {
                          final category =
                              state.productAnalytic.categories[index];
                          return Container(
                            width: 220,
                            padding: EdgeInsets.only(
                              right:
                                  index ==
                                      state.productAnalytic.categories.length -
                                          1
                                  ? 0
                                  : 12,
                            ),
                            child: ReportSummaryCard(
                              color: AppColor.primary,
                              icon: Icons.category_outlined,
                              title: category.categoryName,
                              value: category.totalRevenue.currencyFormatRpV2,
                              subtitle: "${category.productCount} Item",
                            ),
                          );
                        },
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 16),
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: AppColor.white,
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Produk Berkinerja Terbaik',
                                style: AppStyle.lg.copyWith(
                                  fontWeight: FontWeight.w600,
                                  color: AppColor.textPrimary,
                                ),
                              ),
                              Container(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 8,
                                  vertical: 4,
                                ),
                                decoration: BoxDecoration(
                                  color: AppColor.primary.withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(4),
                                  border: Border.all(
                                    color: AppColor.primary,
                                    width: 1,
                                  ),
                                ),
                                child: Text(
                                  'Berdasarkan Pendapatan',
                                  style: AppStyle.xs.copyWith(
                                    fontWeight: FontWeight.w500,
                                    color: AppColor.primary,
                                    fontSize: 10,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const SpaceHeight(12),
                          ListView.builder(
                            itemCount: state.productAnalytic.data.length,
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemBuilder: (context, index) {
                              final product = state.productAnalytic.data[index];
                              return _buildProductItem(
                                rank: index + 1,
                                product: product,
                                isTopPerformer:
                                    product ==
                                    state.productAnalytic.bestProduct,
                                categoryColor: AppColor.primary,
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          _buildBottomSummary(),
        ],
      ),
      (f) => AnalyticErrorStateWidget(
        failure: f,
        menu: menu,
        onRefresh: () {
          context.read<ProductAnalyticLoaderBloc>().add(
            ProductAnalyticLoaderEvent.fetched(
              startDate: startDate,
              endDate: endDate,
            ),
          );
        },
      ),
    );
  }

  Widget _buildBottomSummary() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
      decoration: const BoxDecoration(color: AppColor.white),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: AppColor.success.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: AppColor.success, width: 1),
            ),
            child: Row(
              children: [
                const Icon(Icons.star, color: AppColor.success, size: 16),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    '${state.productAnalytic.bestProduct.productName} memimpin dengan ${state.productAnalytic.bestProduct.quantitySold} unit terjual dan pendapatan ${state.productAnalytic.bestProduct.revenue.currencyFormatRpV2}',
                    style: AppStyle.sm.copyWith(
                      fontWeight: FontWeight.bold,
                      color: AppColor.success,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProductItem({
    required int rank,
    required ProductAnalyticItem product,
    required bool isTopPerformer,
    required Color categoryColor,
  }) {
    return Container(
      margin: const EdgeInsets.only(bottom: 10),
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: isTopPerformer
            ? AppColor.primary.withOpacity(0.1)
            : AppColor.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: isTopPerformer ? AppColor.primary : AppColor.border,
          width: isTopPerformer ? 2 : 1,
        ),
      ),
      child: Row(
        children: [
          // Rank Badge
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: isTopPerformer ? AppColor.primary : AppColor.textSecondary,
              borderRadius: BorderRadius.circular(14),
            ),
            child: Center(
              child: Text(
                '$rank',
                style: AppStyle.sm.copyWith(
                  fontWeight: FontWeight.w700,
                  color: Colors.white,
                ),
              ),
            ),
          ),

          const SpaceWidth(12),

          // Product Info
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Text(
                        product.productName,
                        style: AppStyle.md.copyWith(
                          fontWeight: FontWeight.w600,
                          color: AppColor.textPrimary,
                        ),
                      ),
                    ),
                    Row(
                      children: [
                        if (isTopPerformer)
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 6,
                              vertical: 2,
                            ),
                            margin: const EdgeInsets.only(right: 8),
                            decoration: BoxDecoration(
                              color: AppColor.success,
                              borderRadius: BorderRadius.circular(3),
                            ),
                            child: Text(
                              'BEST',
                              style: AppStyle.xs.copyWith(
                                fontSize: 8,
                                fontWeight: FontWeight.w700,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        Text(
                          product.revenue.currencyFormatRpV2,
                          style: AppStyle.md.copyWith(
                            fontWeight: FontWeight.w700,
                            color: AppColor.primary,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                const SpaceHeight(6),
                Row(
                  children: [
                    // Category Badge
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 6,
                        vertical: 2,
                      ),
                      decoration: BoxDecoration(
                        color: categoryColor.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        product.categoryName,
                        style: AppStyle.xs.copyWith(
                          fontSize: 9,
                          fontWeight: FontWeight.w500,
                          color: categoryColor,
                        ),
                      ),
                    ),

                    const SizedBox(width: 8),

                    // Stats
                    Expanded(
                      child: Text(
                        '${product.quantitySold} units • ${product.orderCount} orders • Avg ${product.averagePrice.round()}',
                        style: AppStyle.xs.copyWith(
                          fontSize: 11,
                          fontWeight: FontWeight.w400,
                          color: AppColor.textSecondary,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
