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

import '../../../../../../application/analytic/payment_method_analytic_loader/payment_method_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 ReportPaymentMethodSection extends StatelessWidget {
  final ReportMenu menu;
  final PaymentMethodAnalyticLoaderState state;
  final DateTime startDate;
  final DateTime endDate;
  const ReportPaymentMethodSection({
    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(
        onRefresh: () {
          context.read<PaymentMethodAnalyticLoaderBloc>().add(
            PaymentMethodAnalyticLoaderEvent.fetched(
              startDate: startDate,
              endDate: endDate,
            ),
          );
          return Future.value();
        },
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            ReportHeader(menu: menu, endDate: endDate, startDate: startDate),
            _buildSummary(),
            Container(
              padding: const EdgeInsets.all(12),
              margin: const EdgeInsets.only(top: 16),
              decoration: BoxDecoration(
                color: AppColor.white,
                borderRadius: BorderRadius.circular(14),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Rincian Metode Pembayaran',
                    style: AppStyle.lg.copyWith(
                      fontWeight: FontWeight.w600,
                      color: AppColor.textPrimary,
                    ),
                  ),

                  const SpaceHeight(16),

                  ...List.generate(state.paymentMethodAnalytic.data.length, (
                    index,
                  ) {
                    final item = state.paymentMethodAnalytic.data[index];
                    return Padding(
                      padding: const EdgeInsets.only(bottom: 16),
                      child: _buildPaymentCard(item),
                    );
                  }),
                ],
              ),
            ),
          ],
        ),
      ),
      (f) => AnalyticErrorStateWidget(
        failure: f,
        menu: menu,
        onRefresh: () {
          context.read<PaymentMethodAnalyticLoaderBloc>().add(
            PaymentMethodAnalyticLoaderEvent.fetched(
              startDate: startDate,
              endDate: endDate,
            ),
          );
        },
      ),
    );
  }

  Container _buildPaymentCard(PaymentMethodAnalyticItem item) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: AppColor.border, width: 1),
      ),
      child: Row(
        children: [
          // Payment Method Icon
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: AppColor.primary,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: AppColor.primary, width: 1),
            ),
            child: const Icon(Icons.money, color: AppColor.white, size: 20),
          ),

          const SpaceWidth(16),

          // Payment Method Details
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      item.paymentMethodName,
                      style: AppStyle.md.copyWith(
                        fontWeight: FontWeight.w600,
                        color: AppColor.textPrimary,
                      ),
                    ),
                    Text(
                      "${item.percentage.round()}%",
                      style: AppStyle.md.copyWith(
                        fontWeight: FontWeight.bold,
                        color: AppColor.primary,
                      ),
                    ),
                  ],
                ),

                const SpaceHeight(8),

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      item.totalAmount.currencyFormatRpV2,
                      style: AppStyle.md.copyWith(
                        fontWeight: FontWeight.w500,
                        color: AppColor.textSecondary,
                      ),
                    ),
                    Text(
                      '${item.orderCount} Pesanan',
                      style: AppStyle.md.copyWith(
                        fontWeight: FontWeight.w500,
                        color: AppColor.textSecondary,
                      ),
                    ),
                  ],
                ),

                const SpaceHeight(8),

                // Progress Bar
                Container(
                  width: double.infinity,
                  height: 6,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade200,
                    borderRadius: BorderRadius.circular(3),
                  ),
                  child: FractionallySizedBox(
                    alignment: Alignment.centerLeft,
                    widthFactor: (item.percentage / 100), // 100%
                    child: Container(
                      decoration: BoxDecoration(
                        color: AppColor.primary,
                        borderRadius: BorderRadius.circular(3),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Padding _buildSummary() {
    return Padding(
      padding: const EdgeInsets.only(top: 16),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.success,
                  icon: Icons.trending_up,
                  title: "Pendapatan Total",
                  value: state
                      .paymentMethodAnalytic
                      .summary
                      .totalAmount
                      .currencyFormatRpV2,
                ),
              ),
              const SpaceWidth(12),
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.info,
                  icon: Icons.shopping_cart_outlined,
                  title: 'Jumlah Pesanan',
                  value: state.paymentMethodAnalytic.summary.totalOrders
                      .toString(),
                ),
              ),
            ],
          ),
          const SpaceHeight(12),
          Row(
            children: [
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.success,
                  icon: Icons.attach_money_outlined,
                  title: "Nilai Rata Rata",
                  value: state
                      .paymentMethodAnalytic
                      .summary
                      .averageOrderValue
                      .currencyFormatRpV2,
                ),
              ),
              const SpaceWidth(12),
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.info,
                  icon: Icons.wallet_outlined,
                  title: 'Jumlah Pembayaran',
                  value: state.paymentMethodAnalytic.summary.totalPayments
                      .toString(),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
